I am building a game. When a piece is moved ('.draggable'), I need make the first ajax call (to move_script.php) which will validate the move and then save it in a database. After that is done, I want to run the second ajax call (to past_moves.php) and query the database and write out the new move.
My problem, is that sometimes the second ajax calls pulls out the results BEFORE the current move is there. I've used microtime(); in the php code to see what is happening, and every time that the most recent result isn't pulled, the second ajax script is completing first. (Most of the time the most recent result comes out, but every so often it won't, it seems to be randomly, every 5 - 15 times or so).
How can I ensure that the second ajax call won't run until the first one is done?
Thank you
code:
<script>
$(function() {
$( ".draggable" ).draggable({
stop: function(event, ui) {
var start = $(this).attr('id')
//ajax call number 1
$.ajax({
type: "POST",
url: "../move_script.php",
data: { start: start }
}).done(function( msg ) {
//alert( "Data Saved: " + msg );
$("#chessboard").html(msg);
});
//ajax call number 2
$.ajax({
type: "POST",
url: "../past_moves.php",
data: {}
}).done(function( moves ) {
$("#past_moves").html( moves );
});
}
});
});
</script>
Nest the ajax calls
//ajax call number 1
$.ajax({
type: "POST",
url: "../move_script.php",
data: { start: start }
}).done(function( msg ) {
//alert( "Data Saved: " + msg );
$("#chessboard").html(msg);
//ajax call number 2
$.ajax({
type: "POST",
url: "../past_moves.php",
data: {}
}).done(function( moves ) {
$("#past_moves").html( moves );
});
});
});
This nesting will force the second call to wait until the first has completed.
Put the second ajax call in the callback of the first ajax call to make sure it only executes after it is complete. Otherwise, since ajax is asynchronous, it starts the request and then keeps going (in this case, starting the second ajax). I'm not familiar with the "done" method - maybe you can put it in that function that you already have. Otherwise, this is the syntax I'm familiar with:
$.ajax({
type: "POST",
url: "../move_script.php",
data: { start: start },
success: function(data){
//data is whatever the ajax returns. is it msg in this case?
//put second ajax call here
},
error: function(jqXHR, textStatus, errorThrown){
//might not need here, but this is example of callback which will be executed instead of success if server returns an error
},
complete: function(jqXHR, textStatus){
//another useful callback to know about - will execute after success or error
}
})
https://api.jquery.com/jQuery.ajax/
Related
I need to call flask function in python with ajax continously. To that I have following script in html file.
<script >
var ajaxFUN = function () {
$.ajax({
url: '/toAjax',
dataType: 'json',
success: function (data) {
console.log('get info');
$('#data').html(data['data']);
}
});
}
setTimeout(ajaxFUN, 1);
</script>
And here is the python code
#app.route('/toAjax')
def ajaxTo():
print("AJAX WAS HERE")
data= reader.getToAjax()
info = {
"data": data
}
return jsonify(info)
I need to call /toAjax header route in the python continously without hitting any button or any kind of method.
But that implementation prints only once AJAX WAS HERE. Where is the missing part ? How can I fix it ?
Here is the similiar questions which I have looked:
setTimeout() and setting parameters
how to make ajax calls continuously for 5 seconds once
setTimeout triggers exactly once (unless cancelled)
you could use setInterval, but that's likely to flood your server at the rate you've used for setTimeout
I would recommend the following
var ajaxFUN = function () {
$.ajax({
url: '/toAjax',
dataType: 'json',
success: function (data) {
console.log('get info');
$('#data').html(data['data']);
ajaxFUN(); // this calls the function again
}
});
}
ajaxFUN();
In case you're worried, there's no "recursion", since ajaxFUN() is being called in an asynchronous callback
I am trying to keep sending AJAX GET requests to a certain page that inputs from a cgi script until a specific set of keystrokes shows up.
However, my requests aren't coming up continuously, in fact they aren't even taking place when I am using a function and trying to call the function. I had to use the complete with the success, because for whatever reason, with the success I could not properly store the value retrieved.
Here is what I have:
function posts() {
$.ajax({
type: "GET",
url: 'http://checkvaluestatus.sh',
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
if (version != null) {
console.log(version);
} else {
posts();
}
},
error: function() {
console.log('failed');
posts(); //calling the ajax again.
}
});
Is there not a way to keep sending requests based on a condition being met and having the value still stored?
This is my AJAX call that worked to print the value:
$.ajax({
url: 'http://checkvaluestatus.sh',
type: "GET",
dataType: "json",
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
document.write(version);
},
});
salam,
the value you are looking for in success function is the 'data' ,not "data_response.responseText" because in "success" function data is your response text ,but in the "complete" function "data_response" is a jqXHR object contain more information.
to print your text in success function replace
alert(data_response.responseText);
by
alert(data);
for more details "jquery.ajax"
I made an api in java , which allows the user to get data.
there is an call : ..../api/users where i give a list back of all users avalible.
Now i got a site with a search user button, wen you press that button i want to make a call to /api/users with the help of Ajax.
i got the part that you can click on the search button, but i don't understand how to make that call with ajax
This is my code:
$.ajax({
url: ”api / resource / users ",
dataType: "json”,
}
).fail(
funcNon(jqXHR, textStatus) {
alert("APIRequestfailed: " + textStatus);
}
).done(
funcNon(data) {
alert("succes!")
}
);
Is this the way of making a good call with ajax ?
or do i have to use :
http://localhost/projectUser/api/resource/users ?
Assuming you are using JQuery to make the Ajax call then this sample code should be helpful to you. What it does is;
On search button was clicked
Do AJAX call to fetch stuff from your Java REST API
When the expected JSON object was returned, parse it and do something
O
$(document).ready(function() {
$('#demoSearchBtn').click(function () {
// Search button was clicked!
$.ajax({
type: "GET",
url: "http://localhost/projectUser/api/resource/users", // edit this URL to point into the URL of your API
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
var jsonObj = $.parseJSON(data);
// Do something with your JSON return object
},
error: function (xhr) {
alert('oops something went wrong! Error:' + JSON.stringify(xhr));
}
});
});
}
if this http://localhost/projectUser/api/resource/users is the url, it's either
$.ajax({
url: ”api/resource/users", ...
or
$.ajax({
url: ”http://localhost/projectUser/api/resource/users", ...
depending on what the browsers current URL is (relative or absoute depends on context of the browser).
but it is never ever ”api / resource / users " with spaces between words and slashes.
This seems a bit strange and i cant get a hold of the situation, apparently i used jquery's .ajax() function to process some script to get some data from the database. The script works fine and data gets returned as accordingly:
$.ajax({
type: "POST",
url: "getevaluationdata.php",
data: { evaluation_ID: value }
})
.done(function( msg ) {
$("#error2").html(msg);
});
After the scripts process, it is suppose to populate the data echoed in the script to the div i mentioned, but this does not happen. However, if i write an alert statement before the div population, the div gets populated. meaning:
$.ajax({
type: "POST",
url: "getevaluationdata.php",
data: { evaluation_ID: value }
})
.done(function( msg ) {
alert(msg);
$("#error2").html(msg);
});
I dont seem to get why this is happening and what I can do to resolve this.
P.S. I have done this before, and this was working correctly before
Is it possible #error2 is not on the page yet?, so the alert gives it time? try putting the ajax call in
$(function(){
$.ajax({
type: "POST",
url: "getevaluationdata.php",
data: { evaluation_ID: value }
}).done(function( msg ){
$("#error2").html(msg);
});
});
Another thing you can try for reference is using the success callback
$.post("getevaluationdata.php",{evaluation_ID:value},function(msg){
$("#error2").html(msg);
});
The first time a user is visiting my website, I am pulling a lot of information from various sources using a couple of ajax calls. How do I reload the page once the ajax calls are done?
if(userVisit != 1) {
// First time visitor
populateData();
}
function populateData() {
$.ajax({
url: "server.php",
data: "action=prepare&myid=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
_id = response[json].id;
getInformation(_id);
}
});
}
function getInformation(id) {
$.ajax({
url: "REMOTESERVICE",
data: "action=get&id=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
$.ajax({
url: "server.php",
data: "action=update&myid=" + id + '&data=' + json.data.toString(),
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
}
});
}
});
}
So what the code does is, it gets a list of predefined identifiers for a new user (populateData function) and uses them to get more information from a thirdparty service (getInformation function). This getInformation function queries a third party server and once the server returns some data, it sends that data to my server through another ajax call. Now what I need is a way to figure out when all the ajax calls have been completed so that I can reload the page. Any suggestions?
In your getInformation() call you can call location.reload() in your success callback, like this:
success: function(json) {
if(!json.error) location.reload(true);
}
To wait until any further ajax calls complete, you can use the ajaxStop event, like this:
success: function(json) {
if(json.error) return;
//fire off other ajax calls
$(document).ajaxStop(function() { location.reload(true); });
}
.ajaxStop() works fine to me, page is reloaded after all ajax calls.
You can use as the following example :
$( document ).ajaxStop(function() {
window.location = window.location;
});
How it's works?
A: Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event.
Hope help y'all, furthermore information, I'm sharing the link of the documentation following.
source: https://api.jquery.com/ajaxstop/
You could just redirect to the same page in the server.php file where the function is defined using a header('Location: html-page');
//document.location.reload(true);
window.location = window.location;
See more at: http://www.dotnetfunda.com/forums/show/17887/issue-in-ie-11-when-i-try-to-refresh-my-parent-page-from-the-popupwind#sthash.gZEB8QV0.dpuf