Enrichman
Enrichman

Reputation: 11337

Handling json with $.ajax() in Jquery

Ok, here's the problem. I've an api that will give me back a json. With success I'll have back a nice list with some values, with an error I'll receive a json containing sone information about the error. I still haven't tried the "success" case because I still have to deploy the api but I think should work. The problem for now is the "error" case. Using $.ajax in case of error I'm going to receive three parameters, a xhrequest (or similar), a message and I don't remember.. How can I handle this? In the response body shoulde be a json, where can I find it?

Thanks for any help, sorry for no code or the poor indentantion but I'm writing from my mobile!

Upvotes: 0

Views: 127

Answers (3)

Wolfram
Wolfram

Reputation: 8052

As Paul Tomblin said, you have (at least) two options:

  • Setting an error code for your response results in error being called. In this case, the datatype of the response content is usually nothing to work with, so it is not parsed and put into a data variable. But you may access the response text via jqXHR.responseText and parse the JSON yourself (.parseJSON()).

  • Returning a 200response with proper JSON content, which is parsed automatically into a data object (if dataType is set to json). You can then check if(data.error) {...}, get the error message and present it to the user.

I would go for the second option, but it depends on which errors you are expecting.

Upvotes: 0

Paul Tomblin
Paul Tomblin

Reputation: 182878

The error callback gets called when it can't get the response from the server (like a 404 error or the like). If you want to pass back your own errors, you need to put them in the JSON response and test for them in your success callback.

For instance, in a success callback I'm working on right now:

    jQuery.ajax({
        'url':      'Client/saveClient.mas',
        'dataType': 'json',
        'data':     {
            'first_name'            :   first_name,
            'middle_initials'       :   middle_initials,
            'last_name'             :   last_name,
            'phone_number'          :   phone_number
            },
        'success':  saveClientSuccessCallback,
        'error':  saveClientFailureCallback
    });
  }
}

function saveClientSuccessCallback(json)
{
  if (json.status == 'error')
  {
    updateClientTips(json.error_msg);
  }
  else
  {
    addReadOnlyClient(json.people.values, json.manager_uperson_id);

    jQuery('#new-client-form').dialog("close");
  }
}
function saveClientFailureCallback(jqXHR, textStatus, errorThrown)
{
  updateClientTips(textStatus + ': ' + errorThrown);
}

As you can see, I return an error condition in json.status and the message in json.error_msg.

Upvotes: 1

Alnitak
Alnitak

Reputation: 340055

The actual body of the response should be available in jqxhr.responseText

Upvotes: 0

Related Questions