AJAX uses old data in request - javascript

I'm using jQuery.ajax and ajaxQueue. I've two events causing AJAX requests, problem is:
both are using the same data and manipulates them,
sometimes they can be both launch by one action (on change for input and click for button).
When they are launched together, first should change value of input, and second should use new value in request. Unfortunatelly, in second request I'm getting old data.
Simply code showing this situation (without events, but main problem is the same):
<input id="in" value="x"><br>
click
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="jquery.ajaxQueue.min.js"></script>
<script>
jQuery.ajaxQueue({
url: 'ajax.php',
method: 'POST',
beforeSend: function() {
console.log('long ajax start');
}
}).then(function() {
$('#in').val('y');
console.log('long ajax stop');
console.log('current input value: ' + $('#in').val());
});
jQuery.ajaxQueue({
url: 'ajax2.php',
method: 'POST',
data: $('#in').val(),
beforeSend: function(xhr, settings) {
console.log('short ajax start');
console.log('data in short ajax: ' + settings.data);
}
}).then(function() {
console.log('short ajax stop');
});
</script>
In console I get:
long ajax start
long ajax stop
current input value: y
short ajax start
data in short ajax: x
short ajax stop
Of course should be data in short ajax: y. What can I change to get correct value?

Try adding cache: false for both requests, like this:
jQuery.ajaxQueue({
url: 'ajax2.php',
cache: false,
...
http://api.jquery.com/jQuery.ajax/

Related

Get request data in jQuery's AJAX response

Let's say I make a Dictionary app, where I check if some word exists or not. I have a text input and a button:
<input type="text" id="word">
<input type="button" id="button">
I'd like the server to respond with either 1 (valid word) or 0 (invalid word).
In my jQuery script, I send an AJAX request:
$("#button").click(function () {
$.ajax({
url: "check.php?word=" + $("#word").val(),
method: 'GET',
success: function (isValid, textStatus, xhr) {
// Can I read the URL from the xhr to know which word was the request for?
}
});
});
The problem is, when the response comes back, I no longer know which word is it for. I know I could attach the word to the server's response, but I'm very curious if it can be done other way.
I'm pretty sure I can just attach this piece of information to the raw XHR and then read it in success callback, but my question is: does XHR in success callback contain infromation about request's URL and data?
You can modify the jQuery xhr object in beforeSend with anything you want then access it in success or then() or done() callbacks
$.ajax({
url: 'http://httpbin.org/get',
data:{foo:'bar'},
beforeSend:function(jQxhr){
jQxhr.something='another thing';
},
success:function(res,statusText,jQxhr){
console.log('"Something" in success() ', jQxhr.something)
}
}).then(function(res,statusText,jQxhr){
console.log('"Something" in then() ', jQxhr.something)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is what I would do:
$("#button").click(function () {
var word = $("#word").val();
$.ajax({
url: "check.php?word=" + word,
method: 'GET',
success: function (data) {
alert(word);
}
});
});
EDIT: Removed from Robo Robok comment, in which he is correct.

How to show live script output during AJAX form submit request?

How to show "Live Feedback" on a script using jQuery?
I have a button that I use to submit a form for processing. Processing takes a long time. I want to have a <div id="progress"></div> where I show live progress report of what order processing script is doing. If all goes well I want to redirect to the View Order script, and if not, just show the progress report (not redirect to view order)
How? Currently I have this:
$("#placeorderbutton").click(function(e) {
e.preventDefault();
this.innerHTML = 'Placing Order...';
this.disabled = true;
$.ajax({
type: 'post',
url: 'process_order.php',
data: $('form#order').serialize(),
success: function(data) {
$("#main").load('view_order.php');
}
});
});
and even though I have print statements in my process_order file, they are not being displayed anywhere on the screen. Well, of course not ... I don't know how to build my jQuery/AJAX to make them show.
I am not sure how to proceed.
You would need to start the long process and then start a timer to poll the status. Keep in mind it doesn't take much for this to become more expensive than it's worth.
$("#placeorderbutton").click(function(e) {
e.preventDefault();
this.innerHTML = 'Placing Order...';
this.disabled = true;
$.ajax({
type: 'post',
url: 'process_order.php',
data: $('form#order').serialize(),
success: function(data) {
$("#main").load('view_order.php');
}
});
setTimer($.ajax({
type: 'post',
url: 'view_order.php',
data: $('form#order').serialize(),
success: function(data) {
$("#main").append(data);
}
}), 30000); //check every 30 Seconds
});

Form submit Ajax using jQuery sometimes does not works

I am doing form data submit using Ajax with jQuery.
When I submit form on popup window, I refresh the parent page.
My code:
$(document).ready(function() {
$("#frm_addSpeedData").submit(function(event) {
//event.preventDefault();
$.ajax({
type: "POST",
url: "/webapp/addSpeedDataAction.do",
data: $(this).serialize(),
success: function(data) {
//console.log("Data: " + data);
window.opener.location.reload();
}
});
});
});
However page gets refreshed on success of callback but i can not see update on my parent page. Sometimes I can see updates and sometimes not. What is the issue? I also need to know how I can write it in native javascript and submit form using ajax javascript.
Maybe your getting this error due the fact that javascript is async and your code will proceed even when you have yet no response from the request.
Try this:
$(document).ready(function() {
$("#frm_addSpeedData").submit(function(event) {
//event.preventDefault();
$.ajax({
type: "POST",
url: "/webfdms/addSpeedDataAction.do",
data: $(this).serialize(),
async: false, // This will only proceed after getting the response from the ajax request.
success: function(data) {
//console.log("Data: " + data);
window.opener.location.reload();
}
});
});
});

How to bring ajax search onkeyup with jquery

My Script to call ajax
<script language="javascript">
function search_func(value)
{
$.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg){
//Receiving the result of search here
}
});
}
</script>
HTML
<input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">
Question: while onkeyup I am using ajax to fetch the result. Once ajax result delay increases problem occurs for me.
For Example
While typing t keyword I receive ajax result and while typing te I receive ajax result
when ajax time delay between two keyup sometime makes a serious issue.
When I type te fastly. ajax search for t keyword come late, when compare to te. I don't know how to handle this type of cases.
Result
While typing te keyword fastly due to ajax delays. result for t keyword comes.
I believe I had explained up to reader knowledge.
You should check if the value has changed over time:
var searchRequest = null;
$(function () {
var minlength = 3;
$("#sample_search").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
if (searchRequest != null)
searchRequest.abort();
searchRequest = $.ajax({
type: "GET",
url: "sample.php",
data: {
'search_keyword' : value
},
dataType: "text",
success: function(msg){
//we need to check if the value is the same
if (value==$(that).val()) {
//Receiving the result of search here
}
}
});
}
});
});
EDIT:
The searchRequest variable was added to prevent multiple unnecessary requests to the server.
Keep hold of the XMLHttpRequest object that $.ajax() returns and then on the next keyup, call .abort(). That should kill the previous ajax request and let you do the new one.
var req = null;
function search_func(value)
{
if (req != null) req.abort();
req = $.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg){
//Receiving the result of search here
}
});
}
Try using the jQuery UI autocomplete. Saves you from many low-level coding.
First i will suggest that making a ajax call on every keyup is not good (and this why u run in this problem) .
Second if you want to use keyup then show a loading image after input box to show user its still loading (use loading image like you get on adding comment)
Couple of pointers. Firstly, language is a deprecated attribute of javascript. In HTML(5) you can leave the attribute off, or use type="text/javascript". Secondly, you are using jQuery so why do you have an inline function call when you can do that with jQuery too?
$(function(){
// Document is ready
$("#sample_search").keyup(function()
{
$.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg)
{
//Receiving the result of search here
}
});
});
});
I would suggest leaving a little delay between the keyup event and calling an ajax function. What you could do is use setTimeout to check that the user has finished typing before then calling your ajax function.

Why can't I use jQuery to fire an AJAX request from an unload event handler?

I have the following code, intended to log the event when a user closes a chat window:
$(window).unload( function() {
test();
});
function test()
{
alert("Hi");
$.ajax({
type: "POST",
url: baseUrl + 'Index/test',
data: "user_id=" + "Nisanth" + "& chat_id=" + 2,
success: function(msg){
alert(msg);
}
});
alert('Success');
}
Both the "Hi" and "Success" messages alert fine but the alert in the AJAX callback doesn't... The operation I intend to trigger via the AJAX request is also not happening (I'm developing a chat application, and intend to log an entry in the database when the user closes the window).
Because the ajax is asynchronous, the page is unloading before the response is properly sent, effectively terminating the connection. Try setting async:false;, although this will delay unloading the page until after the response is received, which isn't great for user experience if your server is running slow.
$(window).unload( function () {
test();
});
function test()
{
alert("Hi");
$.ajax({
async: false,
type: "POST",
url: baseUrl + 'Index/test',
data: "user_id=" + "Nisanth" + "& chat_id=" + 2,
success: function(msg){
alert(msg);
}
});
alert('Success');
}
the problem is the format of your data. It is converted to a query string, it must be Key/Value pairs something like:
"user_id:value"

Categories