How to return a JSON formatted array from an ajax query?

advertisements

I am building two interdependent drop-down lists, where the options of the second list (the 'sensor_list') depend on what option was chosen in the first list (the 'node_list'). To do that I attach a listener to the 'node_list' and when an option is selected I make an ajax request in order to load the data for the 'sensor_list'. All data, for both lists, is loaded from the same database.

In that ajax request I access the 'sensors' table on the database and I get the 'Sensor_ID' and the 'Sensor_name' of the sensors I need. What I want, now, is to pass this data back to the 'success' function of the request. Is this done automatically? Do I need to pass any arguments to the function?

Also, I need the returned data to be in JSON format, for later use. How is this possible?

Here is the PHP code:

<?php

$con = mysql_connect("localhost", "root", "") or die('connection not made');
$db = mysql_select_db('name_of_db', $con) or die('db not selected');

$query = "SELECT SensorID,Variable FROM sensors WHERE SensorID IN (SELECT SensorID FROM nodesensors WHERE NodeID=node_selected)";
$result = mysql_query($query, $con) or die('query not made');

$options = json_encode($result);

?>

The 'node_selected' is the variable I pass with the request and it is the id of the node I selected in the first list.

The JavaScript is:

if (node_selected!=0 & node_selected!=null){
                $.ajax({
                    type: "POST",
                    url: "php/fetch_sensors.php",
                    data: node_selected,
                    success: function( options ){
                        ...//here I need the options to be in json format
                    }
                });
            }

'Options' is the data I want to be returned from the request and they are going to be the options for the 'sensor_list'.

Thanks a lot in advance!!


You can use the mysql_fetch_assoc function for that

Try changing the PHP code to the following:

<?php

$con = mysql_connect("localhost", "root", "") or die('connection not made');
$db = mysql_select_db('name_of_db', $con) or die('db not selected');

$query = "SELECT SensorID,Variable FROM sensors WHERE SensorID IN (SELECT SensorID FROM nodesensors WHERE NodeID=node_selected)";
$result = mysql_query($query, $con) or die('query not made');

$returnArray = array();
while($row = mysql_fetch_assoc($result)) {
    $returnArray[] = $row;
}

$options = json_encode($returnArray);

?>