Problem of using ajax call at the same time - javascript

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();">

Related

Javascript callback function does't fire up

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);});

Refresh page after function has been called

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

Web Workers and JSON

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);

ajax - javascript function to refresh a div

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);

Call HttpHandler from javascript

I have a simple page with button which calls HttpHandler via JavaScript.
HttpHandler gets lots of files and adds them to a zip file, after finishing work zip file will be added to Response.
This operation can take several minutes. I would like to execute some JavaScript function after finishing work of HttpHandler.
How can I do it?
My code:
<asp:Button ID="btnDownload" runat=server Text="Download" OnClientClick="Download()" />
<script type="text/javascript">
function Download()
{
var url = 'FileStorage.ashx';
window.open(url);
}
</script>
UPD 1:
I have found other solution. Using XMLHttpRequest.
Code:
<script type="text/javascript">
var xmlHttpReq = createXMLHttpRequest();
function Download() {
var url = 'FileStorage.ashx';
xmlHttpReq.open("GET", url, false);
xmlHttpReq.onreadystatechange = onResponse;
xmlHttpReq.send(null);
}
function onResponse() {
if (xmlHttpReq.readyState != 4)
{ return; }
var serverResponse = xmlHttpReq.responseText;
alert(serverResponse);
}
function createXMLHttpRequest() {
try { return new XMLHttpRequest(); } catch (e) { }
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { }
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { }
alert("XMLHttpRequest not supported");
return null;
}
</script>
In onResponse() I can see my zip file in responseText (binary). But I don't have any idea how I can say to browser to download result of working httphandler such as file.
Any ideas?
I would use JQuery AJAX and then on success, write a function that will do whatever work you need it to. Plus with AJAX you can show the user an icon that says loading so they know something is actually processing, instead of the page just hanging and nothing appearing to happen.
$.ajax({
url: "FileStorage.ashx",
context: document.body,
success: function(){
// Whatever you want to do here in javascript.
}
});

Categories

Resources