How do I reload the page after all ajax calls complete? - javascript

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

Related

JS / JSON: Cannot redirect to next page after insert data (AJAX JSON)

Based on my question, I have successfully added input data to the database using ajax. However, it cannot redirect to the next page, "viewDetails.html" after inserting the data. Can anyone know how to fix it?
<script>
$('#userForm').submit(function(e){
$.ajax({
type: "GET",
url: "https://yes.hus.com/yesss/husss.asmx/TGA_AppAttendanceInsert?",
data:$('#userForm').serialize(),
beforeSend: function(){
console.log("Pending to send");
},
success: function(response){
console.log("Pending to send" + response);
window.location.href = "viewDetails.html";
return true;
},
});
});
</script>
Add e.preventDefault() after submit function line.
Like
<script>
$('#userForm').submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
url: "https://yes.hus.com/yesss/husss.asmx/TGA_AppAttendanceInsert?",
data:$('#userForm').serialize(),
beforeSend: function(){
console.log("Pending to send");
},
success: function(response){
console.log("Pending to send" + response);
window.location.href = "viewDetails.html";
return true;
},
});
});
</script>
When you use element.submit function, javascript will automatically send request to server side. So usually you don't need an ajax function inside it. Except you need to do something after request.
With e.preventDefault(), submit default function will stop and go to your ajax function.
Also you don't need a question marks on url. Ajax will generate it automatically.

Call python function with ajax and flask continously

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

Calling ajax request continually until a certain search request is found

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"

Ajax jquery making web api call

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.

Retrieve comments on runtime?

I want to call Ajax which fetches all the comments from database.
Now how to put a check on that Ajax Script to Run, when only someone comments.
Same as the stackoverflow notifications. When we comment on question, The Notification appears without reloading page (i.e On Runtime ).
Right now I am Running the same Ajax Script after each 10 seconds again and again, when I think is a bad way .So Here is my working Ajax Code:
$(document).ready(function(){
setInterval(function(){
$.ajax({
type: "GET",
url: "ajax_files/reload_notifications.php"
}).done(function(result) {
var $notifications = $('#notification_area');
if ($notifications.length > 0) {
$notifications.html(result);
}
});
}, 10000);
});
When a comment is entered, do a similar AJAX request that will save the comment and on it's success callback, call another function which will also hit another AJAX request which fetches the comments. For e.g.
function insertComment() {
$.ajax({
type: "GET",
url: "ajax_files/insert_comment.php"
}).done(function(result) {
fetchComments();
}
});
}
function fetchComments() {
$.ajax({
type: "GET",
url: "ajax_files/reload_notifications.php"
}).done(function(result) {
var $notifications = $('#notification_area');
if ($notifications.length > 0) {
$notifications.html(result);
}
});
}
Hope this helps!

Categories

Resources