I'm having trouble getting the error callback getting called when I pass the error function as an object parameter in a function. However, when I declare it within the ajax code it works.
var ajaxSettings = new Object();
ajaxSettings.error = function(request, status, error){ console.log('bad failure');};
ajaxSettings.success = function(result) { console.log('good success');};
uploadFile(contents, ajaxSettings)
function uploadFile(contents, settings) {
$.ajax({
url: uri,
type: "PUT",
data: contents,
processData: false,
dataType: "json",
success: settings.success,
error: settings.error
});
}
In this case the error callback doesn't get fired. However if I write the error function declaration in the ajax code it works.
function uploadFile (contents, settings) {
$.ajax({
url: uri,
type: "PUT",
data: contents,
processData: false,
dataType: "json",
success: settings.success,
error: function(request, status, error) { console.log('bad failure'); },
});
}
I also tried making success: settings.error and it will call that function when it succeeds. What is the reason the error callback is not getting called?
I created a fiddle using your code check it Fiddle
You should initialize the ajaxSettings before use it
Try to declare your callbacks like below:
var ajaxSettings = {}
ajaxSettings.error = function(request, status, error){ console.log('bad failure');};
ajaxSettings.success = function(result) { console.log('good success');};
... because they are probably not visible in "uploadFile" function scope.
Related
I am new to mocha/chai unit testing. I have following ajax call which is making a service call. I have added .fail() and .done() as a part of ajax call.
So I am not sure what I am missing here. Sorry if I am missing basic things here. Can someone please describe what's wrong here?
function searchAPIcall(endPointurl, method, search_headers, search_identifier) {
$.ajax({
type: method,
contentType: "application/json; charset=utf-8",
dataType: "json",
url: endPointurl,
headers: search_headers,
xhrFields: {
withCredentials: true
},
success: function success(results, xhr, XMLHttpRequest) {
successCallback();
},
error: function (xhr, textStatus, error) {
callErrorFunc();
}
}).fail(function (xhr, textStatus, errorThrown) {
callFailFunc();
}).done(function () {
callDoneFunction();
});
}
I have written following unit test:
describe.only('Testing searchdoctorAPIcall function', function () {
var testurl = 'https://abc.serve.org/getData';
beforeEach(function() {
sinon.stub($, 'ajax');
});
afterEach(function() {
$.ajax.restore();
});
it('should make an ajax call', function(done) {
searchAPIcall(testurl, "GET", {"Content-Type":"application-json;charset=utf-8",X-Id":"1da9b0c8-bb52"}, "baseSearch");
expect($.ajax.calledOnce).to.be.true;
done();
});
});
I am always getting the following error while executing unit test.
undefined is not an object (near '...} }).fail(function (xhr,...')
But When I change my searchAPIcall function and remove the .dail() and .done() unit test is passing.
function searchAPIcall(endPointurl, method, search_headers, search_identifier) {
$.ajax({
type: method,
contentType: "application/json; charset=utf-8",
dataType: "json",
url: endPointurl,
headers: search_headers,
xhrFields: {
withCredentials: true
},
success: function success(results, xhr, XMLHttpRequest) {
successCallback();
},
error: function (xhr, textStatus, error) {
callErrorFunc();
}
})
}
Now if I run the unit test then it is passing.
should make an ajax call (passed)
You need to weave the test done call into your code so that it is run after the async call and your tests finish:
function searchAPIcall(endPointurl, method, search_headers, search_identifier) {
return $.ajax({ // return the call so it can be chained
...
});
}
it('should make an ajax call', function(done) {
searchAPIcall(
testurl,
"GET",
{"Content-Type":"application-json;charset=utf-8","X-Id":"1da9b0c8-bb52"}, // Note: you are missing a " before the 'X' in this line
"baseSearch"
).done(() => {
expect($.ajax.calledOnce).to.be.true;
done();
}).fail(done); // Equivalent to: .fail(error => done(error))
});
G'day all,
I'm trying to pass a value through to a Success var from the original AJAX call.
Here's some code :
function isJobComplete(jobGUID) {
var data = { "pJobGUID": jobGUID };
var url = '/DataService.asmx/isJobComplete';
var success = function (response, jobGUID) {
if (response.d) {
//The job is complete. Update to complete
setJobComplete(jobGUID);
}
};
var error = function (response) {
jAlert('isJobComplete failed.\n' + response.d);
};
sendAjax(data, url, success, error);
}
function sendAjax(data, url, success, error) {
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: success,
error: error || function (response) {
jAlert(response.d);
}
});
}
When the isJobComplete function runs, it has the correct value for jobGUID on the first pass through, but on the return to Success after the AJAX call, jobGUID changes to the word "success", with the double quotes.
How can I pass through that jobGUID to the Success function so I can use it to do more work depending on the AJAX response?
Thanks in advance....
I'm trying to implement a function that after consulting a service brings the variables as global.
function ajax_test(str1, callback){
$.ajax({
url: '/path/service',
type: 'POST',
dataType: "json",
data: {'vars':$('form').serialize(), 'test':123},
success: function(data, status, xhr){
callback(data);
}
});
}
and I'm trying to call like this:
ajax_test("str", function(url) {
//do something with url
console.log(url);
});
Now, if I just call ajax_test() it returns an error, saying that callback is not a function.
How would be the best way to simply call the function and get the results to use global variables?
Edit:
I think a good question is: what is a good alternative to async: false? How is the best way to implement synchronous callback?
Edit 2:
For now, I'm using $.post() with $.ajaxSetup({async: false}); and it works how I expect. Still looking a way I could use with a callback.
Have to set the scope inside the success method. Adding the following should work.
function ajax_test(str1, callback){
$.ajax({
url: '/path/service',
type: 'POST',
dataType: "json",
data: {'vars':$('form').serialize(), 'test':123},
success: function(data, status, xhr){
this.callback(data);
}.bind(this)
});
}
As an argument of the ajax_test function, callback is in the scope of the ajax_test function definition and can be called anywhere there, particularly in the successcase. Note that calling ajax_test() without arguments will as expected make your code call a function that does not exist, named callback.
The following sends an Ajax request to the jsFiddle echo service (both examples of callback as anonymous or global function are given in the jsFiddle), and works properly :
function ajax_test(str1, callback){
$.ajax({
url: '/echo/json',
type: 'POST',
dataType: "json",
data: {
json: JSON.stringify({
'vars':$('form').serialize(),
'test':123
})
},
success: function(data, status, xhr){
callback(data);
}
});
}
ajax_test("unusedString", function(data){
console.log("Callback (echo from jsFiddle called), data :", data);
});
Can you check that the webservice you're calling returns successfully ? Here is the jsFiddle, I hope you can adapt it to your need :
https://jsfiddle.net/dyjjv3o0
UPDATE: similar code using an object
function ajax_test(str1) {
this.JSONFromAjax = null;
var self = this;
function callback(data) {
console.log("Hello, data :", data);
console.log("Hello, this :", this);
$("#callbackResultId").append("<p>Anonymous function : " + JSON.stringify(data) + "</p>");
this.JSONFromAjax = JSON.stringify(data);
}
$.ajax({
url: '/echo/json',
type: 'POST',
dataType: "json",
data: {
json: JSON.stringify({
'vars': $('form').serialize(),
'test': 123
})
},
success: function(data, status, xhr) {
console.log("Success ajax");
// 'self' is the object, force callback to use 'self' as 'this' internally.
// We cannot use 'this' directly here as it refers to the 'ajax' object provided by jQuery
callback.call(self, data);
}
});
}
var obj = new ajax_test("unusedString");
// Right after the creation, Ajax request did not complete
console.log("obj.JSONFromAjax", obj.JSONFromAjax);
setTimeout(function(){
// Ajax request completed, obj has been updated
console.log("obj.JSONFromAjax", obj.JSONFromAjax);
}, 2000)
You cannot expect the Ajax request to complete immediately (don't know how it behaves with async: false though, this is why you need to wait for a while before getting the actual response.
Updated jsFiddle here : http://jsfiddle.net/jjt39mg3
Hope this helps!
For example if I have the JS ajax get/post function
function cancelFeeReport() {
var postData = "claimId=" + $("#FeeReport_ClaimID").val() + "&page=#ViewBag.PageNumber";
$.ajax({
type: "POST",
url: '#Url.Action("Cancel", "FeeReports")',
dataType: "json",
async: false,
data: postData,
success: function (result) {
// Do something
},
complete: function () {
// Do nothing for now.
}
});
}
When an error happened in the above JS function. How to identify that cancelFeeReport() threw the error to AJAX global error handler
$(document).ajaxError(function( event, jqxhr, settings, thrownError ) {
alert('Error in ' + <functioname>);
});
I have Node.js server and jQuery ajax requests.
This works:
api(config.categoriesURL, success, config.err1);
setTimeout(function () {
api(config.randomURL, success1, config.err2);
},300);
But this doesn't:
api(config.categoriesURL, success, config.err1);
api(config.randomURL, success1, config.err2);
Here is the console output:
url: http://localhost:3000/categories/?callback=myCallback&_=1431726147454
url: http://localhost:3000/random/?callback=myCallback&category=55564cc42e366b34aa9a529d&callback=myCallback&_=1431726147455
responseText: undefined
status: 200
text status: parsererror
error: Error: myCallback was not called'
Is this server-side or client-side problem? Any idea why this is happening and how I should solve it? Is this normal behaviour?
Here is more code:
main.js
$(document).ready(function() {
var api = require('./api'),
config = require('./config');
function success (data) {
data.forEach(function (category) {
var div = document.createElement('div');
div.id = category._id;
div.textContent = category.name;
$('.container').append(div);
});
}
function success2 (data) {
console.log(data);
}
api(config.categoriesURL, success, config.err1);
api(config.randomURL, success2, config.err2);
});
api.js
function api(url, success, error) {
$.ajax({
type: 'GET',
url: url,
beforeSend: function (jqXHR, settings) {
console.log('url: ' + settings.url);
},
jsonpCallback: 'myCallback',
dataType: 'jsonp',
success: success,
error: error
});
}
module.exports = api;
You should try removing:
jsonpCallback: 'myCallback',
You are making two simultaneous JSONP ajax calls that use the same name for the callback function. I would think that would be a problem.
If you remove the jsonpCallback setting, jQuery will randomly generate the name of the callback function.