Reza
Reza

Reputation: 880

get value of json returned data

Im doing a ajax call to retrieve data. the data is like this:

[{"id":"16","location_name":"agga"}]

this is because the php returns: echo json_encode($getLoc);

now in the javascript i need to change a input value to the json given ID and show the location name as a string in a div. How can i do this ?

what i tried:

data.id undefined data[0].id ..undefined data shows [{"id":"16","location_name":"agga"}]

then i tought maybe i need to loop so I did a jquery each... but that also returned nothing..

so now I came here,, what im I doing wrong?

code:

 $('#deliveryzip').on('change', function(){

    //Get zip first 4 chars
    var zip = $('#deliveryzip').val().substring(0,4);

        //Check if zip is integer
        if (isNaN(zip)) {
            //alert("zip klopt niet");
            return false;
        }

    //Get locationID from zipcode
    $.post(jssitebaseUrl+'/ajaxFile.php',{"zip":zip,"action":"getLocInfo"},function(data){

        $("#locInfo2").html(data); //shows the json returned object
        var show = true;
        return false;
    });   

Upvotes: 0

Views: 3700

Answers (4)

James
James

Reputation: 82096

json_encode returns a JSON string therefore you need to parse the JSON first into an object and then access the data i.e.

//Get locationID from zipcode
$.post(jssitebaseUrl+'/ajaxFile.php',{"zip":zip,"action":"getLocInfo"},function(data){
    var location = JSON.parse(data)[0]; // take first item as you appear to receive an array with 1 item
    $('#' + location.id).val(location.location_name); 
    var show = true;
    return false;
}); 

Upvotes: 0

Andrei Cristian Prodan
Andrei Cristian Prodan

Reputation: 1122

is data variable coming from the response a string in json format? if so then do:

obj = JSON.parse(data);
alert(obj[0].id);

Upvotes: 0

Hüseyin BABAL
Hüseyin BABAL

Reputation: 15550

You need to use JSON.parse. Quick example;

HTML:

<input type="text" name="test" id="test" value=""/>
<input type="button" name="update" id="update" value="Update"/>

JS:

$("#update").on("click", function() {
    $("#test").val(json[0].id);
})
var a = '[{"id":"16","location_name":"agga"}]';
var json = JSON.parse(a);

Here you can see demo : http://jsfiddle.net/y8TwH/

Upvotes: 1

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

try this pattern

        var json = [{ "id": "16", "location_name": "agga"}];
        alert(json[0]["id"]);
        alert(json[0]["location_name"]);
        $("#locInfo2").html(json[0]["location_name"]);

Upvotes: 0

Related Questions