SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Oct 2005
    0 Post(s)
    0 Thread(s)

    How To Open File And Load Contents Into A Variable


    in my PHP webpage I specify 3 files, like:

    $first_file = $_POST["one"];
    $second_file = $_POST["two"];
    $third_file = $_POST["three"];
    then I have a JS fuction, that in some points, needs to open each file and store the data of each file into a variable. My questions are 2:
    First, how do I save all data of each text file into a JS variable?
    Second, the part of the Js function which has these variables looks like this:

                            name: 'ONE',
                            color: 'blue',
                                     HERE WE SHOULD PLACE ALL DATA FROM FILE 1                     
                            name: 'TWO',
                            color: 'yellow',
                                     HERE WE SHOULD PLACE ALL DATA FROM FILE 2                     
                            name: 'THREE',
                            color: 'red',
                                        HERE WE SHOULD PLACE ALL DATA FROM FILE 3            
    Can you please help me, how I can put the data of each file into the correct place? I am new to JS and came across a helpful snipet of code, but I do not know how I can place my data inside the JS code so as to use them.

    Thanks a lot!

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Melbourne, AU
    17 Post(s)
    1 Thread(s)
    Hi ktsirig,

    Currently there is no clear/defined way to simply just inject things directly into JavaScript, however on that same note you can take advantage of your PHP code as pre-load the file then JSON encode the contents which can then be passed to the JavaScript code. See the below example which is loosely based of your above snippet.

    PHP Code:

    // Lets say the contents of the file is
    // $myArray = array('some value', array('another value', 'something else'), 'another thing');

    // Echo out the contents by wrapping them inside a <script> tag
    echo '<script type="text/javascript">
        var someFileContents = ' 
    json_encode($myArray) . '

    Code JavaScript:
    var series = [{data : someFileContents}];

    Of course that is just an example and it only assumes you are using the same type of code structure.
    Blog/Portfolio | Evolution Xtreme | DFG Design | DFG Hosting | CSS-Tricks | Stack Overflow | Paul Irish
    Having lame problems with your code? Let us help by using a jsFiddle


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts