Rocket Rocket - 4 months ago 10
JSON Question

Jquery - parsing returned AJAX Data into existing for fields

I'm using the following to read data from a database.

$.ajax({
url: 'loader.php',
success: function(data) {
console.log(data)
}
});


This is returning :
[{"name":"Bob Green","ID":"1234"}]


The data returned is being created by php and the format is simply being manually created and then echo'd back. I can change how this is done it it make things easier.

Once I have the
data
returned I'd like to update an existing form. The form field names match the keys in the returned data. Most are text fields, but there are a couple of dropdown lists and checkboxes.

I have tried the following which I found on another question, but that didn't work.

function populate(frm, data) {
$.each(data, function(key, value){
var $ctrl = $('[name='+key+']', frm);
switch($ctrl.attr("type"))
{
case "text" :
case "hidden":
$ctrl.val(value);
break;
case "radio" : case "checkbox":
$ctrl.each(function(){
if($(this).attr('value') == value) { $(this).attr("checked",value); } });
break;
default:
$ctrl.val(value);
}
});
}


When I console logged the
key & value
it showed the data as indiviual letters not
name:Bob Green
&
ID:1234


Can someone point me in the right direction.

Thanks

Answer

It's possible that your php code return the data as string without the relevant header that tells your browser to handle the result is json.

To do so you can use:

$data = /* Some variable that contains your data */;
header('Content-Type: application/json');
echo json_encode($data);

Another option is to tell your ajax request to handle the result of the request as json:

$.ajax({
    url: 'loader.php',
    dataType: 'json', // This way jquery will try to handle the returned data as json object
    success: function(data) {
        console.log(data);
        console.log(data);
    } 
});

Note that these are not the same:

console.log('[{"name":"Bob Green","ID":"1234"}]')
    [{"name":"Bob Green","ID":"1234"}]

console.log([{"name":"Bob Green","ID":"1234"}])
    [Object]:
        ID: "1234"
        name: "Bob Green"