I'm using Jquery ajax to check registration form.
this is my code:
$("input.register_input").each(function() {
name= this.name;
$(".ono#"+name).html("<img src='images/ajax-loader.gif'>");
if (name == 're_password') {
var dts = this.name+"="+$(this).val()+"&pass="+$("input[name='password']").val();
} else {
var dts = this.name+"="+$(this).val();
}
$.ajax({
type: "POST",
url: "ajc/register_check.php",
data: dts,
success: function(resultfrompage){
$(".ono#"+name).html(resultfrompage);
}
});
});
This is after user submitting the form. so I can't check all values at once.
I dont completly sure if that's the problem, but I this the each() loop is running before the ajax request is done so I'm getting only 1 value (last one) back. and all the rest still showing ajax-loader.gif.
This is the reason for the problem? and if so how can I fix it?
thank you!
Try t use async:false.
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() or the deprecated jqXHR.success().
$("input.register_input").each(function() {
name= this.name;
$(".ono#"+name).html("<img src='images/ajax-loader.gif'>");
if (name == 're_password') {
var dts = this.name+"="+$(this).val()+"&pass="+$("input[name='password']").val();
} else {
var dts = this.name+"="+$(this).val();
}
$.ajax({
type: "POST",
async: false,
url: "ajc/register_check.php",
data: dts,
success: function(resultfrompage){
$(".ono#"+name).html(resultfrompage);
}
});
});
I suggest you to show some loading image while the Ajax request is processed. This way the user will understand that something is going on in the background. When this process will be finished handle the response.
Related
Refresh information, only when it's new, not always.
Updating data just when differs from response.
<script>
$(document).ready(function(){
setInterval(function() {
$.ajax({
type : "POST",
url : "steam.php",
cache : false,
success : function(response) {
var parsedResponse = $.parseJSON(response);
$("#Display, [class='card-title display']").html(parsedResponse.display, parsedResponse.display);
$("#AvatarFull, #AvatarSmall").attr("src", parsedResponse.avatar, parsedResponse.savatar);
$("#Steam").attr("value", parsedResponse.display);
}
});
}, 1000)
});
</script>
You could achieve this by storing the response in a variable then comparing the new response. If they are the same, don't perform any action.
Also note that html() and attr() only accept one and two arguments respectively, so the last one in each call can be removed. In any case it's preferred practice to use prop() over attr(). In addition use val(), not attr() to update the value of a control. Try this:
$(document).ready(function() {
let lastResponse;
setInterval(function() {
$.ajax({
type: "POST",
url: "steam.php",
cache: false,
success: function(response) {
if (response != lastResponse) {
var parsedResponse = $.parseJSON(response);
$("#Display, [class='card-title display']").html(parsedResponse.display);
$("#AvatarFull, #AvatarSmall").prop("src", parsedResponse.avatar);
$("#Steam").val(parsedResponse.display);
lastResponse = response;
}
}
});
}, 1000)
});
With all that being said I'd strongly suggest you use the observer pattern for this instead of AJAX polling. This is because it puts far less strain on the server resources and you can configure it to only send updates when new information is available. If you want to know more about this research Websockets and SignalR.
I have two ajax calls, one using .post() and the other using .ajax() (for testing). One is triggered as an interval check and the other send mail under a foreach loop. The problem is that the interval check only returns the results once the second ajax call has finished, not during - which is want I want to achieve. I get the results I want - just at the end of t My current code is:
$("#cdj-email-members").click(function() {
$(".cdj-email-content").slideUp();
$(".cdj-send-email").show();
// Disable the buttons
$("#save-email").hide();
$("#cdj-email-members").hide();
$("#cdj-test").attr('disabled','disabled');
// Declare the variables
var cdj_subject = $("#cdj-email-form #subject").val();
var cdj_content = $("#cdj-email-form textarea").val();
var cdj_fan_count = $("#cdj-progressbar").prop('max');
var cdj_email_members_nonce = $("#cdj_email_members_nonce").val();
// Set the interval check
setInterval(function(){
var data = {
'action': 'cdj_update_progress_bar',
};
$.post(cdjAjax.ajaxurl, data, function(response) {
var result = jQuery.parseJSON(response);
console.log(result);
$("#cdj-progressbar").attr('value', result);
});
},500);
// Send the Ajax request
$.ajax({
url: cdjAjax.ajaxurl,
type: 'POST',
data: {
action: 'cdj_email_members',
nonce: cdj_email_members_nonce,
'fan_count': cdj_fan_count,
'subject': cdj_subject,
'content': cdj_content
},
cache: false,
success: function(data) {
// Retreive the WordPress response
var status = $(data).find('response_data').text();
var message = $(data).find('supplemental message').text();
if(status == 'success') {
console.log(message);
$(".send-email-success").slideDown();
$(".send-email-success p.message").text(message);
$(".send-email-success").delay(4000).fadeOut();
// Enable the buttons
$("#save-email").show();
$("#cdj-email-members").show();
$("#cdj-test").prop('disabled', false);
// Switch back to content view
$(".cdj-email-content").delay(2000).slideDown();
$(".cdj-send-email").delay(2000).hide();
}
else {
console.log(message);
$(".send-email-error").slideDown();
$(".send-email-error p.message").text(message);
$(".send-email-error").delay(4000).fadeOut();
}
}
});
});
Thanks
The thing is that setInterval(function() {..},500); calls the function every 500ms, but the first call will only be áfter the first 500ms has passed, not immediately.
That's why $.ajax runs first.
What also happens is that both calls are over HTTP, and depending on your server configuration (simply said) two calls to the same URL can be lined up in a queue, so that's why $.ajax waits for $.post to finish.
To fix I would put the setInterval inside the $.ajax success function (making sure $.ajax gets called first, then running $.post in a 500ms interval afterwards)
I've posted a question about it already, but I've figured out what is the exact problem. Now, I need a solution for that :)
Here's my code:
$('input[type="text"][name="appLink"]').unbind('keyup').unbind('ajax').keyup(function() {
var iTunesURL = $(this).val();
var iTunesAppID = $('input[name="iTunesAppID"]').val();
$.ajax({
type: 'POST',
url: jsonURL,
dataType: 'json',
cache: false,
timeout: 20000,
data: { a: 'checkiTunesURL', iTunesURL: iTunesURL, iTunesAppID: iTunesAppID },
success: function(data) {
if (!data.error) {
$('section.submit').fadeOut('slow');
//Modifying Submit Page
setTimeout(function() {
$('input[name="appLink"]').val(data.trackViewUrl);
$('div.appimage > img').attr('src', data.artworkUrl512).attr('alt', data.trackName);
$('div.title > p:nth-child(1)').html(data.trackName);
$('div.title > p:nth-child(2)').html('by '+data.sellerName);
$('span.mod-category').html(data.primaryGenreName);
$('span.mod-size').html(data.fileSizeBytes);
$('span.mod-update').html(data.lastUpdate);
$('select[name="version"]').html(data.verSelect);
$('input[name="iTunesAppID"]').attr('value', data.trackId);
}, 600);
//Showing Submit Page
$('section.submit').delay('600').fadeIn('slow');
} else {
$('.json-response').html(data.message).fadeIn('slow');
}
},
error: function(jqXHR, textStatus, errorThrown) {
//$('.json-response').html('Probléma történt! Kérlek próbáld újra később! (HTTP Error: '+errorThrown+' | Error Message: '+textStatus+')').fadeIn('slow');
$('.json-response').html('Something went wrong! Please check your network connection!').fadeIn('slow');
}
});
});
The Problem and Explanation:
Every time a key is triggered up it loads this ajax. If my JSON file finds a keyword it returns with error = false flag. You see, if it happens, it loads the effects, changing, etc...
The problem is that when you start to type, for example asdasdasd and just after that I paste / write the keyword there'll be some ajax queries which ones are still processing. These ones are modifying and loading the fadeOut-In effects X times.
So I'd need a solution to stop the processing ajax requests, while an other key is pressed!
Thanks in advance,
Marcell
Personally I would have the script wait so it didn't fire on each keyup. Actually I would probably use http://jqueryui.com/autocomplete/
But you can just abort the ajax before trying again.
...
var iTunesAppID = $('input[name="iTunesAppID"]').val();
if (typeof req!='undefined' && req!=null) req.abort();
req = $.ajax({
...
try adding the option async: false to your ajax this will prevent any other calls until the current one is finished.
I have multiple check boxes for users to select and based on selected checkboxes i need to make a jquery ajax call. For that i used FOR loop to iterate through selected elements array and sent ajax request for each checkbox. Each request takes more than 5-10 minutes. In current scenario it calls all ajax request simultaneously.
I want to call next ajax calls only after finishing earlier ajax request.
Is there any solution for this?
You can make recursive calls.
function sendAjax(id) {
var checkbox = $('input[type=checkbox]:eq('+id+')','#formid');
if(checkbox == undefined)
return;
$.ajax({
type: 'POST',
dataType: "json",
url: 'url',
data: { },
success: function (data) {
sendAjax(id+1);
},
error: function (data) {
alert(data.responseText);
}
});
}
sendAjax(0);
Iterate in your readyStateChange method instead of in the for loop.
...
array_index++;
var data = selected_elements[array_index];
if (data) {
send_ajax_request(data);
}
}
That is kind of against the whole point of ajax. The first "a" is usually considered to mean "asynchronous", but you want to make the request synchronous (async = false I believe in jQuery)
Using recursive call, until previous ajax request not finished, next request cant be processed. So recursive call can solve the problem of these ajax request.
var queue_element = ["a","b","c","d","e","f","g"];
var execute_queue = function(i){
$.ajax( {
url: queue_element[i],
success: function({
i++; // going to next queue entry
// check if it exists
if (queue_element[i] != undefined){
execute_queue(i);
}
}
}); // end of $.ajax( {...
}; // end of execute_queue() {...
var index = 0;
execute_queue(index); // go!
Hi I have a jQuery ajax request for a login system. At first, it worked very well. But after a few try, it just started to show negative response. I checked firebug and it says that the response is, in my case "Connected". But the ajax response just shows "Not_connected". I don't know what to do :(. Please help me.
This is my jquery code :
var data_str = "username="+usrn+"&password="+pwd;
$.ajax({
type: "POST",
url: "index.php?rnd=" + Math.random(),
data : data_str,
complete : function(xhr,data){
if(data == 'connected'){window.location.href = 'admin.php';}
else if(data = 'not_connected'){ error_gen.html('Invalid username or password'); }
alert(data);
}
});
AS for the PHP code :
$log_result = $u_obj->login_user();
if($log_result == true)/*user is connected*/
{
echo 'connected';
exit;/*stoping the script after sending the result*/
}
elseif($log_result == false)/*error while logging in*/
{
echo 'not_connected';
exit;/*stoping the script after sending the result*/
}
Look at this thread: Is it possible to cache POST methods in HTTP?
It might be that there are headers which now make browser caching the response (although it's POST).
Also instead of rnd=" + Math.random() you can add write
$.ajax({
type: "POST",
cache: false,
..
Could it be browser caching?
Try adding this $.ajaxSetup({ cache: false });
You are using the wrong $.ajax option to retrieve the result. You should use the success option. Just change the
complete : function(xhr,data){
line for
success : function(data){
It should work.