Ajax call does not refreshesh the calling page javascript - javascript

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

try to wrap that code inside $(document).ready();
like
$(document).ready(function(){
$.ajax({
url: 'http://localhost:8088/Login.do',
success: function(data) {
alert(data);
$("#refresh").html(data);
alert(data);
},
complete: function() {
alert("refresh");
setTimeout(function(){ worker(); },5000);
//$('#refresh').load("http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js");
}
});
});

you should import the jquery file first
like
<script src="<%=request.getContextPath()%>/view/js/jquery1.7.2.js"></script>
and debug is,if is nothing in you console,it will be success

Related

Use two GetXmlHttpObject results

I'm trying to add functionality to a small php/js I've built, but I can't make it work.
In general, i make two GETS of two different URL, and I need to use the reply of this URL in two different boxes.
I'v tried: seperate var port_name; and them just equals / to call $port_name or port_name.
Relevant part of code:
<script type="text/javascript">
function showPortName()
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var oob=document.getElementById("oob_name").value;
var port=document.getElementById("port").value;
var url="oob_get_port_name.php";
var url2="oob_get_location.php";
url=url+"?oob="+oob+"&port="+port;
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.send(null);
var port_name=xmlHttp.responseText.value;
url2=url2+"?oob="+oob+"&port="+port;
xmlHttp.open("GET",url2,true);
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("device_name").value=$port_name;
document.getElementById("device_location").value=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
</script>

AJAX to request another javascript or function from the server

As we know that AJAX is used to request a web-part in HTML format from the server. Is it possible to request a script containing functions using AJAX?
Here's an example how to use eval() to accomplish what you need:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
eval(xmlhttp.responseText);
// you can use whatever functionw as returned from the server from this line on :)
}
}
xmlhttp.open("GET","your-server-page-url",true);
xmlhttp.send();
Yes you can load a javascript via ajax
http://api.jquery.com/jQuery.getScript/
$.getScript("ajax/test.js")
.done(function(script, textStatus) {
console.log( textStatus );
})
.fail(function(jqxhr, settings, exception) {
$( "div.log" ).text( "Triggered ajaxError handler." );
});
Also you could try something like this as mentioned in(how to run javascript in html loaded via ajax):
require("extra.js", function () {
functionDefinedInExtraJS();
});
//Sample require function:
function require(file, callback) {
var script = document.getElementsByTagName('script')[0],
newjs = document.createElement('script');
// IE
newjs.onreadystatechange = function () {
if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {
callback();
}
};
// others
newjs.onload = function () {
callback();
};
newjs.src = file;
script.parentNode.insertBefore(newjs, script);
}
One other way would be to use eval() function and convert a string reply into working javascript code.
Is it possible to request a script containing functions using AJAX?
Yes, it is possible. And those functions could be executed on the client. For example with jQuery you even have a function that allows you to perform such request: $.getScript.

how can i do jquery's $.get in pure javascript? (without wanting to return anything)

I want the mobile version of my site to be as snappy as possible, however i still want some basic analytics.
I want to ping a php file (hit counter) after the mobile page has loaded to count the amount of hits from javascript enabled browsers.
Jquery's a bit overkill for 1 ajax function so i'm keen to learn how to do the following in pure javascript:
<script type="text/javascript">
Window.onload(function(){
$.get('mvc/assets/ajax/analytics/event_increment.php?id='+id');
})
</script>
Create a utility function that will return to you a browser-specific Ajax object:
function ajax(url, method, callback, params = null) {
var obj;
try {
obj = new XMLHttpRequest();
} catch(e){
try {
obj = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
obj = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Your browser does not support Ajax.");
return false;
}
}
}
obj.onreadystatechange = function() {
if(obj.readyState == 4) {
callback(obj);
}
}
obj.open(method, url, true);
obj.send(params);
return obj;
}
You could then call that function like this:
var ajax = ajax('someurl', 'get', function(obj) { alert(obj.responseText); })
Just specify your file as the src attribute for the script tag.
Something simplistic:
<div id="hidden"></div>
<script type="text/javascript">
window.onload = function(){
var div = document.getElementById("hidden");
div.innerHTML = "<img src='tracking.php' />";
};
</script>
#Mike is suggesting a great method. If you would like to get into AJAX, though, it's not that difficult.
Code c/o bobince
var xhr= new XMLHttpRequest();
xhr.open('GET', 'x.html', true);
xhr.onreadystatechange= function() {
if (this.readyState!==4) return;
if (this.status!==200) return; // or whatever error handling you want
document.getElementById('y').innerHTML= this.responseText;
};
xhr.send();
// FOR <IE8 Compatibility do this first:
if (!window.XMLHttpRequest && 'ActiveXObject' in window) {
window.XMLHttpRequest= function() {
return new ActiveXObject('MSXML2.XMLHttp');
};
}
replace x.html with your php file
While it is possible to create an image tag with that url as the src if you want to do it via AJAX as jQuery does there you could do this:
<script type="text/javascript">
function report(){
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",'mvc/assets/ajax/analytics/event_increment.php?id='+id',true);
}
window.onload = report;
</script>
You can use an img tag and put that in the src, and have your script return a transparent image.
Or as someone else pointed out, have it be the src of a script tag.
EDIT
If you don't want it to load if a bot accesses the page, you could use an img tag still
<img src="transparent.gif" width="1" height="1" />
Then, use javascript to change the src of the image to your php script. Most bots won't execute the javascript and therefor will never access your php script.
You may want to obfuscate the javascript a little though, so they don't see a url in it and try and access it.
<script type="text/javascript">
Window.onload(function(){
var id = "", xmlhttp = null;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
xmlhttp.open("GET","mvc/assets/ajax/analytics/event_increment.php?id=" + id,true);
xmlhttp.send();
}
})
</script>
there existed image preloaders in the early days of webpages, when internet connections were still slow, which created image objects to be used for rollover effects. this should still work and load the image:
<script type="text/javascript">
var img = new Image('http://url.to/your/image/or/script');
</script>
As 2019 you can use ES6 fetch a modern replacement for XMLHttpRequest.
const options = {
method: "POST",
data: {
title: "foo",
body: "bar",
userId: 1
},
credentials: "include",
headers: {}
};
fetch("https://jsonplaceholder.typicode.com/posts", options)
.then(response => {
return response.json();
})
.then(jsonObject => {
console.log(jsonObject);
document.write(`ID ${jsonObject.id} was created!`);
})
.catch(error => {
document.write(error);
});

how to call remote page in div?

this is my code for taking external page into div using ajax
what i tried is i clicked on button i must display the response in div
but i tried several times but doesn't works.
my javascript code is
var rootdomain="http://"+window.location.hostname
function ajaxinclude(url) {
var url=rootdomain+url;
alert(url);
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.open('GET', url, false) //get page synchronously
page_request.send(null)
writecontent(page_request)
}
function writecontent(page_request){
if (window.location.href.indexOf("http")==-1 || page_request.status==200)
document.getElementById("eee").innerHTML=(page_request.responseText);
}
and this is my body section :-----
<input type="button" onclick="ajaxinclude('/songcake/index.php')" value="Click !" />
<div id="eee" style=" width:400px; height:800px;">
</div>
please help
Thanks.
Use jQuery and you can just do something like
$.get('/songcake/index.php', function(data) { $("#eee").html(data); });
attach your method to onreadystatechange which not there in your code
page_request.onreadystatechange = writecontent;
function writecontent() {
if (page_request.readyState != 4) { return; }
document.getElementById("eee").innerHTML=(page_request.responseText);
}

Browser compatibility with AJAX function

I have the following AJAX function that calls a PHP file to determine if an email is present in a db.
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(Email){
var url="index.php?EmailCheck=Yes&Email=" + Email;
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
if(ajaxRequest.responseText == 0) {
alert("Sorry that email is not registered.");
} else {
alert("Login successful.");
window.opener.location.reload();
window.close();
}
}
}
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
Are there going to be any browsers this won't work for? I have had some complaints from users, but I can't replicate the errors in IE, FF, or Chrome.
It won't work in Lynx, and it probably won't work in some specialized screen-reader browsers. If you seriously expect to have users for which it won't work, for God's sake fix the error message. Better yet, use something like jQuery. Realize that it's possible to fall back to an alternative approach of using a hidden <iframe> or something instead of XMLHTTPRequest.

Categories

Resources