hitUrl = function (searchUrl, nbCity) {
$.ajax({
context: this,
type: 'GET',
headers: { "sourceid": "1" },
url: '/webapi/xyz/abc/?' + searchUrl,
dataType: 'text',
success: function (json) {
D_usedSearch.similarCars.showSimilarCarLink(searchUrl);
});
When i put breakpoint on 1st line of success of this jquery success callback, i am unable to access 'searchUrl' in console. It is undefined.
How do i access this?
That's probably because Ajax is asynchronous: the code from the function is executed parallel from the code in the ajax call.
Take a look to this answer for the solution to your problem.
Related
Right now I have a code like this:
$.ajax({
url: apiUrl + valueToCheck,
data: {
format: 'json'
},
error: function () {
},
dataType: 'json',
success: function (data) {
checkAgainstDBHelperWH(data, valueToCheck);
},
type: 'GET'
});
If I am not mistaken, checkAgainstDBHelperWH is known as a callback function. The function executes once the servers sends back response for this particular HTTP /ajax request.
I want to try writing something like the one below, but I don't know what are the effects or is it even logical:
var request = $.ajax({
url: apiUrl + valueToCheck,
data: {
format: 'json'
},
error: function () {
},
dataType: 'json',
success: function (data) {
checkAgainstDBHelperWH(data, valueToCheck);
},
type: 'GET'
})
arrayOfPromises.push(request);
$.when.apply(null, arrayOfPromises).done(function () {
//...some javascript here
});
I want to understand if the .done(function () is fired after the callback function checkAgainstDBHelperWH is completed? Or whatever I am trying to write above does not flow consistently with how ajax works?
Thanks!
I tested it, your code only work if the function(in this case, 'checkAgainstDBHelperWH') doesn't call ajax.
If you want to wait finishing the inner ajax process, use then() and return inner ajax.
var ajaxs =
$.get("xxx").then(function() {
return $.get("yyy").done(function() {
});
});
Here is the jsfiddle.
I'm not sure whether this way is general or not.
I've got a small javascript function that's only purpose is to call a script to get some data from the database so it can be used by other functions on the client side.
I'm using a jQuery call to get the data but for me to pass the object out of the success functions scope I need to turn asynchronous off which raises a deprecation warning.
My function works as intended currently but I'd like to use a method that isn't deprecated. Here is my function:
function getData(ID) {
var Data = {};
$.ajax({
url: 'script',
method: 'POST',
dataType: 'json',
async: false,
data: {action: 'get', id: ID },
success: function(response) {
Data = response;
})
});
return Data;
}
I've changed the variable names for privacy reasons so apologies if they're vague.
Also why is synchronous calls considered harmful to the end users experience?
As AJAX call is asynchronous, you will always get blank object ({}) in response.
There are 2 approach.
You can do async:false
To get response returned in AJAX call try like below code. Which wait for response from server.
function getData(ID) {
return $.ajax({
url: 'script',
method: 'POST',
dataType: 'json',
//async: true, //default async call
data: {action: 'get', id: ID },
success: function(response) {
//Data = response;
})
});
}
$.when(getData(YOUR_ID)).done(function(response){
//access response data here
});
I try to convert an ajax function that I do not understand. Here the original function :
$.get(page, function (data) {
$('.former-students__list').append(data.student
$('#load-more').data('next-page', data.next_page);
})
I'd like to convert it to make it more readable (with $ .ajax), So I could clearly see the events success, and so on.
Here is what I tried but it doesn't work
$.ajax({
url: page,
data: function (data) {
$('.former-students__list').append(data.students);
$('#load-more').data('next-page', data.next_page);
}
'success': 'Cool, it's work')
},
Thank you for your help and your explanations
The issue is because the data parameter should be an object, a string or an array which you use to send data to the server. However, given your $.get sample, you don't actually need to use it in $.ajax at all.
Instead, the success property should be a function which receives the data back from the request and then acts on it. Try this:
$.ajax({
url: page,
success: function(data) {
$('.former-students__list').append(data.students);
$('#load-more').data('next-page', data.next_page);
})
});
For more information, please read the jQuery $.ajax documentation.
Try this:
$.ajax({
url: page,
success: function (data) {
$('.former-students__list').append(data.students);
$('#load-more').data('next-page', data.next_page);
}
})
I think the data property is for POST request payloads.
you should fire the success callback event so try this :
$.ajax({
url: page,
success: function(data) {
$('.former-students__list').append(data.students);
$('#load`enter code here`-more').data('next-page', data.next_page);
}
});
I have the following javascript which contains an ajax call:-
$.ajax({
type: "POST",
url: '#Url.Action("DeleteSelected"),
data: { ids: boxData.join(",") }
})
});
but is there a way to call a javaScript function is the above Ajax call succeed?
Thanks
function mySuccessFunction() {
alert('success');
}
$.ajax({
type: "POST",
url: '#Url.Action("DeleteSelected")',
data: {
ids: boxData.join(",")
},
success: function(data) {
// your code if AJAX call finished successfully
// call your function that already loaded from here:
mySuccessFunction();
// you can also process returned data here
}
});
You have three particular handlers you can use to process information returned with AJAX, .success(), .done(), and .fail(). With these methods, your code might look something like this:
$.ajax({
type: "POST",
url: '#Url.Action("DeleteSelected"),
data: { ids: boxData.join(",") }
}).success(function(data) {
// This callback is executed ONLY on successful AJAX call.
var returnedJSON = data; // The information returned by the server
yourSuccessFunction();
}).done(function() {
// This callback is ALWAYS executed once the AJAX is complete
yourDoneFunction();
}).fail(function() {
// This callback is executed ONLY on failed AJAX call.
});
Also see: jQuery AJAX Documentation
I am trying to implement Repository pattern in JavaScript. I have ViewModel which i want to initialize with the data when i call Initialize method on it. Everything seems to be falling in places except that i am not able to return the data from my AJAX call. I can see that data is coming back from the ajax call but when i trying to capture the data in SomeViewModel's done function, it is null.
Can someone please point me out where i am going wrong here?
P.S: Please notice that i am not making Async call so the call chain is properly maintained.
This is how my Repository looks like:
function SomeRepository(){
this.LoadSomeData = function loadData()
{
$.ajax({
type: "POST",
url: "someUrl",
cache: true,
async: false,
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
//success: handleHtml,
success: function(data) {
alert('data received');
return data;
},
error: ajaxFailed
});
function ajaxFailed(xmlRequest) {
alert(xmlRequest.status + ' \n\r ' +
xmlRequest.statusText + '\n\r' +
xmlRequest.responseText);
}
}
};
This is how my ViewModel looks like:
function SomeViewModel(repository){
var self = this;
var def = $.Deferred();
this.initialize = function () {
var def = $.Deferred();
$.when(repository.LoadSomeData())
.done(function (data) {
def.resolve();
});
return def;
};
}
This is how i am calling from an aspx page:
var viewModel = new SomeViewModel(new SomeRepository());
viewModel.initialize().done(alert('viewmodel initialized'));
alert(viewModel.someProperty);
I have used successfully an auxiliar variable to put the ajax result, when ajax call is inside a function (only works if ajax is async=false) and i need the function does return the ajax result. I don't know if this is the best solution.
function ajaxFunction(){
var result='';
$.ajax({
type: "POST",
url: "someUrl",
cache: true,
async: false,
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
//success: handleHtml,
success: function(data) {
alert('data received');
result=data;
},
error: ajaxFailed
});
return result;
}
Doesn't matter that it's synchronous (though it really shouldn't be). Returning a value from inside the ajax callback will not cause the value to be returned from the containing function.
Using asynchronous ajax is generally a much better idea anyway, but that will force you to create an API that allows its clients to pass in handlers to be called when the ajax request completes. To do that, you'd give your "LoadSomeData" function a parameter. A caller would pass in a function, and your ajax "success" handler would pass on the results (or some transformation of the results; depends on what it is that you're doing) to that callback. It's the same idea as the callbacks used in the ajax call itself.