Why does my ajax success callback-function not work as expected? - javascript

I code this ajax request but I don't know why the code in the success method doesn't work
Even though in the networks in chrome browser appear state: 200ok
this is ajax code:
$("#noti_filter").click(function(){
//first add item into cart
var item_id = 'test';
$.ajax({
method:"POST",
//contentType:"application/json",
url:"../html/notifies.php",
data:{product_id:item_id},
dataType: "json",
success:function(data,state) {
console.log(data);
console.log(state);
alert('ajax success');
}
});
});
the problem is that alert or console Not to mention the others code
success:function(data,state)
{
console.log(data);
console.log(state);
alert('ajax success');
}

From the ajax events docs:
success (Local Event)
This event is only called if the request was successful (no errors from the server, no errors with the data).
Since your server responded with 200 OK that means we can route out problems with the server and are left with errors with the data.
From the ajax docs (only the relevant parts):
dataType
The type of data that you're expecting back from the server.
The available types (and the result passed as the first argument to your success callback) are:
"json": Evaluates the response as JSON and returns a JavaScript object.
...
The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
So most likely the data returned by the server is being rejected by ajax in which case a parse error should be thrown.
This would be an example of how to implement an error handler:
$("#noti_filter").click(function(){
//first add item into cart
var item_id = 'test';
$.ajax({
method:"POST",
//contentType:"application/json",
url:"../html/notifies.php",
data:{product_id:item_id},
dataType: "json",
success: function(data,state) {
console.log(data);
console.log(state);
alert('ajax success');
},
error: function(err) {
console.log(err.responseText); // <-- printing error message to console
}
});
});

You defined the dataType as json. The dataType is the type of data that you're expecting back from the server. Does your server responds json?
I assume the result of your 200-ok-server-request is probably not in json format, so the parsing fails and your success-callback is not called. You can catch the error with error callback function.
After that you know the exact reason.

Related

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.

AJAX requests fails whitout error

My loadView function is a somehow broken
function loadView(view){
$.get("../content/mainView.html", function(data) {
$("#content-container").html(data);
})
.done(function() {
console.log("done");
})
.fail(function(xhr, status, error) {
console.log("fail");
console.log(error);
});
}
I dont know what is wrong with me since I dont even can debug it since
console.log(error);
just gives me an empty response.
Can someone tell me whats wrong with my code and why
console.log(error);
dont give any response?
It is possible in AJAX/GET request world that you may get empty error parameter in fail scenarios.
error object is the message sent from server, In case request doesnt reached till server you may get empty response.
I would recommend to use textStatus
The three parameters are explained below respectively.
.fail(function(jqXHR , textStatus , error)......
jqXHR is a JS object
textStatus is "error"
error is "Internal Server Error", it's the error message sent by the server.
Try using the $.ajax method instead of $.get method
function loadView(view){
$.ajax({
type: "GET",
url: "../content/mainView.html", //Please put the actual url of the page
data: {NameOfData: $("#content-container").html(data)},
dataType: "text",
success: function(resultData){
//Do something
}
})
}
also is your code in $(document).ready(function(){})? If it isn't then also try putting your code into this function
Hope it helps!

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

Cross-domain AJAX call returning string JSON, instead of JSON object

I am making a cross-domain AJAX call, and I am not sure if I am doing something wrong or the providers of the API call is incorrectly returning the JSON. Whenever I get the response from the API call, it is a string instead of a JSON object. Here is my AJAX call.
$.ajax({
async: false,
dataType: 'jsonp',
url: 'http://cross-domain/getSummaryStat.action',
data: { minDailyDate: start_param, maxDailyDate: end_param },
success: function(response) {
map = {
gamefuse: response["ROM-GF-Live"],
facebook: response["ROM-FB-Live"],
kongregate: response["ROM-Kongregate-Live"],
yahoo: response["ROM-Yahoo-Live"]
}
},
error: function(xhr, textStatus, errorThrown){
alert('request failed');
}
});
When the response comes back, here is response.result
"[{"dayRetention1":"0.01453800063053","visit":"601","installs":"203"},{"dayRetention1":"0.122484891199019","visit":"33863","installs":"10949"]"
NOTE: I set dataType to jsonp because it is a cross-domain AJAX call, and I was getting an error without it.
First, It looks like the returned string isn't even in correct JSON form. It's missing a close bracket at the end.
If this doesn't fix it then the issue here is probably on the server side. Since JSONP is JSON with padding, your return function shouldn't be:
function_name("the string that I return");
Instead you should have:
function_name({
"name":"Bob Loblaw",
"age":40
});

jQuery Ajax - how to get response data in error

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.

Categories