Rony Rony - 1 year ago 83
Javascript Question

Load Javascript array with MYSQL database data

suppose i have an javascript array "userName".I want to load it from a database table named "user".

Can anyone help with idea or sample code?


Answer Source

Use ajax and php as an intermediate :

  1. Define an empty JS array :

    var myarray = new Array();

  2. use ajax to call your php script, javascript will eval the output by PHP (note this uses prototype library):

     new Ajax.Request('myfile.php', {
        onSuccess : function(xmlHTTP) {
  3. Write your PHP code to grab data and print JS code (it must be valid javscript !) :

    $i=0; $q=mysql_query('select ..');
        echo "myarray[".$i."]='".$row['data']."';";
  4. You can check that your Js array contains data :


hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download