1

I'm doing a simple javascript application. It involves several items in different tables stored using MYSQL.

The user has to choose an item from a table. Based on his choice he can choose a second item from another table, then a third item from a third table based on his former choices, and continues on the same pattern.

I just have one simple problem that I don't know a simple method to import tables from MYSQL into javascript arrays!!

Any ideas of how to do that?!

3 Answers 3

3

I find the easiest way to send MySQL data to Javascript using PHP is as a JSON object using jQuery.

In PHP: connect to your db, do your query. Assuming you store your results in an array called $results, just do:

echo json_encode($results);

This will format the output as a JSON object.

This is the javascript side (using jquery) - note the GET var I'm passing as an example, in case you need that for the tablename or id or whatever:

$.getJSON( 'json.php', { some_get_var: 1 }, function(data){
    var i, total = data.length;
    for ( i = 0; i < total; ++i ) {
        // do whatever with your data, like populate a select.
        // your data would be like:
        // data[i].fieldname
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0
json_encode($arr)

The array you want to return, wrap it in the json_encode method. If you are using jQuery it will automatically convert it to an object in the success handler

Comments

0

You can't directly access your database from Javascript. You'll have to use PHP to render the JS code necessary for loading those arrays.

For that, you can use the json_encode function. You could also do it by ajax, that way, you can separate your php code from your JavaScript code and keep it organized.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.