IEnumerable
IEnumerable

Reputation: 3790

jQuery Ajax response fails with invalid characters

Im calling an ajax function and getting back some JSON data.

Ive looked at the data and it all looks like the server is responded as it should

However FireBug reports an issue and my program fails.

This is JSON the response

{"status":"success","message":"item was added to cart OK","cost":38.5,"qty":11}

This is the error from firebug

SyntaxError: JSON.parse: unexpected character


return window.JSON.parse( data );

Here is a screenshot of the callstack;enter image description here

Here is the Javascript

$('.submitform').click( function() {
$.post( 'myrll.com/cart/add', $('[name=myform]').serialize(), function(data) {
    var new_data = jQuery.parseJSON(data);

    if(new_data.status=='error')
    {
        alert(new_data.message);
    }
    else
    {
        add_item_to_cart(new_data.cost,new_data.qty);
    }
},
'json' // I expect a JSON response
);

});

And finally my php server script

    $sys_message['status'] = 'success'
    $sys_message['qty'] = $total_items; //this is INT
    $sys_message['cost'] = $this->sfcart->total_cost_contents(); //FLOAT
    $sys_message['message'] = $message; //string

    echo json_encode($sys_message);return;

Upvotes: 4

Views: 9305

Answers (3)

Alex
Alex

Reputation: 11245

1) It fails at response = conv( response ); - string probably?

2) Make sure the Content-type is set to application/json.

Upvotes: 0

IEnumerable
IEnumerable

Reputation: 3790

I removed this line and it worked: Im not sure why, possible conflict with parse ? If anyone can explain this than that will be helpful to myself and others

 ,'json' // I expect a JSON response

Upvotes: 0

Pathik Gandhi
Pathik Gandhi

Reputation: 1344

you are assigning string to the response param not json object. thaty it give you an error. assign direct object to the response param instead of string

You current Response (string coz there is a "" around this)

response = "{"status":"success","message":"item was added to cart OK","cost":38.5,"qty":11}"

You need Response (object no quotation)

response = {"status":"success","message":"item was added to cart OK","cost":38.5,"qty":11}

with out Quotation ("). and then try it works

Upvotes: 3

Related Questions