Bill Greer
Bill Greer

Reputation: 3156

How to handle json repsonse in Ajax request

I have the following ajax request:

$.ajax({
                    url: '/DrawMandrel/RemoveFromList',
                    type: 'POST',
                    data: JSON.stringify({ "ID": ID }),
                    dataType: 'text',
                    contentType: 'application/json;charset=utf-8',
                    traditional: true,
                    success: function (data) {
                        alert(data);

                        if (data == "result:success") {
                            alert('REMOVED');
                        }
                        else {
                            alert('ah oh!');
                        }
                    },
                });

I am sending the data to an ASP.NET MVC controller and I am getting a response like this:

{"result":"success"}
Content-Type    application/json; charset=utf-8

I cannot figure out why I am getting the alert('ah oh').

Upvotes: 0

Views: 65

Answers (3)

MaTya
MaTya

Reputation: 782

you have to write this statement for your ajax request whether it is fail or not

if (data.result == "success") 
{
     // do what u want
}

Upvotes: 1

Michael Stewart
Michael Stewart

Reputation: 411

Technically the raw string you getting would be '{"result":"success"}'. But you can also change your dataType attribute to be "json" then use

if(data.result == "success") 

Upvotes: 3

Selman Genç
Selman Genç

Reputation: 101681

You should change your if statement like this:

if (data.result == "success") 
{
      alert('REMOVED');
}

Upvotes: 4

Related Questions