1

I have a button on a pge thats fetches json data from a php page,

the data seems to arrive ok but i have gone through hundreds of examples and i just cant seem to reference the returned data, here is my script:

EDITED SCRIPT from previous comments

 $('#geo_batch').click(function (){
            var ajax_load = "<label><img src='/images/icons/loadinfo.gif' alt='saving location...' /> Loading data...</label>";
            $("#batch_detail").html(ajax_load);
            $('#batch_buttons').hide();
            var form = $("form"); //Grab the form element from the DOM 
            //alert(form.serialize());
            var mydata = form.serialize();
            $.ajax({  
                type: "POST",  
                url: 'geo_getupdate_list.php', 
                data: mydata,  
                datatype: 'json',
                success: function(dat) {
                    alert('dat:'+ typeof dat ) //RETURNS STRING
                    //alert(dat.location[0].id_mdt); //RETURNS UNDEFINED
                    // Cache the batch_detail element
                    var $detail = $("#batch_detail").html('<label>Locations have been retrieved:<br>' + dat + '<label>');
                    $('#batch_buttons').show();
                    // Instead of several .append() calls on the same element, create a 
                    //   single string, and do one.
                    var appendString = '';
                    for(var key in dat) { alert(key); return false; };
                    /*for(i=0; i < count; i++){
                        appendString += 'display address: ' + data.location[i].displayaddr_mdt + 'flag: ' + data.location[i].flag_mdt;
                    }*/
                    $detail.append(appendString);
                }, 
                error: function(dat) { //Triggered if an error communicating with server   
                     //alert('fail');
                     $("#batch_detail").html('<label>There was an error: '+dat+'<label>');  
                     $('#batch_buttons').show();
                }
            });  
            return false; //Ignore the default behavior of the button click  
        }); 

the json that is returned is:

{"location":[{"id_mdt":"5","idetp_mdt":"1","name_mdt":null,"geoaddr_mdt":null,"displayaddr_mdt":"31a Arundel Gardens London W11 2LW","telephone_mdt":null,"email_mdt":null,"website_mdt":"http:\/\/","lat_mdt":"51.513561","lng_mdt":"-0.206519","active_mdt":"1","flag_mdt":"1","id_etp":"1","name_etp":"Stockist","icon_etp":null},{"id_mdt":"1","idetp_mdt":"1","name_mdt":null,"geoaddr_mdt":null,"displayaddr_mdt":"via todde 29 Ales Sardegna 09091","telephone_mdt":null,"email_mdt":null,"website_mdt":"http:\/\/","lat_mdt":"39.7670964","lng_mdt":"8.813689","active_mdt":"1","flag_mdt":"1","id_etp":"1","name_etp":"Stockist","icon_etp":null},{"id_mdt":"4","idetp_mdt":"1","name_mdt":null,"geoaddr_mdt":null,"displayaddr_mdt":"31a Arundel Gardens London W11 2LW","telephone_mdt":null,"email_mdt":null,"website_mdt":"http:\/\/","lat_mdt":"51.513561","lng_mdt":"-0.206519","active_mdt":"1","flag_mdt":"1","id_etp":"1","name_etp":"Stockist","icon_etp":null},{"id_mdt":"3","idetp_mdt":"1","name_mdt":null,"geoaddr_mdt":null,"displayaddr_mdt":"31a Arundel Gardens London W11 2LW","telephone_mdt":null,"email_mdt":null,"website_mdt":"http:\/\/","lat_mdt":"51.513561","lng_mdt":"-0.206519","active_mdt":"1","flag_mdt":"1","id_etp":"1","name_etp":"Stockist","icon_etp":null},{"id_mdt":"6","idetp_mdt":"1","name_mdt":null,"geoaddr_mdt":null,"displayaddr_mdt":"31a Arundel Gardens London W11 2LW","telephone_mdt":null,"email_mdt":null,"website_mdt":null,"lat_mdt":"51.513561","lng_mdt":"-0.206519","active_mdt":"1","flag_mdt":"1","id_etp":"1","name_etp":"Stockist","icon_etp":null},{"id_mdt":"7","idetp_mdt":"1","name_mdt":"Test","geoaddr_mdt":null,"displayaddr_mdt":"31a Arundel Gardens London W11 2LW","telephone_mdt":null,"email_mdt":null,"website_mdt":null,"lat_mdt":"51.513561","lng_mdt":"-0.206519","active_mdt":"1","flag_mdt":"1","id_etp":"1","name_etp":"Stockist","icon_etp":null}]}

how do i access the data in the array?

i have tried so many examples on here and other places and i cant get any to work. I think it may be to do with the returned json object it has [ symbols in it which i think is wrong?

the php i have to generate the json is as follows:

//have defined a recordset called $rs_locations
$rows = array();
while($r = mysql_fetch_assoc($rs_locations)) {
    $rows[] = $r;
}
$jsondata = json_encode($rows);
// trying to strip out the [ ] brackets but doesn't work
str_replace ("[", "", $jsondata);
str_replace ("]", "", $jsondata);
echo($jsondata);

any ideas anyone, i am so stuck, thanks

3
  • At the beginning of the success: callback, what happens if you do alert(data.location[0].id_mdt); ? Commented Nov 7, 2010 at 15:18
  • Verify your JSON returned. Are you certain it is {"location": ? Or is it {"locations": or {"rows": instead? Commented Nov 7, 2010 at 15:25
  • 1
    I'd highly suggest you to NOT prefix regular variables with $ - that should be used only for jQuery objects, e.g. stuff like var $this = $(this);. Additionally you should not make local variables global, i.e. declare them with the var keyword. So, replace $locdata = data; with var locdata = data;. Commented Nov 7, 2010 at 15:54

2 Answers 2

3

EDIT: Your dataType property is mis-spelled.

It should be dataType, not datatype.

Also, try changing the data parameter to some other name, like dat. I've seen problems with that before when your $.ajax() call has the data property set.

success: function( dat ) {
   // Then change all references from data to dat

Try this for your success: callback.

You were fetching the same #batch_detail element several times and continuously calling .append() on that element.

This way you cache a reference to the element, create a single String to append, and then do the append once after the loop is done.

The specific trouble you were having was that you needed to reference the Array stored at data.location directly.

 success: function(dat) {
     // Cache the batch_detail element
     var $detail = $("#batch_detail").html('<label>Locations have been retrieved:<br>' + dat + '<label>');
     $('#batch_buttons').show();
     var count = dat.location.length - 1;
       // Instead of several .append() calls on the same element, create a 
       //   single string, and do one.
     var appendString = '';
     for(i=0; i < count; i++){
         appendString += 'display address: ' + dat.location[i].displayaddr_mdt + 'flag: ' + dat.location[i].flag_mdt;
     }
     $detail.append( appendString );
 }, 
Sign up to request clarification or add additional context in comments.

13 Comments

ahhhh nice! i was wondering what all the jqueryfy errors meant in firebug!!, thanks for that, maybe it would be better to store the original html in the appendstring and do a .html(appendstring). thats good thanks but the data.location still returns indefined, are you sure its not to do with the '[' and ']' crackets in the json?
@Dizzy - The [] are fine. They denote an Array. If data.location is undefined, then check to make sure that location is the correct key. It would seem like locations (plural) may be more likely.
@Dizzy - Invalid JSON is now being returned. You have an extra set of quotation marks around the [...] portion of the JSON. So instead of {"location":"[{...}]"} it should look like {"location":[{...}]} This is why it is going to the error: callback.
@Dizzy - Looks like the proper JSON is now being returned. Just be sure to put the count variable back in there, and update all occurrences of data to dat. You missed a couple. With those changes, I have it working on my end. I'll update my answer to reflect the changes.
@Dizzy - Glad I could help. If you're not doing it now, I'd highly recommend using console.log() along with Safari/Chrome/Firefox developer tools to observe data that seems to be giving you trouble.
|
0

If I get your script right, you have to get the location array from data first:

var locations = data.location;
for(var location in locations) {
    console.debug(locations[location]);
}

10 Comments

so [ ] characters are ok in the json then?
yeah. for loops through Objects as well. Key would be an IntegerOR String then. Btw: Accessing Object-Values is possible through obj['key'] or obj.key
var locations = data.location; for(var location in locations) { /// do stuff ("#batch_detail").append(this['id_mdt']); }; this does not output anything???
try var locations = data.location; for(var location in locations) { var current = locations[location]; $("#batch_detail").append(current.id_mdt); };
var locations = data.location; alert(locations); for(var location in locations) { /// do stuff $("#batch_detail").append(location+' is the location'); }; returns undefined.... /// do stuff $("#batch_detail").append(location+' is the location');};
|

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.