Waiting for ajax Request using Callbacks - javascript

I was trying to use callbacks to wait for Ajax request but it wouldnt work
.can someone please tell me the logic behind callbacks and help me in-cooperate it in my laravel code.
function sendImageToController(callback){
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name="csrf-token"]').attr('content') }
});
$.ajax({
url: "{{route('HeatMap.moveToStorage')}}",
data: {"imgUrl":imgUrl,
"targetHeatMap":myMap
},
type:'post',
success:function(response){
//Refresh After Creating the image
if(!window.location.hash) {
// alert('Please Wait Loading');
//window.location = window.location + '#loaded';
//window.location.reload();
}
console.log("correct");
console.log(response);
},
error:function(e){
console.log(e);
},
});
}

you need to call callback function from success and error function
success:function(response){
callback(null, response);
}error:function(e){
callback(e, null);
}
so it will call callback function in callback function first argument will be error and second will be result.

Related

Jquery Asynchronous call return undefined value

I have gone through many topics on stack overflow for jquery asynchronous AJAX requests. Here is my code.
funciton ajaxCall(path, method, params, obj, alerter) {
var resp = '';
$.ajax({
url: path,
type: method,
data: params,
async: false,
beforeSend: function() {
$('.black_overlay').show();
},
success: function(data){
console.log(data);
resp = callbackFunction(data, obj);
if(alerter==0){
if(obj==null) {
resp=data;
} else {
obj.innerHTML=data;
}
} else {
alert(data);
}
},
error : function(error) {
console.log(error);
},
complete: function() {
removeOverlay();
},
dataType: "html"
});
return resp;
}
The problem is, when I use asyn is false, then I get the proper value of resp. But beforeSend doesn't work.
In case, I put async is true, then its beforeSend works properly, but the resp value will not return properly, Its always blank.
Is there any way to solve both problems? I would get beforeSend function and resp value both.
Thanks
Use async:false and run the function you assigned to beforeSend manually before the $.ajax call:
var resp = '';
$('.black_overlay').show();
$.ajax({
...
Either that or learn how to use callback functions with asynchronous tasks. There are many nice tutorials on the web.
Take the resp variable out from the function
Create one extra function respHasChanged()
when you get the data successfully, use the code
resp = data;respHasChanged();
You can restructure on this way, (why no use it in async way?)
function ajaxCall(path, method, params) {
return $.ajax({
url: path,
type: method,
data: params,
beforeSend: function() {
$('.black_overlay').show();
},
dataType: "html"
});
}
Call in your javascript file
ajaxCall(YOUR_PATH, YOUR_METHOD, YOUR_PARAMS)
.done(function(data) {
console.log(data);
// DO WHAT YOU WANT TO DO
if (alerter == 0 && obj !== null) {
obj.innerHTML = data;
} else {
alert(data);
}
}).fail(function(error) {
console.log(error);
}).always(function() {
removeOverlay();
});

JQuery ajax stoppen in $.when when server returns 500 error

I make a request to a server with JQuery and the $.when method.
$.when(ajaxRequest(param)).done(function(response){
console.log(responseData);
});
my ajax function looks like this:
function ajaxRequest(param){
var requestedData;
return $.ajax({
type: 'POST',
url: myurl,
data: {
setParam:param
},
error: function(data){
console.log(data);
return(data);
}
});
}
Everything works fine if the server returns a 200 OK. But if there was something wrong the server answers with 500. How can I return the response body to the calling method?
The errorbody is printed with console.log on the ajaxRequest method but its not returned to the calling method?
Given js at Question $.when() is not necessary as $.ajax() returns a jQuery promise object. var requestedData; is not set to a value, would be undefined at .done(); use response available at .then() or .done() as returned data; .then() to handle both success and error responses
function ajaxRequest(param){
return $.ajax({
type: 'POST',
url: myurl,
data: {
setParam:param
}
});
}
ajaxRequest(param)
.then(function(response){
console.log(response);
return response
}
// handle errors at second function of `.then()`
, function err(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
return errorThrown;
});

Ajax - All request are Done/Completed

I have a difficulty to know when all Ajax requests are completed because I need this information to call another function.
Difficulty are to know when my 4/5 function with requests are completed. I use native function of ajax and none is working for me.
I used Chrome, and async requests.
Someone Helps me
I use this(not work):
$(document).ajaxStop(function() {
alert("Completed");
});
and this (not Work):
$(document).ajaxComplete(function() { alert("Completed"); });
Both ways I try use in another function thal calls all requests:
Example:
function Init()
{ Search("123"); Search2("1234"); Search3("12345");
... }
Extract one (of 5 requests,others are very similar ) of my request:
function Search(user) {
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
success: function(response, textStatus, jqXHR) {
try {
if (response != null) {
alert("Have Data");
} else {
alert("are empty");
}
} catch (err) {
alert("error");
}
},
error: function() {
alert("error");
}
}); }
have you tried putting it in a done function? something like...
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP'
}).done(function (data) {
code to execute when request is finished;
}).fail(function () {
code to do in event of failure
});
bouncing off what Michael Seltenreich said, his solution, if i understand where you guys are going with this...might look something like:
var count = 0;
function checkCount(){
if(count == 5 ){
//do this, or fire some other function
}
}
#request one
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
}).done( function(data){
count += 1
checkCount()
})
#request two
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
}).done( function(data){
count += 1
checkCount()
})
and do it with your five requests. If that works out for you please make sure to mark his question as the answer;)
You can create a custom trigger
$(document).trigger('ajaxDone')
and call it when ever you finished your ajax requests.
Then you can listen for it
$(document).on('ajaxDone', function () {
//Do something
})
If you want to keep track of multiple ajax calls you can set a function that counts how many "done" values were passed to it, and once all are finished, you can fire the event.
Place the call for this function in each of the 'success' and 'error' events of the ajax calls.
Update:
You can create a function like so
var completedRequests= 0
function countAjax() {
completedRequests+=1
if(completedRequests==whatEverNumberOfRequestsYouNeed) {
$(document).trigger('ajaxDone');
}
}
Call this function on every success and error events.
Then, ajaxDone event will be triggered only after a certain number of requests.
If you wanna track specific ajax requests you can add a variable to countAjax that checks which ajax completed.

Calling Ajax request function in href

I have an href in an html page and i have an AJAX request in a method in a javascript file.
When clicking on href i want to call the JS function and I am treating the response to add it to the second html page which will appear
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
var request = $.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {client_language: client_language, PIN_code:pin,client_phone:number}
});
request.done(function(msg) {
//alert(JSON.stringify(msg));
});
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
request.error(function(jqXHR, textStatus)
{
//MESSAGE
});
}
I tried with , and also to write the function with $('#idOfHref').click(function(){}); not working.
All I can see is the alert TEST and then nothing happens. I checked several posts here but nothing works for me.
Function can be corrected as,
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {"client_language": client_language, "PIN_code":pin,"client_phone":number},
success : function(msg) {
//alert(JSON.stringify(msg));
if (msg.ws_resultat.result_ok == true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
alert('Error Occured'); //MESSAGE
}
}
});
1. No need to assign ajax call to a variable,
2. Your further work should be in Success part of AJAX request, as shown above.
It's a bad practice use an onclick() so the proper way to do this is:
Fiddle
$(document).ready(function(){
$('#mylink').on('click', function(){
alert('onclick is working.');
miniReport(); //Your function
});
});
function miniReport(){
var client_account_number = localStorage.getItem('numb');
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {
'client_language': client_language,
'PIN_code': pin,
'client_phone': number
},
success: function(msg){
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
//Manage your error.
}
});
}
Also you have some mistakes in your ajax request. So I hope it's helps.
Rectified version of your code with document .ready
$(document).ready(function(){
$("#hrefid").click(function(){ // your anchor tag id if not assign any id
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data:{"client_language":client_language,"PIN_code":pin,"client_phone":number},
success : function(msg) {
if (msg.ws_resultat.result_ok == true)
{
window.open("account_details.html");
}
else
{
alert('some thing went wrong, plz try again');
}
}
}
});
});

.done() jquery not working

Im using the below code for a ajax call
var getRequest = $.ajax({
type: 'GET',
url: Url,
async: false,
dataType: "text",
complete: function () {
$('#loading').hide();
}
});
the request is getting complete and data is also withdrawn after the data is recieved the following:
getRequest.done(function (dataDb) {
if (dataDb) {
alert('dataDb: ' + dataDb);
}
});
getRequest.fail(function (jqXHR, textStatus, error) {
alert('data error within getUsersRequest ' + textStatus + ' : ' + error);
});
I'm recieving a error that getRequest.done(function(dataDb) or getRequest.fail(function(jqXHR, textStatus, error) is not a function.
It is because your JQuery version is too old.
You can use success if you are not willing to upgrade the latest version of JQuery.
success: function(dataDb) {
}
success only fires if the AJAX call is successful from back end, i.e. it returns a HTTP 200 status as response. if any error fires if it fails and complete when the request finishes, regardless of success.
In jQuery 1.8 on the jqXHR object (returned by $.ajax) success is being replaced with the done, error with fail and complete with always.
However you should still be able to initialise the AJAX request with the current syntax. So these do similar things:
// set success action before making the request
$.ajax({
url: '...',
success: function(){
alert('AJAX successful');
}
});
// set success action just after starting the request
var jqxhr = $.ajax( "..." )
.done(function() { alert("success"); });
Last: you need to use .success rather then using .done
You can try using .success.
var getRequest = $.ajax({
type : 'GET',
url : Url,
async: false,
dataType: "text",
complete: function(){
$('#loading').hide();
}
}).success(function(dataDb){
if(dataDb) {
alert('dataDb: '+ dataDb);
}
});

Categories

Resources