Abort ajax request without affecting the next request - javascript

I have a number input and "onChange" event, where I'm triggering this ajax request (see the code).
This aborting affects my next request.
If I'm sending only one request without aborting , the request has a normal speed but if I'm aborting, like 3 requests, the ajax looks like it's sending, in one request, all the aborted requests...
globalAjaxChange = $.ajax({
type: 'POST',
dataType: 'json',
url: ajaxUrl,
data: formData,
processData: false,
contentType: false,
beforeSend: function () {
if (globalAjaxChange != null) {
globalAjaxChange.abort();
}
},
success: function (data) {
if (data['ok'] == false) {
notify(data['msg'], 'error');
}
},
error: function (data) {
if (data.statusText !== 'abort')
notify('message', 'error');
}
});
Here is the network inspection:

Try returning try/false in your beforeSend callback. Unless you need to send the ajax request anyway, jQuery will abort the request for you with a return of false in that function. See the jQuery docs here for more info on the callback methods.
You also might be having a logic or async issue on the set of the globalAjaxChange variable. Which would cause the ajax request to always send by never returning null on your check for globalAjaxChange. Try placing breakpoints around where it sends and gets set at, to see what the values are.

Related

How do I send through ajax each element from the following array?

Send through ajax each element from the following array. Note: Each request must
be made once the previous has finished.
[‘This’, ‘is’, ‘a’, ‘fake, ‘array’]
I am a little confused by this question because I thought Ajax is asynchronous, meaning the script keeps sending requests to the server without waiting for the reply.
***Was downvoted so going to clarify something: It specifically states in the problem statement that the REQUEST must be made synchronously. I do realize that there are better ways of doing this via def/promises asynchronously so order remains for the result but that isn't the request.
Ajax has a async parameter you can set to false which will block until call completion.
Per documentation:
async (default: true)
Type: Boolean
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().
http://api.jquery.com/jquery.ajax/
Example:
$.each(["This", "is", "a", "fake", "array"], function( index, value ) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/echo/json/',
data : { json: JSON.stringify( value ) },
async: false,
success: function(data) { alert(data);}
});
});
Working fiddler example: https://jsfiddle.net/zm9bb4xk/
I was talking about JQuery Ajax.
So, first, based on documentation, Ajax has many events that run at certain times, for example:
beforeSend (Local Event)
This event, which is triggered before an Ajax request is started,
allows you to modify the XMLHttpRequest object (setting additional
headers, if need be.)
error (Local Event)
This event is only called if an error occurred with the request (you
can never have both an error and a success callback with a request).
complete (Local Event)
This event is called regardless of if the request was successful, or
not. You will always receive a complete callback, even for synchronous
requests.
success (Local Event)
This event is only called if the request was successful (no errors
from the server, no errors with the data).
More in documentation.
Second, following your example (you have to complete this with your own data and this code is not tested, maybe it has some small sintax errors), an approximation is:
// Variables
var myArray = ["This", "is", "a", "fake", "array"];
var globalIndex = 0;
// Function for Ajax Calls
function myFunction(){
$.ajax({
url: 'myURL', // Your own controller/url
type: "GET", // Or POST
dataType: "json", // Or other datatype
data: {
arrayContent: myArray[globalIndex] // arrayContent = your controller param name
},
/**
* A function to be called if the request succeeds.
*/
success: function(data) {
alert('Load was performed. Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information! ');
alert(data); // Do what you want with your data, this is an example
globalIndex = globalIndex +1;
// Recursive/next call if current call is finished OK and there are elements
if(globalIndex < myArray.length){
myFunction();
}
},
/**
* A function to be called if the request fails.
*/
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
alert('<p>status code: '+jqXHR.status+'</p><p>errorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
// We don't do a recursive/next call because current call has failed
},
});
}
// First call to myFunction
myFunction();

Ajax request is never entering `success:function(resp){ ...}`

My ajax request is never entering success:function(resp){ ...}
I'm getting a response status of 200 and the Json response obtained is not null.
My ajax function:
$.ajax({
url: '/url/',
type: 'GET',
data: {
pass_value: 0,
req_time_last_ack_update: 0,
},
dataType: "json",
success : function (resp) {
// Compiler is never entering here [I checked with Mozilla debugger]
},
error: function(){
....
}
});
Can anyone please help me find the reason for this failure?
(Question edited for clarification)
If you are trying to step into this directly after the call it will not work.
The Ajax request you are sending happens Asynchronously.
Only as soon as a response is received from the server (this could be several seconds later) you will see a breakpoint being hit (if you set one) inside the success method.

My AJAX responses are getting downloaded rather than getting loaded in success data

I am quiet new to JQuery. I am sending an AJAX request (File Upload) to WEB API (ASP.NET MVC) but my responses are getting downloaded as JSON file rather than the loaded to success data.
Please find the code in the HTML below
$('#myForm1')[0].submit(function (event) {
alert("Hello2");
event.preventDefault();
//grab all form data
var formData = new FormData($(this)[0]);
alert("Hello2");
$.ajax({
url: 'http://localhost:102/webapi/api/values/All',
type: 'POST',
data: formData,
datatype : "json",
//async: false,
//cache: false,
contentType: true,
processData: false,
complete: function () {
alert("Complete");
},
success: function (returndata) {
// $("#productFormOutput").html(returndata);
alert("Executed");
},
error: function () {
alert("error in ajax form submission");
}
});
return false;
});
BTW no alert messages in success, error and complete is called after getting the response. But Fiddler shows the response is successful (HTTP 200). Is anything am I doing wrong while calling the request?
try using "done" method as the success handler instead of "success",
and instead of alert use console log(you can check the log on the browser, ctrl+shift+I on chrome, you can even put object to be logged).
after several times alert my be blocked by browser as it is annoying.
easy and complete reference: https://scotch.io/tutorials/submitting-ajax-forms-with-jquery
*what is the complete method doing in that post object ?
Removing [0] and changing the input to 'submit' in form solved my problem
$('#myForm1')[0].submit(function (event)
As Roland said, submit with button in input tag is not handling the event handler

Making 2 AJAX jquery to work synchronous

I have requirement to manage 2 AJAX jQuery functions to start a process in the server and get the status from the server.
I,e. The first AJAX JQuery which will send a request to the server to start a particular process and returns back to the client with the status 'process-running'. The second AJAX JQuery function which will be called inside the success block of first function and its responsibility to query the status until it gets the response 'process-complete'.
Here is the psedo code I have
//This function which will be called on a button click
function buildApplication(){
//show the gif spinner in the front-end
$.when(buildApp()).then(function(result){
console.log('process-completed');
//hide the gif spinner in the front-end
});
}
function buildApp(){
return $.ajax({
type: 'POST',
url: 'url pointing to php script',
data: dataString,
cache: false,
success: function(result){
if(result == 'process-running'){
console.log('monitor starts');
getAppStatus();
console.log('monitor ends');
}
},
error: function(result){
}
});
}
function getAppStatus(){
console.log('Querying server');
return $.ajax({
type: 'POST',
url: 'url pointing to php script',
data: dataString,
cache: false,
success: function(result){
if(result == 'process-running'){
getAppStatus();
}
},
error: function(result){
}
});
}
The sleeping process is handled inside the PHP script of getAppStatus. I.e, If process is still running then the server will sleep for 10 seconds and then only returns response to the client.
The problem is both the functions are running asynchronous. That means the buildApp function invokes the getAppStatus function and just returns back immediately. The getAppStatus function runs as an orphan process.
How can I make it both synchronous (or similar) so that the parent caller will wait till the child to return back?
Note: I tried the async:false in the getAppStatus function but it freezes the browser and the ajax loader image stops spinning and it looks like hanged.

Wait for Async ajax to complete before moving onto other code?

I know this has been asked, probably, a million times, but for the life of me I cannot get anything to work.
I have a UI wizard control that on the "changed" event validates the model. If the model is not valid, it doe not allow the user to move forward in the wizard. I have tired using the $.when().done() feature in jquery, but my code still passes through before making sure the model is valid. The reason for calling an async ajax request is I do not want the UI to lock up so I can show some sort of progress indicator. I had set the async property to false, but my UI indicator would never show up. Here is an example of what my code is doing:
//the change event that is called when the user clicks 'next' on the wizard:
wizard.on('change', function (e, data) {
var isValid = $.validate({
"Model": [The_UI_MODEL],
"Url": [URL_To_Server_Validation],
"Async": true, //tells ajax request to send as async
});
//Tells the wizard not to move 'next' if the request comes back as not valid
if (data.direction === 'next' && !isValid) {
e.preventDefault();
}
}
//I am using the $.extend method for JQuery to create a function that will validate any model in my system.
validate: function(options) {
//Clear any previous validation errors
$.clearValidations();
var data = $.postJson(options);
//the result is getting returned before the $.postJson(options) finishes
return data.Success;
}
//I created my own method that extends the $.ajax method so I could do other things before /after a request:
postJson: function(options){
...other code for my application
//This is where I want the ajax request to happen and once done return the data coming back
//This is what I have tried, but it is not doing what I thought.
$.when(function(){
return $.ajax({
url: options.Url,
type: 'POST',
cache: false,
async: options.Async,
timeout: options.Timeout,
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(options.Model),
error: function(xhr, status, error) {
...do stuff if ajax errors out
},
success: function (data) {
},
});
}).done(function(response){
//looks like i get back the responseText of the request. which is fine, but other posts i have read stated i should be getting back the request itself
...other UI stuff
return response;
})
}
KarelG is absolutely right. You need to refactor your code and do your valdiation check within the success callback of the ajax request.
Something like this...
wizard.on('change', function (e, data) {
$.ajax({
url: [URL_To_Server_Validation],
type: 'POST',
cache: false,
async: true,
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: {"Model": [The_UI_MODEL]},
success: function (response) {
//Tells the wizard not to move 'next' if the request comes back as not valid
if(!response & data.direction === 'next')
{
e.preventDefault();
}
}
});
});
It looks like you're trying to write asynchronous code as if it were synchronous. An asynchronous call such as your $.validate() will return immediately without a result and continue on to the rest of your code. Anything you want to happen when the validate call finishes must be done in a callback function passed to it.
You can use jQuery promises (when, then, done, etc.) or another library such as async.js to help manage the control flow.
Also, this isn't particularly useful now since there's little to no browser support for it yet, but the yield operator plus a library such as Task.js will eventually let us write asynchronous code as if it were synchronous.

Categories