Is there a way that I can run a function then call window.location.reload() to refresh the page? Currently when I do this the page is refreshing but the function isn't running.
function postComment() {
var name;
if (document.getElementById("yourName").value == "") {
name = "(Anonymous)";
} else {
name = document.getElementById("yourName").value;
}
var uri = "http://tgg.tcs.com/AP/Open/Service.svc/comment?name=" + name;
var xhr = new XMLHttpRequest();
xhr.open("POST", uri, true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8")
xhr.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(JSON.stringify(document.getElementById("comment").value));
}
You need to use a callback
function yourFunction(arg, callback) {
doSomeStuff(arg);
callback();
}
yourFunction('argument', window.location.reload);
If doSomeStuff function is async, you have to do
function yourFunction(arg, callback) {
doSomeStuff(arg, callback);
}
yourFunction('argument', window.location.reload);
also, if you refresh the page, you will refresh the scripts as well, so it depends on what does your function do, you may need a cookie if the data the function generates has to be persistant
Related
var emps;
function GetEmps(){
const Http = new XMLHttpRequest();
const url='http://127.0.0.1:3001/GetEmployeeList';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
e.preventDefault();
if(Http.responseText.length>0)
{
emps=JSON.parse(Http.responseText);
for(let i=0;i<emps.length;i++)
{
CreateElementsInPage(i);
}
}
}
}
function CreateElementsInPage(id) {
console.log(id);
var btn = document.createElement("BUTTON");
btn.innerHTML = emps[id].name;
document.body.appendChild(btn);
var newLine=document.createElement("br");
document.body.appendChild(newLine);
}
GetEmps();
i am trying to create buttons dynamically. for every item in emps array, I want a button to appear in the DOM, but the "CreateElementsInPage" functions get called 4 times instead of 2 (suppose I have 2 items in emps) and I get 4 buttons
You should check request state inside your callback:
Http.onreadystatechange = (e) => {
if(Http.readyState === XMLHttpRequest.DONE ) {
// Request is complete, do your logic
}
}
onreadystatechange event function is triggered/called whenever the state of the connection is changed (readyState).
So you need to make sure that you create your button only when the connection is successful (done).
function GetEmps(){
const Http = new XMLHttpRequest();
const url='http://127.0.0.1:3001/GetEmployeeList';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
// Make sure that the request is done before calling your button creation method
if (Http.readyState === XMLHttpRequest.DONE) {
if(Http.responseText.length>0)
{
emps=JSON.parse(Http.responseText);
for(let i=0;i<emps.length;i++)
{
CreateElementsInPage(i);
}
}
}
}
}
for some reason callback doesn't fire up.
I cut all the extra code out, this is the structure. Perhaps i can't see something wrong here?
(function() {
registerSecendStep = new Page('registerSecendStep', function(name) { //CLIKED THE BUTTON
$('.register-second-step-button').click(function() {
function doAjax(testReferral) {
alert(testReferral); //THIS NEVER GETS PRINTED
}
showHint(function() { doAjax(testReferral); }); //START THE CALL
});
});
function showHint(callback) { //CALLBACK
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert('called'); //THIS GETS ALERTED
callback(true);
}
}
xmlhttp.open("GET", helper.app.HomeSite + "/ajaxresponder?w=" + str, true);
xmlhttp.send();
}
})();
Any help appreciated
testReferral is never defined in the callback. Try:
showHint(function(testReferral) {doAjax(testReferral);});
I am sure there is something that I am missing from this code, I just can not figure out what it is.
Here is the main page:
<script>
function wwCallback(e) {
document.write(e.data);
}
function wwError(e) {
alert(e.data)
}
$(document).ready(function () {
var worker = new Worker("sync.js");
worker.onmessage = wwCallback;
worker.onerror = wwError;
worker.postMessage({
'cmd': 'downloadUser',
'url': 'server.php'
});
console.log("WW Started");
});
</script>
Server.php simply echoes a JSON string and I have verified that it is both valid and working using normal ajax requests.
Here is my web workers code:
function getData(url) {
var req = new XMLHttpRequest();
//expect json
req.open('GET', url);
req.send(null);
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
self.postMessage(req.responseText);
}
}
}
}
self.addEventListener('message', function (e) {
var data = e.data;
switch (data.cmd) {
case 'downloadUser':
getData(data.url);
}
self.close();
}, false);
Could anyone point me in the right direction?
Your problem is in your WebWorker XHR call. You've opened the request, then immediately sent it before you've set up the event handler to handle the response. You just need to move the req.send(null); call below the code that sets up the event handler.
Try this:
function getData(url) {
var req = new XMLHttpRequest();
//expect json
req.open('GET', url);
// req.send(null); // remove this line from here.
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
self.postMessage(req.responseText);
}
}
}
req.send(null); // make the request after your readystatechange
// handler is set up.
}
self.addEventListener('message', function (e) {
var data = e.data;
switch (data.cmd) {
case 'downloadUser':
getData(data.url);
}
self.close();
}, false);
I'm trying to have a div refresh after a callback using ajax functions. Basically, I want /includes/view_game/achievements.inc.php to be reloaded in the div #achievements_tab. The callback (I didn't include it in codes below) works well and triggers the AchievementRefresh function found below (the opacity of the div changes to 0.5, but it remains like this and the refresh is not made).
Those two functions are used for another similar ajax refresh on my site that works well. So I tried to modify the code, but since it's for a slightly different purpose, maybe I have the wrong approach.
function AjaxPost(url, success_function) {
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Your browser doesn't support AJAX. You should upgrade it!")
return
}
xmlHttp.onreadystatechange = success_function;
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
This AjaxPost function is used in the other function below:
function AchievementRefresh() {
div('achievements_tab').style.opacity = 0.5;
div('highscore_pages').innerHTML = '<img src="'+site_url+'/images/loader.gif" />';
AjaxPost(site_url+"/includes/view_game/achievements.inc.php?", '',
function () {
div('achievements_tab').innerHTML = xmlHttp.responseText;
div('achievements_tab').style.opacity = 1;
}
)
}
Use load
$('#achievements_tab').load('/includes/view_game/achievements.inc.php');
See: http://api.jquery.com/load/
Edit
E.g.
function AchievementRefresh() {
$('#achievements_tab').css('opacity', 0.5);
$('#highscore_pages').html('<img src="'+site_url+'/images/loader.gif" />');
$('#achievements_tab').load('/includes/view_game/achievements.inc.php')
.success(function() {
$('#achievements_tab').css('opacity', 1);
});
}
Try this.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
div('achievements_tab').innerHTML = xmlHttp.responseText;
div('achievements_tab').style.opacity = 1;
}
}
};`
Name and id is example.
Also, some changes:
AjaxPost(site_url+"/includes/view_game/achievements.inc.php");
var params= 'name'+encodeURIComponent(name)+'&id='+encodeURIComponent(id)
Parameters shouldn't be in URL.
xmlhttp.send(params);
Now, I have a problem with the ajax call which is when the web page is loaded, in the onload event of body, I assign it to call the functions which are startCount() and updateTable() this two functions contain the code that use ajax call to get the data from DB on the server side. The problem is when the ajax return it will return only one call and another call does not response. Please help me what happen and how I can slove it.
This is the onload in the body
<body onLoad="setAjaxConnection();startCount();updateTable()">
I use the XMLHttpRequest with the normal javascript, I do not use jQuery....
Use javascript closures. This link may help
http://dev.fyicenter.com/Interview-Questions/AJAX/How_do_I_handle_concurrent_AJAX_requests_.html
function AJAXInteraction(url, callback) {
var req = init();
req.onreadystatechange = processRequest;
function init() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function processRequest () {
if (req.readyState == 4) {
if (req.status == 200) {
if (callback) callback(req.responseXML);
}
}
}
this.doGet = function() {
req.open("GET", url, true);
req.send(null);
}
this.doPost = function(body) {
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(body);
}
}
function startCount() {
var ai = new AJAXInteraction("/path/to/count.php", function(){alert("After startCount");});
ai.doGet();
}
function updateTable() {
var ai = new AJAXInteraction("/path/to/update.php", function(){alert("After updateTable");});
ai.doGet();
}
Have the 'onSuccess' of one call initiate the next ajax call. So you would call startCount() and when that returns you fire off updateTable().
function setAjaxConnection(){
//call Ajax here
setAjaxConnectionResponce;
}
function setAjaxConnectionResponce(){
//on readystate==4
startCount();
}
function startCount(){
// code for count
updateTable();
}
function updateTable(){
// code for update
}
<body onLoad="setAjaxConnection();">