How to send a variable from ajax success to a template? - javascript

Is it possible reload a page without refresh (silently) ?
Here is an example where page reload automatically. But you can easily see that the page is refreshing after certain time interval. I don't like this where end user is getting such experience. I want that the page reload but without refreshing. End user should not feel that page is refreshing. Is it possible using simple html? or jquery?
I don't want <META HTTP-EQUIV="refresh" CONTENT="5"> or setTimeout of jquery because it refreshes the page while reloading?

Don't reload the whole page. Just use ajax to reload the components that needs to be updated. jQuery is perfect for that.

Use a setInterval with an ajax request. I'll update in 1 min with the script.
var divid = 'yourDivsId'
function createRequestObject()
{
var obj;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
obj = new ActiveXObject("Microsoft.XMLHTTP");
}else{
obj = new XMLHttpRequest();
}
return obj;
}
function sendReq(req)
{
http.open('get', req);
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse()
{
if (http.readyState == 4)
{
var response = http.responseText;
document.getElementById(divid).innerHTML=response;
}
}
var http = createRequestObject();
setInterval('yourUrl', 30000); //or whatever time you want.
Should do the trick.

Related

Will an ajax call finish even after a page redirect?

I am trying to create a temporary image url for a local image and send it to Google to do a Search by Image. I don't want the image url to be permanent so I want to delete it right after I use it. I have the code below:
// Gets a URL that can be used to do a search by image through Google.
function getImageURL() {
var xml = new XMLHttpRequest();
xml.onreadystatechange = function () {
if (xml.readyState == 4 && xml.status == 200) {
deleteImageURL(); // asynchronous call to server to delete the URL
window.location.href =
"https://www.google.com/searchbyimage?site=search&sa=X&image_url="
+ xml.responseText; // the image url
}
}
xml.open("GET", "REST_ENDPOINT", true);
xml.send();
}
The function above calls the server, and when it finishes, will delete the url and redirect the page. The function "deleteImageURL()" is another ajax call done asynchronously. Currently, this loads the google page fine as the image URL is not done deleting the url by the time that the redirect happens.
My question is this: Will deleteImageURL() finish deleting the image URL even after the page redirects or will it stop (and thus, never delete the URL)?
EDIT: So I was thinking about what you guys were saying about race conditions and tried the following code instead:
// Gets a URL that can be used to do a search by image through Google.
function getImageURL() {
var xml = new XMLHttpRequest();
xml.onreadystatechange = function () {
if (xml.readyState == 4 && xml.status == 200) {
deleteImageURL(xml.responseText);
}
}
xml.open("GET", "REST_ENDPOINT"
+ id + "/public_url", true);
xml.send();
}
// Deletes the url for the image.
function deleteImageURL(imageURL) {
var xml = new XMLHttpRequest();
xml.open("GET", "REST_ENDPOINT_FOR_DELETE", true);
xml.send();
window.location.href =
"https://www.google.com/searchbyimage?site=search&sa=X&image_url="
+ imageURL;
}
This code works every time that I run it. I think that there still may be a race condition, but it seems to be working fine so far.
Thanks again.
The "deleteImageURL()" will finish deleting the image URL even after the page redirects..
Refer : Should I wait for ajax to complete to redirect a page?
The server won't stop processing the request (initiated by deleteImageUrl), but you will not be able to handle a callback if the current page unloads in the browser before the operation is completed.
If deleteImageURL(); contains an async call you should do the redirect when the call is completed. Your code will work when the call is synchronious. We don't see the source of deleteImageURL(); and can be more concrete, but you should do the same thing as you've done for getImageURL().

Phonegap synchronous ajax call

I've been working with phonegap to build an app and have been using ajax to communicate with the server to get all the necessary data. Some of the pages take a few seconds to load (and I dont display the page until everything is loaded) and I would like a loading screen to appear while the client is communicating with the server and processing all the data.
I had everything working great until I decided to throw the the ajax calls into functions (I'm working with a few team members, so I thought it would be easier for them to use these ajax calls if they were in some nice functions). Now because of the ajax function is asynchronous, the loading screen turns on and off before the requests are finished processing. I would like my function to stop the execution of code (similar to an alert) so that the loading screen will turn off AFTER all the ajax calls are made.
Essentially I want my javascript code to look like this:
loading();
sendRequests();
notLoading();
where loading() displays the loading screen, and notLoading() turns the loading screen off. My sendRequests() function is specific to each page (each page has to send different requests depending on the functionality of the page)
if you guys are wondering what the loading() and notLoading() functions looks like, here you go
// functions to make loading screen appear and disappear
function loading() {
document.getElementById("blackout").style.display = 'block';
}
function notLoading() {
document.getElementById("blackout").style.display = 'none';
}
I looked into a few other posts about it
How to wait for ajax request to complete in javascript when synchronous option is not available?
http://www.hunlock.com/blogs/Snippets:_Synchronous_AJAX
Which those two links essentially tell you the same information, that the third parameter in request.open() needs to be set to false... well, I've tried that and it didn't work =/
here is an example of my getRequest() function so everyone can see what I'm trying to do:
// will send a GET request to the parameter url
function getRequest(url) {
var req = new XMLHttpRequest();
req.open('GET', url, false);
setHeaders(req);
req.onreadystatechange = function() {
if (req.readyState == 4) {
if( (req.status == 200) || (req.status == 0) ) {
if( (typeof req.responseText != "undefined") && (req.responseText != "") ) {
localStorage["request"] = req.responseText;
}
else {
alert("GR: Error talking to the server");
}
}
else {
alert("GR: Error talking to server");
}
}
}
req.send(null);
return parseJSON();
}
If anyone knows how I can fix this, I would be very appreciative!
I ended up just throwing the notLoading() function at all the exit statuses in the sendRequests() function. Kind of a pain, but seems to work now.

Ajax refresh does not refresh the Java script

I have a JSP page that refreshes every 5 seconds Using ajax.
The page i am calling having javascript that is not getting refreshed .
Please tell me how to achieve that.
Below is the code i am using to refresh that page .
refresh is the name of the div where i am displaying the data.
<script type="text/javascript">
function AutoRefresh() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("No AJAX");
return false;
}
}
}
xmlHttp.onreadystatechange = function () {
//alert("hi");
if (xmlHttp.readyState == 4) {
document.getElementById('TotalRoutes').innerHTML = xmlHttp.responseText;
setTimeout('AutoRefresh()', 10 * 1000); // JavaScript function calls AutoRefresh() every 3 seconds
}
}
xmlHttp.open("GET", "QAGENIE.jsp", true);
xmlHttp.send(null);
}
</script>
Here js files in the QAGENIE.jsp page is not getting refreshed on the ajax call
I think you are not calling AutoRefresh function first time. so nothing will be execute. and if you are calling from outside of your code which you gave here, then please post whole web page code in question.
setTimeout(AutoRefresh,5000); for every 5 seconds
if (xmlhttp.readyState==4 && xmlhttp.status==200)
window.onload = AutoRefresh();
When you call document.getElementById('TotalRoutes').innerHTML=xmlHttp.responseText;, script tags inside the "QAGENIE.jsp" are not executed, that's why:
js files in the QAGENIE.jsp page is not getting refreshed.
Since the question is tagged with jQuery, you could try $.ajax and $.html. Like this:
function AutoRefresh(){
$.ajax({
url:"QAGENIE.jsp"
})
.done(function(response){
$("#TotalRoutes").html(response);
setTimeout(AutoRefresh,10*1000);
});
}
AutoRefresh(); //call this to trigger the first call
$.html automatically parses and executes script tags in the response HTML.
There is 1 more thing to notice is browser cache, if your js files are cacheable (as it usually does by the cache response header from server), the js files may be served from the cached. If you need to always refresh with new js files, ensure your js files are not returned with a cache header, or try to append a random string at the end of the script tags. Like this:
<script src="yourFile.js?[randomstring]"></script>

Javascript: Find browser windows open with the same domain

Is there a way to get a list of all the open browser windows if they are from the same domain as the window that is trying to get the list?
In general, no.
Unless there is a "connection" between the windows (e.g., one window opened all the other using window.open), browser windows can't interact because of security reasons.
Edit:
If you assign a name to your window, you can regain control over it after refreshing the parent page.
windowVar = window.open('somePage.html', 'windowName'); opens a child window with name windowName.
After refreshing the parent page, windowVar = window.open('', 'windowName'); re-associates the variable windowVar with the window of name windowName.
Now, windowVar.location.href= 'logout.html'; lets you log out your user.
Edit:
Assuming you use PHP, you could do something like this:
Create logged.php with a function logged_in that verifies if the session ID is still valid.
<?php
if (isset($_GET['sid']))
if (logged_in($_GET['sid']))
echo "in";
else
echo "out";
?>
Include check() function in your pages.
function check()
{
var url = "http://redtwitz.com/test/logged.php?sid=" + sessionId;
var request;
try
{
request = new XMLHttpRequest();
}
catch(error1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(error2)
{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
}
request.open("GET", url, false);
request.setRequestHeader("User-Agent",navigator.userAgent);
request.send(null);
if(request.status==200)
if(request.responseText == "out")
window.location.href = "logout.html";
}
Call check function every 5 seconds.
<body onload="setInterval(check, 5000);">
Alternatively, you can implement Chrome extension and do your task by using extension api: http://code.google.com/chrome/extensions/tabs.html
But it will work in Chrome browser only.

problem in refreshing the page after making two ajax calls

Problem I am making ajax call to server1 i.e. csce and once I got the response I am sending the response as contents to server2 i.e.yahoo server after getting response from there I want to refresh the page or atleast redirect it to the same page. Both ajax calls are working fine. The contents I am sending are also saved the only problem is that I have to manually refresh the page to see the changes. I want to refresh the page once the contents are saved on yahoo. I tried reload and redirect commands in success function of yahoo. But nothing works. I can see the both ajax calls in the HTTPfox but not the redirect.
The url from which i am making calls is different from the url where contents are saved thats why I need to refresh the page to see the changes. i.e. I am saving in yahoo/save while sending contents and seeing changes at yahoo/edit.
I am not sure where I am going wrong. Here is my code I am using. Can anyone suggest where I am going wrong. If my problem is not clear kindly do ask me to clarify more. Thanks.
This code is the code:
function handleButtonClick()
{
// Declare the variables we'll be using
var xmlHttp, handleRequestStateChange;
// Define the function to be called when our AJAX request's state changes:
handleRequestStateChange = function()
{
// Check to see if this state change was "request complete", and
// there was no server error (404 Not Found, 500 Server Error, etc)
if (xmlHttp.readyState==4 && xmlHttp.status==200)
{
var substring=xmlHttp.responseText;
alert(substring);// I am able to see the text which is returned by the server1 i.e csce
var handleSuccess = function(o)
{
if(o.responseText !== undefined)
{
console.log(o.responseText);
**window.location.reload()** // also I tried to redirect it to the same site but that also not works
}
};
var callback ={ success:handleSuccess, failure: function(x) {
console.error(x) }, argument: ['foo','bar']};
var request = YAHOO.util.Connect.asyncRequest('POST','http://yahoo.com******', callback, substring);
}
}
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://cse*****id=c6c684d9cc99476a7e7e853d77540ceb", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
Do you just want to display the content in your page? Why don't you try something along the lines of document.getElementById('divID').innerHTML = xmlHttp.responseText;?
With divID being the id of a div that you want to fill the content with.
try following in the handleRequestStateChange function
window.location.href = window.location.href;

Categories