1

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

5 Answers 5

2

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. :)

Sign up to request clarification or add additional context in comments.

3 Comments

Awesome, perfect for what I was trying to achieve. Many thanks!
BTW, you get an array from php if you will not provide values: json_encode(['one', 'two']); -> ["one","two"], otherwise you get an object.
@starikovs : You're right. However, my answer was in the context of what the OP is getting from the server. Perhaps, I should use this comment of yours as an opportunity to improve my English. :) When I read my answer again I realized that the first sentence from the Addendum is ambigous and may lead readers to think that one can never get an array from PHP. Thank you for your feedback. :)
1

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.

Comments

1

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.

Comments

0

{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();
        };
    });
});

Comments

0

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();
        }
    });
});

Comments

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.