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);
}
Related
So I have a list of movies and their info displayed from mysql in a table on a JSP. Each movie's table entry looks like <a id="135006" onmouseover=ajaxFunction(this); href=SearchSingleMovieServlet?txt_movie_id=135006>The Life Aquatic</a>.
My ajax function looks like:
<script language="javascript" type="text/javascript">
function ajaxFunction(obj){
var ajaxRequest;
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){
$( '#'+ obj.id ).tooltip({
content: "<strong>Hi!</strong>",
track:true
});
document.getElementById('popup').innerHTML = '#' + obj.id+ ajaxRequest.responseText;
}
}
var parameter = "movie_id=" + obj.id;
ajaxRequest.open("POST","MoviePopUpWindowServlet", true);
ajaxRequest.setRequestHeader("Content-type"
, "application/x-www-form-urlencoded")
ajaxRequest.send(parameter);
}
</script>
The line document.getElementById('popup').innerHTML = '#' + obj.id+ ajaxRequest.responseText; is just a debugging line so I can see if the code enters the AJAX function and to make sure responseText displays correctly (which it does). But when I try mousing over the link of the movie, its tooltip doesn't show. Any reason why?
There is a way for combine these two technologies so that they work together when we are alredy in the div "result" ?
Let's see the problem.. We have the first code that do the ajax request
var http_request = false;
function makeRequest(url,getvar,funzione) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
//http_request.overrideMimeType('text/xml');
// See note below about this line
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Errore :( Non riesco a creare unna connessione XMLHTTP');
return false;
}
http_request.onreadystatechange = funzione;
http_request.open('POST', url, true);
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http_request.send(getvar);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
//alert(http_request.responseText);
document.getElementById("result").innerHTML = http_request.responseText;
} else {
alert('C\'è stato un problema alla connessione.');
}
}else{
document.getElementById("result").innerHTML ="loading";
}
}
And another function that edit the andress bar..
jQuery(document).ready(function() {
$('a.clickurl').click(function(event) {
var currentPage = document.location.pathname.substring(document.location.pathname.lastIndexOf('/') + 1);
if ($(this).attr('href') != currentPage){
if (history && history.pushState) {
history.pushState(null, document.title, $(this).attr('href'));
$.get($(this).attr('href'), {ajax:'1'}, function(data, text, xhr) {
pageSlider(data, text, xhr);
});
event.preventDefault();
}
}
});
after the first istance we got result on the div.. and up to here everything is working correctly, but how let the function work also in the links inside the "result" div?
setting a href="#" the ajaxrequest work correctly and just reflash the "result" div.. but if i set an different address loads the entire page..
ps. i already tried return false;
Problem is the fact that you are not binidng events to the dynamic content. You need to either rebind or use event delegation.
$(document).on("click", 'a.clickurl', function(event) {
or even better if all the links are only in the result div
$("#result").on("click", 'a.clickurl', function(event) {
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);
});
i have this ajax function working well in firefox and not in ie6
are there some specific issues for ie?
the error is on ths line
document.getElementById(containerid).innerHTML=page_request.responseText
here is the full code i'm using
var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects=""
var rootdomain="http://"+window.location.hostname
var bustcacheparameter=""
function ajaxpage(url, containerid){
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.onreadystatechange=function(){
loadpage(page_request, containerid)
}
if (bustcachevar) //if bust caching of external page
bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', url+bustcacheparameter, true)
page_request.send(null)
}
function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 ||
window.location.href.indexOf("http")==-1))
////////////////////// here is the error line pointed by ie debugger/////////
document.getElementById(containerid).innerHTML=page_request.responseText
//////////////////////////////
}
thanks for your answers
Try using something like this - or checking out jQuery
function isIE(){return/msie/i.test(navigator.userAgent)&&!/opera/i.test(navigator.userAgent);}
function parseFile(filename)
{
try
{
if(isIE())
{var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
else
{var xmlhttp=false;}
if(!xmlhttp&&typeof XMLHttpRequest!='undefined')
{
try
{xmlhttp=new XMLHttpRequest();}
catch(e)
{xmlhttp=false;}
}
if(!xmlhttp&&window.createRequest)
{
try
{xmlhttp=window.createRequest();}
catch(e)
{xmlhttp=false;}
}
xmlhttp.open("GET",filename);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
return xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
catch(e)
{
alert(e);
}
}
I have a bunch of divs with weird id and each of them contains a video. They're actually video embed codes but they're not usual to me. Here's one example:
<div id="evp-1fae4e37639894816f03591bc7009c68-wrap" class="evp-video-wrap"></div><script type="text/javascript" src="http://domain.com/evp/framework.php?div_id=evp-1fae4e37639894816f03591bc7009c68&id=cmVsYXRpb25zaGlwLW1hcmtldGluZy0xLmZsdg%3D%3D&v=1278525356"></script><script type="text/javascript">_evpInit('cmVsYXRpb25zaGlwLW1hcmtldGluZy0xLmZsdg==');</script>
What I want to do is create a video playlist. As a part of that, I created list using divs also which use the onclick attribute to trigger my JS function to switch between videos. Here's how it looks:
<div class="vid-list" onclick="switchvideo('http://domain.com/html-vids/headline-vids/second-vid.html', 2)"><p>This a video tutorial for blah blah blah.</p></div>
The problem is, each time I switch to another video the div id of the embed code changes also because otherwise it won't work. So I need to change that before loading the video script inside the div. I tried to achieve that using the following JS function:
function switchvideo(url, vidnumber)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET",url,false);
xmlhttp.send();
}
var div_node = document.getElementByClass('evp-video-wrap');
if ( vidnumber == 2 ) {
div_node.id = 'evp-78c0b7c4f6d3377954825f145734fd5c-wrap';
}
document.getElementById(div_node.id).innerHTML=xmlhttp.responseText;
}
Apparently it's not working. I suspect the problem are the lines in bold above. I tried to get the element by 'class' and its id by using 'div_node.id'. I am assuming that by doing 'document.getElementByClass', I am getting the reference to that element so I could use it to manipulate its other attributes. But I am not sure... Could anyone pls enlighten me??
There is no getElementByClass() method. There is a getElementByClassName() but it's not available in every browser.
Here is one you can use:
// http://www.dustindiaz.com/getelementsbyclass/
function getElementsByClass(searchClass, node, tag) {
var classElements = new Array();
if (node == null) node = document;
if (tag == null) tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
Then you can call it as
getElementByClass('evp-video-wrap');
Your ajax is a bit tricky, but here is a more general one:
function getXmlHttpObject() {
var xmlHttp;
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");
}
}
if (!xmlHttp) {
alert("Your browser does not support AJAX!");
}
return xmlHttp;
}
function ajax(url, onSuccess, onError) {
var xmlHttp = getXmlHttpObject();
xmlHttp.onreadystatechange = function() {
if (this.readyState === 4) {
// onSuccess
if (this.status === 200 && typeof onSuccess == 'function') {
onSuccess(this.responseText);
}
// onError
else if(typeof onError == 'function') {
onError();
}
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
return xmlHttp;
}
Finally your code becomes:
function switchvideo(url, vidnumber) {
var div_node = getElementByClass('evp-video-wrap')[0];
// make a call to the url, and execute the
// callback when the response is available
ajax(url, function( responseText ){
if (vidnumber == 2) {
div_node.id = 'evp-78c0b7c4f6d3377954825f145734fd5c-wrap';
}
document.getElementById(div_node.id).innerHTML = responseText;
});
}
You can see the whole code [here]
getElementByClass isn't a standard method. Is it possible for you to use a framework for this? jQuery has a nice mechanism to search for an element by class, as do the other frameworks. It also makes it much easier to do the AJAX bits in a cross-browser supported way.
function switchvideo(url, vidnumber)
{
$.get(url, function(data) {
var div_node = $('.evp-video-wrap');
if (vidnumber == 2) {
div_node.attr('id', 'evp-78c0b7c4f6d3377954825f145734fd5c-wrap');
}
div_node.html( data );
});
}
An alternative would be to write your own getElementByClass or specific code to search for a DIV by class. Note: I assume you're only interested in the first match.
function getDivByClass( klass )
{
var regex = new RegExp( '(^|\\s+)' + klass + '(\\s+|$)' );
for (div in document.getElementsByTagName('div')) {
if (regex.text( div.className)) {
return div;
}
}
return null;
}