AJAX: only error callback is been fired - javascript

I have declared success and error callbacks, but in case of status code 200 also it calls error callback only.
I have been making curl call to some other php file too inside registry.php.
Here what i tried:
$.ajax({
type: "POST"
,data: {
action: "blah"
,mobileNo: that.mobNo
,token: that.key
}
,url: "http://90.8.41.232/localhost/registry.php"
,cache: false
,dataType: "json"
,success: function (response) {
console.log("success");
}
,error: function () {
console.log("error");
}
});
I have read in documentation that we don't have to call success callback explicitly, hope it's correct.
Any idea how to call success callback when it is 200 status code.
RESPONSE
hope this will help, this I copied from chrome console, not printed by console.log().
bort: (statusText)
always: ()
complete: ()
done: ()
error: ()
fail: ()
getAllResponseHeaders: ()
getResponseHeader: (key)
overrideMimeType: (type)
pipe: ()
progress: ()
promise: (obj)
readyState: 4
responseText: "{"success":"Mobile No 9535746622 is approved"} {"report":true}"
setRequestHeader: (name,value)
state: ()
status: 200
statusCode: (map)
statusText: "OK"
success: ()
then: ()

As you have mentioned that you are making a curl call to some other php, what happens is whenever you make curl call you have to return the response of the curl to the client. So to transfer the return value of curl call, you have to set an option curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);.
This will sort your problem. Hope so.

First, checkout the real error you get (not certain you really get a 200 status ?)
error: function (err) {
console.error("error");
console.log(err);
console.log(err.stack);
throw err;
}
Show us the resulting log please.

I did that a few weeks ago and for me it works if I call it like
$.ajax(
{
type: "POST",
data: { action: "blah", mobileNo: that.mobNo, token: that.key },
url: "http://90.8.41.232/localhost/registry.php",
cache: false,
dataType: json,
})
.success (function (data, status, jqxhr)
{
// do your stuff
})
.error (function(x, status, jqxhr)
{
// handle your errors
});

Related

Why can't I wrap js promise resolve in a jquery object?

I wanted to be able to send the data from a successful jquery ajax call to other methods in my application because its quite large and it made coding sense to have one api method to work from, so I opted to try out promises. This is my first shot. I am getting some good results but clearly I am still a bit confused on context and timing.
When I run the following code, I am unable to wrap my return data from the ajax call as a jquery object without getting an error:
var widgetSystem={
listenForClick: function(){
$('div').on('click','a',function(){
var $selectTarget = $(this),
widgetid = $(this).data('widgetid');
apiRequestData = widgetSystem.makeApiRequestForSingleWidget(widgetid);
apiRequestData.then(function(result) {
widgetSystem.showWidget(result);
}).catch(function(e) {
console.log('no way big error ' +e);
});
});
},
makeApiRequest: function(widgetid){
return new Promise(function(resolve, reject) {
$.ajax({
method: "POST",
url: "localhost",
dataType: 'json',
data: {
data: {
widgetId: widgetid
},
action: 'apiMethod'
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
reject();
},
success: function (data) {
resolve(data);
}
});
});
},
showWidget: function(data){
$(data).appendTo('body');
//this causes an exception in my apiRequestData.then function in listenForClick
}
}
I am running un minified jquery and getting the following error in my console:
no way big error TypeError: context is undefined
I don't know exactly what your HTML looks like or how the API is set up, but assuming that the API is working correctly and the data sent via POST is correct, I was able to get it working using jsonplaceholder api with the following code (you can find it on JSbin).
var widgetSystem={
listenForClick: function(){
$('div').on('click','a',function(){
console.log('clicked');
var $selectTarget = $(this);
var widgetid = $(this).data('widgetid');
widgetSystem.makeApiRequest(widgetid)
.then(function(result) {
widgetSystem.showWidget(result);
return result;
})
.catch(function(e) {
console.log('no way big error ' +e);
});
});
},
makeApiRequest: function(widgetid){
return new Promise(function(resolve, reject) {
var root = 'http://jsonplaceholder.typicode.com';
$.ajax({
method: "POST",
url: root+'/posts/',
dataType: 'json',
data: {
userId:1,
title:"Havanagila",
body:"Testing the greatness"
},
success: function(xData, status){
resolve(xData);
//reject('whoops');
},
error: function(xhr, status, error){
reject(status);
}
});
});
},
showWidget: function(data){
$('#space').append(document.createTextNode(JSON.stringify(data)));
}
}
widgetSystem.listenForClick()
I don't think there is an issue which how you are calling resolve(data) within the ajax success callback. There may be an issue with the data being sent to your API such that the error callback is called, which in turn calls reject and causes the callback passed to .catch to be called instead of the intended callback passed to .then.

Why is Jquery $.ajax firing all statusCode on function call even with successful call

I have a simple Jquery ajax function call that looks like this.
function getUsers(){
var jqxhr = $.ajax({
url: "../assets/js/data/users.json",
type: "GET",
cache: true,
dataType: "json",
statusCode: {
404: handleError404("Error at getUsers();"),
500: handleError500("Error at getUsers();")
},
success: function (data) {
$.each(data, function(index, element) {
console.log(element.name);
});
}
});
}
The error handle functions look like this.
function handleError500(customMsg){
alert("Oops, there was an error: 500");
console.log("ERROR: 500 | "+customMsg);
}
function handleError404(customMsg){
alert("Oops, there was an error: 404");
console.log("ERROR: 404 | "+customMsg);
}
For some odd reason, even on a successful call with no apprent error 500 or 404 the statusCode functions are firing.
Any ideas? Thank you.
This is a common Javascript gotcha, but you're actually firing off these functions!
() after the name will actually invoke that function at that moment.
404: handleError404() // <-- it calls it immidiately
What you need to do, is create an anonymous function, which will be called later when the error actually happens, which inside of it will invoke your functions.
statusCode: {
404: function () { // <-- anonymous function won't get called until it needs to
handleError404("Error at getUsers();")
},
500: function () {
handleError500("Error at getUsers();")
}
},
Side note: If you weren't passing in parameters to your function,
you could actually ommit the anonymous function function () { /*
function call */ } part, and just call your function!
statusCode: {
404: handleErrors, // since no parameters are passed, this could be done
500: handleErrors
}
Because in the definition of the property of the object you are actually calling the function instead of defining one to be called when the code actually happens.
One thing you can try is:
statusCode: {
404: function() { handleError404("Error at getUsers();") },
500: function() { handleError500("Error at getUsers();") }
},

Getting only the JSON from an ajax query

I'm using this script :
var test = $.ajax({ url : ("/areas/list"), type : 'GET', dataType : 'json', success : function(e) {
} });
I get this result in var text :
Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
abort: function ( statusText ) {
always: function () {
complete: function () {
done: function () {
error: function () {
fail: function () {
getAllResponseHeaders: function () {
getResponseHeader: function ( key ) {
overrideMimeType: function ( type ) {
pipe: function ( /* fnDone, fnFail, fnProgress */ ) {
progress: function () {
promise: function ( obj ) {
readyState: 4
responseJSON: Object
responseText: "{↵ "kind": "fusiontables#sqlresponse",↵ "columns": [↵ "INSEE_COM",↵ "KML",↵ "NOM_COMM"↵ ]}"
setRequestHeader: function ( name, value ) {
state: function () {
status: 200
statusCode: function ( map ) {
statusText: "OK"
success: function () {
then: function ( /* fnDone, fnFail, fnProgress */ ) {
__proto__: Object
The problem, is in this object, i would like get only the object in response JSON. I tried with test.responseJSON, but it doesnt work...
How can i get only the JSON ?
Thanks for your help !
F.
You're not doing anything with the returned data in the success callback.
This should work:
var test;
$.ajax({
url: "/areas/list",
type: 'GET',
dataType: 'json',
success: function(response) {
// Do what ever with the response here
console.log(response);
// or save it for later.
test = response;
}
});
If you decide to save the response in a variable you won't be able to access it straight away. The ajax request wont't be complete. Best to do your processing of the JSON object in the success callback.
The test variables value will be the value returned by the $.ajax() function call, not the result. $.ajax will not immediately return the value from the call, its asynchronous, that's why a callback (success: function(e) {}) is used. The success callback will be called when the ajax call have successfully fetched whatever it is asked to fetch.
Check what e is in the success callback!
$.ajax({url: ("/areas/list"), type: 'GET', dataType: 'json', success: function(e) {
console.log(e); // e == result from the ajax call.
}});
1. Are you returning JSON data?
In your AJAX, you're sending a request to a link at /areas/list - how are you handling that request in the Rails controller?
For it to return JSON data, it should read something like this:
#app/controllers/areas_controller.rb
def list
respond_to do |format|
format.json { return :json => "hello".to_json }
end
end
Posting your controller's code will be a big help for us all
2. Are you handling the JSON data correctly?
JSON data is different than "normal" javascript data. It has to be parsed when it is returned from the server, using the JSON parse functions:
$.ajax({
url : ("/areas/list"),
type : 'GET',
dataType : 'json',
success : function(data) {
var json_data = JSON.parse(data);
//do what you need here with the new array
}
});
you are trying to fetch value synchronously, which is not a good practice. You should try the following way:
var test;
$.ajax({
url:"/areas/list",
type:"GET",
dataType:"JSONP",
success:function(testdata){
console.log(testdata);
test=testdata;
}
});

How to capture the 500 error message using jquery?

How can i capture the 500 error message using jquery? I want to keep on checking for the 500 error message for sometime until it changes and time out after 50 sec.
I used the code below to try to capture and check the 500 error message but it doesnt seem to catch the 500 error message. I can see it in the firebug
$.ajax({
statusCode: {
500: function() {
alert(" 500 data still loading");
console.log('500 ');
}
}
});
Dispite the accepted answer mentioned by #Danny, you can also do this in newer versions of jQuery.
var xhr = $.ajax({
url: "somewhere"
});
xhr.fail(function(xhr, textStatus, error) {
// Error handling stuff here ...
});
See Deferred Object.
Are you missing url in $.ajax like the one below
$.ajax({
url: "/path to page",
statusCode: {
500: function() {
alert(" 500 data still loading");
console.log('500 ');
}
}
});
You can check the status in error of ajax post please check the below code.
$.ajax({
.....
success: function (data) {
},
complete: function (XMLHttpRequest, textStatus) {
},
error: function (e, status) {
if (e.status == 404)
alert("404 error");
}
});
Thanks

Trapping Function not defined error in Javascript and jQuery

Okay, I do use firebug to determine when a function is not defined in Dev. What I would like to do in production is show a modal window saying an error has been received which would then redirect them to another page upon click. Not so easy.
Please understand that this function does work and the component that is called works. I am going to misspell the function call on purpose to demonstrate the error I am not receiving thru the jquery ajax function.
I am using .ajaxSetup to set up the default options for several ajax functions that will be running asynch:
$.ajaxSetup({
type: "POST",
dataType: "json",
url: "DMF.cfc",
data: {
qID: 1,
returnFormat: "json"
},
beforeSend: function() {
$('#loadingmessage').fadeIn(); // show the loading message.
},
complete: function() {
$('#loadingmessage').fadeOut(); // show the loading message.
}
}); //end AjaxSetup
The actual ajax call is:
$.ajax({
data: {
method: 'getCurrentIssues'
},
success: function(response) {
nsNewDebtshowDebtIssues(response);
},//end success function
error: function(jqXHR, exception) {
alert("Error running nsNewDebt.showDebtIssues");
}
}) //end getCurrentIssues Ajax Call
The error I forced is that the method run in the success function should actually be nsNewDebt.showDebtIssues. Firebug correctly displays in console the error nsNewDebtshowDebtIssues is not defined but the actual error message for the ajax call does not run, so if an enduser was running the page it would appear the page was hung.
So, In summary I want to know how to track when such an error occurs, preferrable to place in the error section of the .ajaxSsetup but if neccessary in each .ajax call.
It is not an ajax error, so you cannot handle it from the ajaxError method.
You should do a try/catch in the success method.
success: function(response) {
try {
nsNewDebtshowDebtIssues(response);
} catch (ex) {
//exception occured
//alert("Error running nsNewDebt.showDebtIssues");
alert( ex.message + '\n\tin file : ' + ex.fileName + '\n\t at line : ' + ex.lineNumber);
}
}
Before making the call, you can do:
if(typeof nsNewDebtshowDebtIssues == 'function') {
// .. call it ..
}
Well, the error actually occurs after the AJAX call has succeeded (since it comes from your success handler), so the error handler indeed won't be called.
If you want to use the same handler for actual AJAX request errors and for further errors originating from your success handler, you can define a named function and use it both as your error handler and from a try/catch block in your success handler:
function handleError(jqXHR, status, exception)
{
alert("Error running request.");
// Or print something from 'jqXHR', 'status' and 'exception'...
}
$.ajax({
data: {
method: "getCurrentIssues"
},
success: function(response, status, jqXHR) {
try {
nsNewDebtshowDebtIssues(response);
} catch (x) {
handleError(jqXHR, status, x);
}
},
error: handleError
});

Categories

Resources