0

Here is my success function for my ajax request via jquery,

success: function(response) {

    if (response.error == undefined) {

    alert(response);
    }
$('#' + id).after('<div id="emailMsg" class="error">' + response.error + '</div>');

}

Because the value is coming back as undefined it alerts me the returned JSON which is...

{"error":true}

Why is this happening, surely when I call response.error I should get either true or false.

UPDATE

Variable is returning as a string and not boolean, my json_encode();

    if (!$q -> rowCount()) {

    echo json_encode(array('error' => false));
}
else {

    echo json_encode(array('error' => true));
}

2 Answers 2

1

You might want to try adding the dataType: 'json' parameter to your $.ajax call. That will ensure that jQuery will take care of making the response an object for you.

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

Comments

0

You need to first parse the JSON from a string into a JavaScript object.

This can be done with JSON.parse(response). In old browsers that don't have native JSON, eval(response) works too, but is less secure.

5 Comments

Just tried it, adding it in before the if statement, does not work :/
Try alert(typeof response); and see what it gives you.
It returns string, I have edited my question to show you my json_encode();
Okay, and are you doing response = JSON.parse(response);?
Thanks for your help Tarek Fadel's solution worked just fine.

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.