Aaron Murray
Aaron Murray

Reputation: 2030

Handling responses from server side in jQuery ajax calls

I have a flaw in my code here and I am a little confused.

    $.ajax({
        type: 'POST',
        url: '/contact/index/add/',
        data: $("#addContact").serialize(),
        success: function(data, status, xhttp) {
            var response = eval ("[" + data + "]");
            console.log(response.msg);
            if ( response.success ){
                console.log( response.msg );
            } else {
                console.log( response.msg );
            }
        },
        dataType: "html"
    });

What I am looking for is on the response to be able to access an array (encoded in JSON format), however I am getting 'undefined' on the console.log( response.msg ) line

If I console.log(response) it shows (in firebug) as:

[Object { success=true, msg="test"}]

The request is sending back the following string:

{"success":true,"msg":"test"} Which is why I have to enclose the response in [ ] for the eval.

So what I am confused about is: how do I access the properties of said array.

Server side I have (php / zend framework)

echo Zend_Json_Encoder::encode(array('success'=>true,'msg'=>'test')); exit;

What do I need to do to access the key/values of the array as in the line

if( response.success ) { // do something }

Do I need to modify server side or javascript side?

Upvotes: 0

Views: 441

Answers (3)

FreeCandies
FreeCandies

Reputation: 1113

Try to switch the square bracket with the regular ones is the eval statement "(" + ...

Upvotes: 0

Anber
Anber

Reputation: 319

dataType: "json"

And don't use eval to parse json. Use jQuery.parseJSON

Upvotes: 1

hohner
hohner

Reputation: 11588

You need to specify the right dataType. You should specify JSON as the returned data type:

dataType: 'json'

Upvotes: 1

Related Questions