TheRealPapa
TheRealPapa

Reputation: 4539

jQuery read array from ajax response

This is so basic but I have now been stuck for over an hour as I cannot find an exact example. Thanks for any links you can provide.

I build the JSON in php like this:

return json_encode(['error' => 'customer number not found']);

It returns a basic array that looks like this (from inspect):

{error: 'customer number not found'}

I have an Ajax/getJSON call via jQuery:

   $.getJSON( url, function( response ) {

        $.each(response[0], function(key, value) {

            // Check response for errors
            if (key == "error") {

                // display message
                $(message_area).innerHTML = value;

                // Show the error message
                $(message_area).show();

            };

        });

    });

I just want to check the first value, then show the second and display the container. The above code gives me

Uncaught TypeError: Cannot read property 'length' of undefined

Upvotes: 1

Views: 2037

Answers (5)

iamawebgeek
iamawebgeek

Reputation: 2865

I would prefer to do like so:

$.getJSON( url, function( response ) {
  for(var key in response) {
    if(!response.hasOwnProperty(key)) continue;
    if(key === "error") {
      // display message
      $(message_area).innerHTML = response[key];
      // Show the error message
      $(message_area).show();
      break; // exit the loop!
    }
  }
});

In this case it would loop through the keys of an object, in case of JSON it would work great.

Upvotes: 1

AdityaParab
AdityaParab

Reputation: 7100

Instead of using $.each, a better way of doing the same thing (given the current scenario) is to check if response.error exists. :)

Change your code to something like

 $.getJSON( url, function( response ) {
    if (response.error){
        $(message_area).html(response.error);
        // Show the error message
        $(message_area).show();
    } else{
        // No error, do your success stuff
    }
 });

ADDENDUM:

First things first, the response that you get from PHP is NOT an array. It is an object. Checking for existing properties in an object is more sensible and inuitive way of doing things than looping through the object's key and values.

Second - your $(message_area) is a jQuery object. You can not directly set innerHTML for jQuery object the way you have set it. The way to do it, assuming message_area selects only ONE element, is $(message_area)[0].innerHTML = "your value";

But if you're using jQuery, it is more sensible to just conform to jQuery's ethos, so what you should actually be doing is

$(message_area).html('your value');

Hope that helps. :)

Upvotes: 2

Peter
Peter

Reputation: 447

In PHP:

return json_encode(array('error' => 'customer number not found'));

In your jQuery .done() function:

.done(function(response){
    response = $.parseJSON(response);
    $.each(response, function(key, value) {
        if(key == 'error') {
            // display message
            $(message_area).html(value);

            // Show the error message
            $(message_area).show();
        }
    });
});

Upvotes: 0

Pete
Pete

Reputation: 4622

Try response instead of response[0]

You were just accessing the first element of the array not looping over it.

The length error was because the single first item didn't have a length.

Upvotes: 1

Satpal
Satpal

Reputation: 133453

{error: 'customer number not found'} is not an array, its a simple object. So you need to use response instead of response[0].

Additionally innerHTML is property of DOM element not jQuery object. Use .html() function when setting HTML using jQuery object.

Use

$.getJSON( url, function( response ) {
    //Remove [0]
    $.each(response, function(key, value) {
        if (key == "error") {

            //Use .html() method
            $(message_area).html(value);

           $(message_area).show();
        };
    });
});

Upvotes: 0

Related Questions