JQuery AJAX async false not working on Chrome - javascript

I'm writing a jQuery for send list of form datas one by one to server.
It working perfectly on Firefox, but when i use chrome it's sending all data at once
Here is my code
$('.frmroldcon').each(function(){
var thobj=this;
$(thobj).prev().prev().prev('.failedicoconold').hide();
$(thobj).prev('.doneicoconold').hide();
$(thobj).prev().prev('.proccesicoconold').show();
fuser = jQuery('input[name="fusername"]',thobj).val();
fpass = jQuery('input[name="fpassword"]',thobj).val();
$.ajax({
type: "POST",
async: false,
cache:false,
url: "checkcon.php",
data: { checkcons: "1", fusername: fuser, fpassword: fpass},
success: function(data){
$(thobj).prev().prev('.proccesicoconold').hide();
if(data==0){
$(thobj).prev().prev().prev('.failedicoconold').show();
window.errc=window.errc+1;
}
else{
$(thobj).prev('.doneicoconold').show();
}
}
});
});
I'm using jQuery version 2.1.4, also tried other old versions like 1.4 but it seems not working.
Can anyone give me a solution for this or alternative for submit each forms data to server one by one,
Thanks a lot

A quick way to do serial, asynchronous, ajax requests using jQuery's $.when
var requests = [];
$('.frmroldcon').each(function() {
$.when.apply($,requests).then(function() {
requests.push($.ajax({/* your ajax request */});
});
});
You haven't shown the requirement to have to do these requests serially, however. And if you can do everything you need to do with 1 call to the server instead of 60, then that's the way you should be doing it.

Related

PHP doesnt see posted data from ajax by serializeArray()

I have a form, running through jquery validation which then submits via ajax to a PHP script to handle backend functions. Ajax collects form values through serializeArray() and looks to do the job. Script fires and data is sent through(I think) to PHP. I've tried probably close to 100 combinations to receive the data at the PHP side but with no luck. I'm convinced this must be simple, something I've overlooked. Code for the ajax is below, along with a screenshot of developer tools showing what's being sent.
No matter what I try on the PHP side, I either get an empty array, NULL through $_POST/$_GET. I've tried json_decode, parsing the string, var_dump etc.
var data=$(form).serializeArray();
$.ajax({
cache: false,
type: "POST",
dataType: "JSON",
url: "process/create_site.php",
data: data,
success: function(response) {
console.log(response);
//$(form).html("<div id='message'></div>");
//$('#message').html("<h2>Your request is on the way!</h2>")
// .append("<p>someone</p>")
// .hide()
// .fadeIn(1500, function() {
// $('#message').append("<img id='checkmark' src='images/ok.png' />");
// });
}
});
I managed to get to the bottom of this, after an embarrassing amount of time. I'd like to post the simple reason here to help others.
The entire JS block was wrapped in $(document).ready(function(){
which was causing the values to be stripped when posting to the PHP.
I can't find any documentation or answer to a question with a similar scenario - so here it is!

Only IE 11 losing focus on ajax call sometimes ASP.NET MVC4

I am using a boostrap dialog box to pull in a list with a quantity. After I submit my form, and open the dialog box to check to see if the quantity has updated, it seems to be stale data. I have a call with ajax to the controller and then back to the database to pull in updated info. But when I set a breakpoint in the controller (on server side) it never hits. IT ONLY kicks out of the issue when I set a breakpoint to the function calling ajax within developer tools and debugger. I don't see any console errors either.
I don't have an issue with Firefox, just IE11.. here is the code:
<script type="text/javascript">
function LocationModal() {
$("#GetLocBtn").attr("disabled", "disabled");
var partNumber = $("#PartNum").val();
var Condition = 'Z';
var urlQry;
var receiveIsChecked = document.getElementById('Receive').checked;
var src = 'removed for security';
$.ajax({
type: "GET",
url: src,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { partNumber: partNumber, CCODE: Condition },
beforeSend: function () {
},
success: function (data) {
$("#LocationModalContainer").html(data.LocationModal);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
};
The problem is indeed that IE caches the results of Ajax calls. You can prevent that behavior either by adding cache: false to every call, like you've discovered, or setting it globally via ajaxSetup before you make any calls.
$.ajaxSetup({
cache: false
});
The use of ajaxSetup is discouraged in the jQuery documentation, but might be a good solution for you if you don't use any plugins that might rely on the normal behavior and want to quickly make sure none of your own ajax calls is cached.
Personally, I have my doubts about how real the interference risk mentioned in the documentation is when it comes to the cache setting, since basically you just make IE behave like other browsers.

jQuery when, then executing in browser but not on mobile device?

Following code snippet:
$.ajax({
url: 'actions.xml',
cache: false,
dataType: 'xml'
}).done(function(data) {
$(data).find('script').each(function() {
deferreds.push($.ajax({
url: $(this).text(),
dataType: 'script'
}));
});
$.when.apply($, deferreds).then(function() {
$('.preloader').fadeOut();
...
});
});
On the browser, this code executes without a problem. The preloader fades out and everything is fine. On a mobile project via cordova, I get a problem. The $.when.apply part doesn't seem to execute. The preloader is never fading out and because of this the app is not working. Does anyone know, why this is happening?
The deferreds array has the same values as in the browser. I tested this via alert(JSON.stringify(deferreds));
I have figured this out by setting some alerts and could come down to this specific problem. It is definitely crashing at this point.
I have to finish this thing due today and I tried different things like setting timeouts, putting other things in function, etc, to solve this, but nothing seems to work and maybe an expert in this has the solution in two seconds.
You could avoid sending too many requests at same time but one by one using this kind of logic:
$.ajax({
url: 'actions.xml',
cache: false,
dataType: 'xml'
}).done(function (data) {
var queue = $.Deferred().resolve();
$(data).find('script').map(function () {
return $(this).text()
}).get().forEach(function (url) {
queue = queue.then(function () {
return $.ajax({
url: url,
dataType: 'script'
}).promise();
})
});
});
Be aware, maybe your issue is just because IOS simulator, you should test your original code on an IOS device (if not already done), and see if same issue persists.

How to wait for an async call from a callback using jQuery?

I'm using the select2 jQuery based replacement for combo boxes, and I have to define a callback to process the data I receive from a json rest web service.
The problem is that, in the same callback, I have to issue another GET request to get the total numbers of matching records, so that select2 can decide if it has to load more results (it has an infinite scroll feature)
The code is something like this:
$("#country").select2({
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: 'http://localhost:9000/api/countries',
dataType: 'json',
data: function(term, page) {
return {
filter: term,
page: page,
len: 10
};
},
results: function(data, page) {
return {
results: data, more: ????
};
}
}
});
The problem is I don't know how to issue an async request (I'm issuing a cross-domain request, and the docs says async is not supported in that case) and wait for it to finish before returning form the results callback.
The example from select2 page is like this:
results: function (data, page) {
var more = (page * 10) < data.total; // whether or not there are more results available
// notice we return the value of more so Select2 knows if more results can be loaded
return {results: data.movies, more: more};
}
The problem is that my web service returns the total number of records from a different endpoint, so I have to make another request, like this: http: //localhost:9000/api/countries?filter=term
any idea?
You can't wait for an async callback in javascript. You have to restructure your code to do all future work based on the async response from the actual callback.
If you need to make multiple consecutive ajax calls, then you issue the first one and in the success handler or response handler for the first ajax call, you issue the second ajax call and in the response handler for the second one, you carry out whatever you want to do with the data.
If see that you're using the .select2() framework. In the framework, the results callback is where the ajax call returns. It would be in that function that you would issue the second ajax call using normal jQuery ajax calls and in the success handler from that second ajax call, you would carry out whatever you're trying to do with the eventual data you got back. You won't be able to use the normal return value of the results callback because you won't have your final data yet at the point you need to return. I think this is just a limitation of .select2() in that it only supports a single ajax call. It just means you can't use a little bit of the built-in behavior and have to apply the result yourself with your own code, but it doesn't mean you have to throw out .select2() for everything else you were using it for.
It looks like you might want to just hook the change event directly and not use their built-in ajax stuff since it doesn't look like it really provides you with much if you need two serialized ajax calls.
I studied the source code on select2, and finnally came out with this solution
var ajax = {
url: 'http://localhost:9000/api/countries',
len: 3,
};
$("#country").select2({
query: function(options) {
var data = {
filter: options.term,
page: options.page,
len: ajax.len
};
$.ajax({
url: ajax.url,
data: data,
dataType: 'json',
type: 'GET',
success: function(data) {
$.ajax({
url: ajax.url + '/count',
data: { filter: options.term },
dataype: 'json',
success: function(resp) {
var total = parseInt(resp, 10);
var more = (options.page * ajax.len) < total;
options.callback({results: data, more: more});
}
});
}
});
},
});
As you can see, when te first fetch (ajax.url) completes I issue another request (ajax.url + '/count') and only when this second request completes I call options.callback, efectively serializing both ajax calls...
In fact the ajax function from select2 has more functionality, such as throttling and dropping out-of-order responses, I just ported them too, but I left them out of this response in order not to complicate the example...
In addition to jfriend00's answer (which is excellent, BTW) I found the followgin workaround, which is basically to issue the request synchronously, which in spite jquery docs it seemd to work (at least with chromium 18.0 and jquery 1.8.0)
I'm just posting it in case anybody find it useful...
var config = {
url: 'http://localhost:9000/api/countries',
len: 20,
term: ''
}
$("#country").select2({
ajax: {
url: config.url,
dataType: 'json',
data: function(term, page) {
config.term = term;
return {
filter: term,
page: page,
len: config.len
};
},
results: function(data, page) { // parse the results into the format expected by Select2.
var more = false;
$.ajax({
url: config.url + '/count',
data: { filter: config.term },
cache: false,
async: false,
success: function(resp) {
var total = parseInt(resp, 10);
more = (page * config.len) < total;
},
async:false
});
return {
results: data, more: more
};
}
}
});

AJAX Load Content

Im completely lost on how to work AJAX. Looked up some tutorials and all seemed pretty confusing. I ran into the problem: [ Script only runs once ].
I would use it to reload pages like so: [ http://www.roblox.com/Poison-Horns-item?id=62152671 ] so I could get the latest item prices, without refreshing the page. if anyone could help/tell/point me in the right direction, it'd help TONS.
Im somewhat a beginner scripter, so be a little patient ;)
Thanks for any help,
Alex
AJAX requests are the same as page requests (GET and POST), except that they are handled asynchronously and without leaving the current page. The response data is the source of the page you wanted to fetch. That source is useless until you parse/use it.
A simple jQuery example:
//for example, we are on example.com
$.ajax({
type : 'get', //the METHOD of the request, like the method of the form
url : 'index.php' //the url to fetch
data : { //additional data which is synonymous to:
query1 : 'foo', // - url queries
query2 : 'bar', // - form inputs
query3 : 'baz',
},
success : function(resposeText){ //response text is the raw source of the fetched resource
$(element).html(responseText); //use response as HTML for element
}
});
//this is similar to requesting:
http://example.com/index.php?query1=foo&query2=bar&query3=baz
agree with joseph. You can use ajax by javascript manner or by jQuery, I personally suggest jQuery because it is simple to implement.
$.ajax({
type: 'GET',
url: "URL you want to call" ,
data: 'Data you want to pass to above URL',
cache: true, //to enable cache in browser
timeout: 3000, // sets timeout to 3 seconds
beforeSend: function() {
//when ur ajax call generate then u can set here loading spinner
},
error: function(){
// will fire when timeout is reached
},
success: function(response){
//in response you can get your response data from above called url.
}
});

Categories

Resources