Rony Rony - 1 month ago 12
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?

Thanks

Answer

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) {
    
            eval(mlHTTP.responseText);
        }
    
    });
    
  3. Write your PHP code to grab data and print JS code (it must be valid javscript !) :

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

    alert(myarray.length); 
    

hope this helps.