How to show only the last ajax request result - javascript

Total up the amount of the ajax request and show the ajax response when it is the last ajax response.
In other words, how to use only the response of last sent ajax request.
var req=0;
function ajaxReq(){
req++; /total up the amount of request/
$.ajax({
url: "result.php",
type: 'GET',
contentType: false,
enctype: 'multipart/form-data',
cache: false,
processData: false,
success: function(response) {
if(req==1){ /show the response when this is the last request/
$("#response-element").html(response);
}
req--; /Subtract when every success ajax response/
}
});
}
I using this on viewing messages detail
if the user clicked few threads before the response show out it will show the previous thread detail before the current selected thread detail shown out
Any better solution would be nice for sharing

You should decrement as soon as you send request.
var req=""; // should be a number
function ajaxReq(){
req++; /total up the amount of request/
$.ajax({
url: "result.php",
type: 'GET',
contentType: false,
enctype: 'multipart/form-data',
cache: false,
processData: false,
beforeSend: function() {
if (req > 1) req -= 1;
},
success: function(response) {
if(req==1){ /show the response when this is the last request/
$("#response-element").html(response);
req -= 1;
}
}
});
}

You are more or less on the right lines. This is the only way you can avoid the callbacks of previous calls. You will have to associate an ID with each request and then check if the ID of the request is the last sent request.
var sentReqCount = 0;
setInterval(function() {
sentReqCount++;
ajaxReq(sentReqCount);
}, 100);
function ajaxReq(thisReqId) {
$.ajax({
url: "result.php",
type: 'GET',
contentType: false,
enctype: 'multipart/form-data',
cache: false,
processData: false,
success: function(response) {
if (thisReqId === sentReqCount) {
$("#response-element").html(response);
}
}
});
}

Related

Checking if form has been submitted via ajax - PHP

As the title says, I wanna check if this ajax method has been submitted or not and show the result in a condition.
Here is the Ajax POST code;
$.ajax({
url: "addorderInfo.php", // Url to which the request is sent
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false,
success: handleResult
});
And here is the condition I put but it is not working.
function handleResult(data){
if(data == 'error'){
window.location.href ='404.php';
}
else{
$( "#clearcart" ).click();
window.location.href = "ordercomplited.php";
}
}
try this
$.ajax({
url: "addorderInfo.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function (data) {
alert(data)
},
error: function (error) {
alert(error.responseText) // if your request doesn't work
}
});
There isn't sufficient code to know why is not working.
IMHO the ajax call is not handling the error. Try to edit your code as follow:
$.ajax({
url: "addorderInfo.php", // Url to which the request is sent
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false,
success: function(data) {
handleResult(data);
}
error: function(data) {
handleError(data);
}
});

Two ajax requests on same event at same time . what should be the typical behaviour? how it is different if request is synchronous

In the following javascript code, I am sending two Ajax request at the same time.
After analysis using Firebug, I came to unusual conclusion that :
"which ever (Ajax) response is coming first is printing last".
Problem 2: if I assign the Ajax url destination to a random string (say "abcd") [which don't exist] then total number of ajax call will be increased to 3?
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).serialize();
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$("#loadingimg").show();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
alert ("a");
// $("#result").html(returnhtml);
// $("#loadingimg").hide();
}
});
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
// $("#duplicate").html(returnhtml);
// $("#loadingimg").hide();
alert("b");
}
});
});
});
Please refer the following Fiddle.
Gaurav, you have an error, at the end of the 1st $.ajax it must end as ), and 2nd as ).
You can't end with ;
var result1;
var result2;
$.when(
$.ajax({ // First Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result1 = returnhtml;
}
}),
$.ajax({ //Seconds Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result2 = returnhtml;
}
})
).then(function() {
$('#result1').html(result1);
$('#result2').html(result2);
});
I'm not sure I completely understand, but I will try to give you some information. Like David said It may seem that the first request is the last one responding, but that will vary under many circumstances. There are different ways you could do this to control the outcome or order of the requests.
1) Upon success of the first request you could initiate the second request. I don't recommend this for speed purposes as your requests aren't running in parallel.
$.ajax({ // First Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$.ajax({ //Seconds Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
// $("#duplicate").html(returnhtml);
// $("#loadingimg").hide();
alert("b");
}
});
alert ("a");
// $("#result").html(returnhtml);
// $("#loadingimg").hide();
}
});
2) If you need to have both requests responses at the same time, the preferred method would likely be jQuery deferred. This will make both requests run in parallel, and once both responses are received you can proceed as you would have.
Something Like this:
var result1;
var result2;
$.when(
$.ajax({ // First Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result1 = returnhtml;
}
});
$.ajax({ //Seconds Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result2 = returnhtml;
}
});
).then(function() {
$('#result1').html(result1);
$('#result2').html(result2);
});
Check out:
https://api.jquery.com/jQuery.when/
http://api.jquery.com/deferred.then/
https://api.jquery.com/deferred.done/
I hope this helps!
Or use server_response in your code. The script begin with condition:
if (recherche1.length>1) {
$.ajax({ // First Request
type :"GET",
url : "result.php",
data: data,
cache: false,
success: function(server_response){
$('.price1').html(server_response).show();
}
}),
$.ajax({ //Seconds Request
type :"GET",
url : "result2.php",
data: data,
cache: false,
success: function(server_response){
$('.price2').html(server_response).show();
}
});
}
var result1;
var result2;
$.when(
$.ajax({ // First Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result1 = returnhtml;
}
});
$.ajax({ //Seconds Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result2 = returnhtml;
}
});
).then(function() {
$('#result1').html(result1);
$('#result2').html(result2);
});

avoid showing values in url with jquery ajax

I am making ajax call to login with spring security but it shows username and password in the url no matter what.
ex: /?j_username=s&j_password=s
I am trying to find my mistake for a long time but I couldnt be able to see it. It is probably a small mistake.
here is my ajax call;
function performLogin() {
var j_username = $("#j_username").val();
var j_password = $("#j_password").val();
$.ajax({
cache: false,
type: 'POST',
url: "/login",
crossDomain: true,
async: false,
data: { 'j_username': j_username, 'j_password': j_password},
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("x-ajax-call", "no-cache");
}
});
}
Thanks
EDIT:
It is resolved by adding `return false;`
But I am not sure if my approach is good. Here is the update;
'function performLogin() {
var j_username = $("#j_username").val();
var j_password = $("#j_password").val();
$.ajax({
cache: false,
type: 'POST',
url: "/Mojoping2/login",
crossDomain: true,
async: false,
data: { 'j_username': j_username, 'j_password': j_password},
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("x-ajax-call", "no-cache");
},
success: window.location.reload()
});
return false;
}
It has nothing to do with the Ajax call. You are not cancelling the form submission!
function performLogin() {
var j_username = $("#j_username").val();
var j_password = $("#j_password").val();
$.ajax({
cache: false,
type: 'POST',
url: "/login",
crossDomain: true,
async: false,
data: { 'j_username': j_username, 'j_password': j_password},
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("x-ajax-call", "no-cache");
}
});
return false;
}
and however you are adding the event
onsubmit="return performLogin();
If you are using jQuery to attach the event, you can use
function performLogin(evt) {
evt.preventDefault();
...
I created a jsfiddle to test your code and have been unable to replicate your bug. The POST request appears to submit normally (going via the chrome dev tools), and no extra GET values are appearing for me.
Demo: http://jsfiddle.net/5EXWT/1/
Out of interest, what version of jQuery are you using?
{this is just here so i can submit the jsfiddle}

Ajax Call waiting for the response of another Ajax Call?

I have two ajax call that cannot be done in one call. When the first ajax call starts the second ajax call can start immediately or whenever the user presses a send button. If the second ajax call starts he has to wait for the response of the first ajax call because he needs data from it.
How can I achieve that the second ajax call sends his request only after the first ajax call's response has been arrived?
Is there another way than setTimeout?
Can I register a listener for ajax call 2 on ajax call 1 somehow?
My code would be:
var xhrUploadComplete = false;
// ajax call 1
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
complete: function(response) {
var returnedResponse = JSON.parse(response.responseText);
xhrUploadComplete = true;
}
});
// ajax call 2
if (xhrUploadComplete) {
$.ajax({
url: url2,
type: "POST",
data: formdata2,
processData: false,
contentType: false,
complete: function(response) {
...
}
});
}
Edit: The second ajax call cannot be posted in done() or complete() of the first call, because it depends on the users choice to send the final form. The purpose of this two step process is to send an image to the server just after the user had inserted it to an input type=file.
Edit: In know that I cannot the the if(..) because this is an async call. I wrote it to make clear what I need to do. I think I need something like a future in Java.
xhrUploadComplete will be set to true asynchronously (in the future, when the request has finished) so your if-condition (that is evaluated right after the request is started) will never be fulfilled. You cannot simply return (or set) a value from an ajax call. Instead, move the code that waits for the results into the handler that would have set/returned the variable:
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
complete: function(response) {
var returnedResponse = JSON.parse(response.responseText);
$.ajax({
url: url2,
type: "POST",
data: formdata2,
processData: false,
contentType: false,
complete: function(response) {
…
}
});
}
});
With the Promise pattern you can compose those even more elegantly:
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false
}).then(function(response) {
var returnedResponse = JSON.parse(response.responseText);
return $.ajax({
url: url2,
type: "POST",
data: formdata2,
processData: false,
contentType: false
});
}).done(function(response) {
// result of the last request
…
}, function(error) {
// either of them failed
});
Maybe you need also need this:
var ajax1 = $.ajax({
url: url, …
}).then(function(response) {
return JSON.parse(response.responseText);
});
$(user).on("decision", function(e) { // whatever :-)
// as soon as ajax1 will be or has already finished
ajax1.then(function(response1) {
// schedule ajax2
return $.ajax({
url: url2, …
})
}).done(function(response) {
// result of the last request
…
}, function(error) {
// either of them failed
});
});

How to set cookie value with AJAX request?

I want to set a cookie value on an AJAX request but the code below doesn't work.
$.ajax({
type: "GET",
url: "http://example.com",
cache: false,
setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
success: function (data) {
alert(data);
});
How can I set cookies in the header?
Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:
type: "GET",
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: function (data) {
alert(data);
});

Categories