开发者

Creating a 2-dimensional jQuery array from a 2-dimensional PHP array with AJAX

开发者 https://www.devze.com 2023-03-18 07:09 出处:网络
I am using jQuery, AJAX and PHP to update the contents of a drop down box on an event.My code currently triggers the event and uses AJAX to call a PHP function which goes to the database and gets the

I am using jQuery, AJAX and PHP to update the contents of a drop down box on an event. My code currently triggers the event and uses AJAX to call a PHP function which goes to the database and gets the records associated with each member of the drop down.

I can currently return this 2-dimensional array (an array of records with an array of columns in each one) back to my jQuery function but I am at a loss as to how to convert the array into something which I can use.

jQuery code to ca开发者_高级运维ll AJAX:

    var element= $('select[name=elementName]');
    var data = 'inData=' + element.val();

    // Call AJAX to get the info we need to fill the drop downs by passing in the new ID
    $.ajax(
    {
        type: "POST",
        url: "ops.php",
        data: "op=getInfo&" + data,
        success: 
        function(outData) 
        {   
            // WHAT DO I DO HERE TO CONVERT 'outData' INTO A 2-DIMENSIONAL jQUERY ARRAY??
        },
        error:
        function()
        {

        }
    }); 

PHP code:

$sqlResults= mysql_query("SELECT data FROM table WHERE id='".$_POST['inData']."'"); 

$outData = array();

// Fill the data array with the results
while ($outData[]= mysql_fetch_array($sqlResults));

// echo the data to return it for use in the jQuery file
echo $outData;

The code posted is working fine - I just don't know how to read 'outData' in jQuery.

Thanks in advance for any help!!


Have you looked at json_encode?

echo json_encode($outData);

This will convert it into a json object that can be read by jQuery.


your looking for json

//php
echo json_encode($outData);

//javascript
$.ajax({
    type: "POST",
    url: "ops.php",
    data: "op=getInfo&" + data,
    dataType: "json",
    success: function(outData) {   
        console.log(outData); //this will be an object just like 
                              //your php associative array
    },
    error: function() {

    }
});


JSON can do the trick, but why not look at it from another angle?

If you're pinging PHP to get updated info, just have PHP output the option values you want in your select box. Then use the HTML return of jQuery AJAX to .html() the result into your select element.

There's a couple of different ways to skin a cat, and I would submit that this much easier approach is going to gain you extra time to do more jQuery wizardry.


jQuery can not read the echo of a PHP array. Use json_encode before you output it:

 echo json_encode($outData);

That's a format jQuery actually can parse as the response.

0

精彩评论

暂无评论...
验证码 换一张
取 消