read server side use client side

Discussion in 'PHP' started by gregd1, May 17, 2012.

  1. #1
    Hello,
    I am trying to read data from a database (server side/php), but use the variable from javascript (client side).

    Is it possible to fill a variable and use it client side?

    Do I have to hide the data in the form, then read it client side?

    How would one do this?

    thanks
     
    gregd1, May 17, 2012 IP
  2. HostPlanz

    HostPlanz Well-Known Member

    Messages:
    449
    Likes Received:
    34
    Best Answers:
    4
    Trophy Points:
    130
    #2
    Yes, using an AJAX library like jQuery, you can call the PHP script using JavaScript and store the returned value within a JavaScript variable for client side use. This method doesn't require you to refresh the page.

    Another method you can use is to fill the JavaScript variable when loading the page from the client side. To do this, the JavaScript must be inline JavaScript code written directly in the HTML source code of course.

    Another way is to enter the value into a hidden div when generating the HTML, and use JavaScript to read the value of that hidden div, and store it into a JavaScript variable for client side use. Not really a generic way to do so though.
     
    HostPlanz, May 17, 2012 IP
  3. UpscalePageRanking

    UpscalePageRanking Peon

    Messages:
    13
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Either you can read javascript or AJAX for such a requirement i would prefer to go with jquery to achive my goal of this kind
     
    UpscalePageRanking, May 18, 2012 IP
  4. Macaua

    Macaua Greenhorn

    Messages:
    24
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    13
    #4
    You can also use this method:
    PHP page will print the details from database in this format:
    
    <?php
    ..............
    $query = mysql_query('SELECT var1, var2, var3 FROM test WHERE test = 'test2');
    $res = mysql_fetch_row($query);
    
    echo 'db_var1='.$res[0].';db_var2='.$res[1].';db_var3=9;db_array=["3", "1", "2"];'
    
    Code (markup):
    and then request the php page with AJAX for example and evaluate the response.
    eval(xmlhttp.responseText);
    Code (markup):
    and then you can use the db_var1,db_var2,db_var3,db_array as normal javascript variables.
    Ex:
    <script type="text/javascript">
    var res = db_var1 + db_var2;
    alert(db_array[0] + db_var3);
    </script>
    
    Code (markup):
     
    Macaua, May 23, 2012 IP