jQuery Ajax - how to get response data in error - javascript

I have a simple web application.
I've created the server REST API so it will return a response with HTTP code and a JSON (or XML) object with more details: application code (specific to scenario, message that describe what happened etc.).
So, for example if a client send a Register request and the password is too short, the response HTTP code will be 400 (Bad Request), and the response data will be: {appCode : 1020 , message : "Password is too short"}.
In jQuery I'm using the "ajax" function to create a POST request. When the server returns something different from HTTP code 200 (OK), jQuery defines it as "error".
The error handler can get 3 parameters: jqXHR, textStatus, errorThrown.
Ho can I get the JSON object that sent by the server in error case?
Edit:
1) Here is my JS code:
function register (userName, password) {
var postData = {};
postData["userName"] = userName;
postData["password"] = password;
$.ajax ({
dataType: "json",
type: "POST",
url: "<server>/rest/register",
data: postData,
success: function(data) {
showResultSucceed(data);
hideWaitingDone();
},
error: function (jqXHR, textStatus, errorThrown) {
showResultFailed(jqXHR.responseText);
hideWaitingFail();
}
})
}
2) When looking at Firebug console, it seems like the response is empty.
When invoking the same request by using REST testing tool, I get a response with JSON object it it.
What am I doing wrong?

Here's an example of how you get JSON data on error:
$.ajax({
url: '/path/to/script.php',
data: {'my':'data'},
type: 'POST'
}).fail(function($xhr) {
var data = $xhr.responseJSON;
console.log(data);
});
From the docs:
If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.
Otherwise, if responseJSON is not available, you can try $.parseJSON($xhr.responseText).

directly from the docs
The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of
jQuery 1.5 is a superset of the browser's native XMLHttpRequest
object. For example, it contains responseText and responseXML
properties, as well as a getResponseHeader()
so use the jqXRH argument and get the responseText property off it.
In the link above, look for the section entitled
The jqXHR Object

I also faced same problem when i was using multipart/form-data. At first I thought multipart/form-data created this mess, but later i found the proper solution.
1) JS code before:
var jersey_url = "http://localhost:8098/final/rest/addItem/upload";
var ans = $.ajax({
type: 'POST',
enctype: 'multipart/form-data',
url: jersey_url,
data: formData,
dataType: "json",
processData: false,
contentType: false
success : funtion(data){
var temp = JSON.parse(data);
console.log("SUCCESS : ", temp.message);
}
error : funtion($xhr,textStatus,errorThrown){
console.log("ERROR : ", errorThrown);
console.log("ERROR : ", $xhr);
console.log("ERROR : ", textStatus);
}
});
Here when error occurred, it showed me this in console :-
Error :
Error : { abort : f(e), always : f(), .... , responseJSON :"{"message":"failed"}" }
Error : error
Thus i came to know that we have to use $xhr.responseJSON to get the string message which we sent from rest api.
2) modified/working error funtion:
error : funtion($xhr,textStatus,errorThrown){
var string= $xhr.responseJSON;
var json_object= JSON.parse(string);
console.log("ERROR : ", json_object.message);
}
Thus will output "Error : failed" on console.

After spending so much time on this problem, I found the problem.
The page is under the URL: www.mydomain.com/register
The REST api is under the URL: server.mydomain.com/rest
Seems like this kind of POST is not so simple.
I'm going to search more information to understand this issue better (if you have more information please share it with me).
When putting the REST API under www.mydomain.com/rest - everything is working fine.

Related

Getting null in return when executing Ajax request

Ajax request is executing, but it returns not curent_day variable but null.
Js:
$.ajax({
url: 'planing/next-day',
data: {new_curent_day: $('.owl-item.center .slide_day').text()},
dataType: 'json',
type: 'POST',
success: function(curent_day) {
alert(curent_day);
},
error: function(xhr, status, error) {
alert(xhr.responseText + '|\n' + status + '|\n' +error);
}
});
Controller:
public function actionNextDay() {
if (Yii::$app->request->isAjax){
$this->planing_model->curent_day = Yii::$app->request->post('new_curent_day');
return Json::encode($this->planing_model->curent_day);
}
}
May be the problem is your are sending the POST data as JSON so your not able get it through
Yii::$app->request->post('new_curent_day');
Try this they have updated JSON parser set and to get the JSON value through yii.
Error in accessing post json data in yii2
Use the Javascript console and debugger in your browser to see what $('.owl-item.center .slide_day') contains. Make your API endpoint log what it gets in the post variables.
The typos in variable names make me worry that you might refer to the wrong thing. planing has two n's, curent has two r's. This code looks consistent at least but if I came across this code I would suspect current and curent got mixed up.

Can't return any data from jQuery Post

I've been searching for an answer on this one, but none of the answers I found help resolving this issue:
HTTP Post via jQuery is not returning any data.
Here is the javascript code:
$.post(
<ENDPOINT_URL>,
<XYZ DATA SENT>,
function(data){
//THIS IS THE PROBLEM HERE
},
"json")
.fail(function(jqXHR, textStatus, errorThrown){
alert(textStatus);
});
This calls my endpoint API Url fine, which returns code 200 and a JSON response body:
{message: "XYZ"}
So here is what I've done so far:
Because of the asynchronous behavior, I created a function to receive and process the data input. Nothing happens still.
Added the .fail to process failures. According to an article my JSON returned may be incorrectly formatted and placing that .fail to process a failure may let me know what's going on... Is there a way to get the actual error message details?
Validated my JSON. Is it incorrectly formatted or something I'm not realizing?
Replaced the entire code with $ajax instead. Still, getting the same error.
I want to be able to receive that response and process the message "XYZ".
Thank you everyone for your help, much appreciated.
Tutorials/Articles I've followed:
https://api.jquery.com/jquery.post/
How do I return the response from an asynchronous call?
why cant I return data from $.post (jquery)
All, thank you very much for all of the feedback - the issue is now resolved. #Austin French, after reviewing the full method on both the server side and client side javascript, I realized the issue was related to headers.
My apologies for not expanding further on my question and providing further details: I am using Amazon AWS API Gateway to process a backend Lambda function, the client calls out to the function, the function does the job and returns the JSON:
{"message":"xyz"}
I wasn't received this message on the client side using jQuery $.post. The problem came down to how AWS API Gateway processes the request and returns the response.
I needed to include the following headers as part of my Lambda's function response:
"Access-Control-Allow-Origin" : "*"
Here is the full code for the server side response:
//Response
let responseCode = 200;
var responseBody = {
message: responseMessage
};
var response = {
statusCode: responseCode,
headers: {
"Access-Control-Allow-Origin" : "*"
},
body: JSON.stringify(responseBody)
};
Now on the client side, my original function(data){...} receives the response and is able to process it correctly, no errors are being triggered. Client side response handler:
function(data){
alert(JSON.stringify(data));
}
Thanks again everyone for your help!
Try following:
$.post(
ENDPOINT_URL,
myData,
function(data) {
var response = jQuery.parseJSON(data);
console.log(response);
}
);
This is the way I usually use it. It sends data as if sent in an html form and receives json response.
var value1, value2;
$.ajax({
type: "POST",
url: url,
data: {"property1" : value1, "property2" : value2},
success: function(result, status, xhr){
<here you can process the json you get as response in result}
},
error: function(xhr, status, theError){
<here process if ajax fails>
},
dataType: "json"
});
A couple things that won't fit in a comment:
I prefer this format for AJAX:
var myUrl = $(selector).val();
$.post( myUrl, { name: "John", time: "2pm" })
.fail(function (data) { /* code for failure */ }),
.done(function( data ) {
alert( "Data Loaded: " + data );
});
To see what the server is returning however, an easy thing to do is use Chrome's debugger:
Go to the network tab, choose the calling method and then on the right sub pane choose response. You should be able to see not only the response code, but the full contents returned.
A couple additional notes:
the .Done will call the function once the AJAX completes.
Depending on Jquery version you might not have not have a .done but rather .success and vice versa.

jQuery.Ajax Error result

Im using MVC on server side and calling a function via jQuery.Ajax sending json type.
the function results with exception.
i want to invoke/trigger the error result function of the Ajax, what should i send back with the return JSON function?
for the example, let's say the return JSON is triggered from the catch section.
MVC Function
public JsonResult Func()
{
try
{
var a = 0;
return Json(a, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
FxException.CatchAndDump(ex);
return Json(" ", JsonRequestBehavior.AllowGet);
}
}
JavasScript call
$.ajax({
url: '../Func',
type: 'GET',
traditional: true,
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
alert('s');
},
error: function (data) {
alert('e');
}
});
Quoting from this answer:
The error callback will be executed when the response from the server is not going to be what you were expecting. So for example in this situations it:
HTTP 404/500 or any other HTTP error message has been received
data of incorrect type was received (i.e. you have expected JSON, you have received something else).
The error callback will be executed when the response from the server is not going to be what you were expecting. So for example in this situations it:
HTTP 404/500 or any other HTTP error message has been received
data of incorrect type was received (i.e. you have expected JSON, you have received something else).
In your situation the data is correct (it's a JSON message). If you want to manually trigger the error callback based on the value of the received data you can do so quite simple. Just change the anonymous callback for error to named function.
function handleError(xhr, status, error){
//Handle failure here
}
$.ajax({
url: url,
type: 'GET',
async: true,
dataType: 'json',
data: data,
success: function(data) {
if (whatever) {
handleError(xhr, status, ''); // manually trigger callback
}
//Handle server response here
},
error: handleError
});
error callback is invoked when HTTP response code is not 200 (success) as well as when response content is not comply to expected contentType which is json in your case.
So you have to either send HTTP header with some failure response code (e.g. 404) or output non-json response content. In the latter case you can simply output empty string:
return "";
If you want to trigger an error in AJAX, but still know "why" it was triggered so you can customize the error message, see this post:
https://stackoverflow.com/a/55201895/3622569

PhoneGap - Sending JSON encoding data error

I am using Phonegap to connect to a server to authenticate a user. The server expects the data to be Json encoded, and I will get the response back from the server.
var serviceURL = "http://appdev/PEPS-CS-Services/";
The serviceURL (APPDEV) is hosted on our network within the office.
var loginData = {
'strUniqueID' : '123',
'UserName' : 'User123',
'Password' : 'Password123'
};
I have checked the login credentials and they are fine. When I try the following:
$.ajax({
type: "POST",
url: serviceURL + "services/AuthenticationServices/authenticateUser",
data: loginData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
I get the Access-Control-Allow-Origin error in my console.
XMLHttpRequest cannot load http://appdev/PEPS-CS-Services/services/AuthenticationServices/authenticateUser.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost' is therefore not allowed access.
I had a look around, and I was suggested to use Jsonp as the dataType in the ajax request, which does give me back the response I was looking for. However, it isn't alerted out as it should be, the console shows the url with the parameters used in the loginData variable, as below
Resource interpreted as Script but transferred with MIME type application/xml:
http://appdev/PEPS-CS-Services/services/AuthenticationServices/authenticateUser?callback=jQuery164017807046906091273_1396515434941&strUniqueID=123&UserName=Mark&Password=Password1&_=1396515434963"
When I open the link in a browser i get the correct response, as below
<ns:authenticateUserResponse xmlns:ns="http://services">
<ns:return>SESSION ID HERE</ns:return>
</ns:authenticateUserResponse>
However, I also get the Uncaught SyntaxError: Unexpected token < error below it.
I have tried to change to data: loginData to data: {'data':$.toJSON(loginData)}, but still the same error.
My questions are the following:
Am I sending the data over correctly? Why does the jQuery164017807046906091273_1396515434941 get added to the URL before the parameters?
And why am I getting the Uncaught SyntaxError too?
Is this because the server is sending back the incorrect format of the data? It is currently sending back XML
Any help would be greatly appreciated, thanks
This is a familiar cross context issue, you are not allowed to request resource from another domain with simple ajax call and expect a result.
Instead, use a jsonp call and regiter a callback function to call when return result:
var success = function(data){
/* parse JSON */
data = $.parseJSON(data);
/* show json parsed data */
alert(data);
};
$.ajax({
url: serviceURL + "services/AuthenticationServices/authenticateUser",
dataType: 'jsonp', //use jsonp data type in order to perform cross domain ajax
crossDomain: true,
data: loginData,
success: success,
error: function(errMsg) {
alert(errMsg);
}
});

Function returns JSONP. How to display as JSON - Javascript/jQuery

I am working with an API from another website and I am trying to get a JSON object back. Unfortunately due to the site origin issue I have to use JSONP to retrieve my data.
The function is working but I am stack on how to sanitize the data coming as a JSONP format to be able to use it as JSON?
This is my function
$('.loginForm').click(function(){
var url = 'https//api.example.com';
$.ajax({
type:'GET',
url: url,
dataType: 'jsonp',
error: jsonpCallback,
success: jsonpCallback,
jsonp: "callback"
});
function jsonpCallback(response){
console.log(response);
}
});
EDIT
This is the response I get before the error
Object { readyState=4, status=200, statusText="success", more...}
And this is the error i'm getting
SyntaxError: missing ; before statement
{"accountID":1328031,"authToken":"D81CDCB......
I went through every post in SO and the web in general to find where I am making a mistake but so far I can't find anything.
If you are getting the response in jsonP then you can use jXHR for making cross domain request , below is the link of jXHR (Library) :
https://gist.github.com/1576277/f4aead6741e0d7b0c40db6601048d9db6be1a5f9
And here is an example to use jXHR :
function sendRequest()
{
var xhrReq = new jXHR();
xhrReq.onreadystatechange = function(data)
{
if (xhrReq.readyState === 4)
{
//data contains your jsonp response..
}
};
var url = "http://" + SERVER_NAME + "yourCodeFile.aspx?callback=?";
xhrReq.open("GET",url);
xhrReq.send();
}
Always remember to add 'callback=?' as a query string parameter in url for jXHR request as the respone is jsonP.
Hope this helps you.
try using JSON.parse
function jsonpCallback(response){
console.log(JSON.parse(response));
}

Categories