AJAX won't get PHP - echo - javascript

So I'm trying to build a pretty simple website, to learn basic webdesign. It's just a random quote generator - you click on a button and it prints some famous quote. Anyway, I try to use ajax to get the quote, so I use this function:
function loadXMLDoc()
{
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)
{
document.getElementById("quote").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","RandomQuote.php",true)
xmlhttp.send();
}
but no matter what I type into RandomQuote.php, even if it's something like :
<?php
echo 'Hello, world';
?>
nothing shows up in the quote "div', it just becomes blank. I really have no idea what's the problem here. Thanks for the help!

Well, I'm not sure about much, but are you calling your function? You put your ajax inside loadXMLDoc() , so you probably have to call it. Another way is to put your ajax into an addEventListener so when a user clicks on something, it'll execute. If that's not the problem, try making sure your element in your html page with the id of "quote" is spelled correctly. Sometimes the latter scenario is always the problem for me.

$.get( "RandomQuote.php", function( data ) {
$( "#quote" ).html( data );
console.log( "Load was performed." );
});
Don't forget to include jQuery.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

This is my ajax function, try to use it:
/**
* #function ajax Send ajax-request with post
* #param {string} xmlpage Target url
* #param {string} data Post parameters (like param1=val1&param2=val2...)
* #param {Function} callback
* #return {null}
*/
function ajax(xmlpage, data, callback)
{
var xmlh = null;
if(window.XMLHttpRequest)
xmlh = new XMLHttpRequest();
else
try
{
xmlh = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(ex)
{
xmlh = new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlh)
{
xmlh.open("post", xmlpage, true);
xmlh.onreadystatechange = function(x)
{
if(xmlh.readyState==4 && typeof callback !== 'undefined')
callback(xmlh.responseText);
}
xmlh.setRequestHeader("Accept-Language","ru, en");
xmlh.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlh.send(data);
}
}

Following test files using your code from the question. It is working perfectly. Either you are missing something or its a browser issue. I tested on Mozilla. To be sure of browser independent code use jQuery for Ajax call
test.html
<html>
<script>
function loadXMLDoc()
{
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)
{
document.getElementById("quote").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","RandomQuote.php",true)
xmlhttp.send();
}
</script>
<div id="quote"></div>
<input type="button" value="Click Me" onclick="loadXMLDoc()"/>
</html>
RandomQuote.php
<?php
echo 'hi';
Update: jQuery version
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function loadXMLDoc()
{
$.get( "RandomQuote.php", function( data ) {
$( "#quote" ).html( data );
});
}
</script>
<div id="quote"></div>
<input type="button" value="Click Me" onclick="loadXMLDoc()"/>
</html>

Related

Javascript "getElementsByClassName" not working

I have a website with a picture of a tree, I have then used Ajax to remove that tree and insert a number using javascript. What I used for that was;
document.getElementById("cut_oak_tree");
I have now added another tree on the page, which should have the exact same function as the first tree, except that only the tree that you clicked on, shall be removed. To avoid duplicating code, I have tried adding following:
document.getElementsByClassName("cut_oak_tree");
and then changed my div from using id to class. However, nothing happens when I click any of the trees now. My current ajax code right now, looks like this:
function loadXMLDoc()
{
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)
{
var getClass = document.getElementsByClassName("cut_oak_tree").innerHTML=xmlhttp.responseText;//ask for this.
for(i=0;i<getClass.length;i++)
{
getClass[i].innerHTML = "";
}
}
}
xmlhttp.open("POST","xxx",true);
xmlhttp.send();
}
I have been searching a lot and found that I might need to use a for loop together with the document.getElementsByClassName("cut_oak_tree");
but I can't really get that to work. If I have figured my problem correctly, everything should be good if I could just determine which of the tree images in the div should be removed when it's pressed. Thanks in advance.
EDIT:
Html sample:
<div id "thanks">
<img class="cut_oak_tree" src="http://www.pbpixels.com/x/images/oak.png" onclick="loadXMLDoc(), myFunction()">
<img class="cut_oak_tree" src="http://www.pbpixels.com/x/images/oak.png" onclick="loadXMLDoc(), myFunction()">
</div>
Try the following:
document.getElementsByClassName("cut_oak_tree")[0];
If you want to apply changes to more than one elements with classname cut_oak_tree then you will have to use for loop
var getClass = document.getElementsByClassName("cut_oak_tree");
for(i=0;i<getClass.length;i++)
{
getClass[i].innerHTML = "";
}
Using your earlier HTML with slight modifications you can do the following:
HTML
<div class="cut_oak_tree">
<img src="http://www.pbpixels.com/x/images/oak.png" onclick="loadXMLDoc(this.outerHTML), myFunction()" />
<img src="http://www.pbpixels.com/x/images/oak.png" onclick="loadXMLDoc(this.outerHTML), myFunction()" />
</div>
Hence change your JS function to :
function loadXMLDoc(h)
{
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)
{
var getEle = document.getElementsByClassName('cut_oak_tree')[0];
getEle.innerHTML = getEle.innerHTML.replace(h,xmlhttp.responseText);
}
}
xmlhttp.open("POST","http://www.pbpixels.com/x/post.php",true);
xmlhttp.send();
}
Demo Fiddle
Response to comment:
Inorder to uniquely identify clicked <img>s with same images just make minor change to the one of the img srcs from the two.Example give space within src src="http://www.pbpixels.com/x/images/oak.png ".Note the space after .png which will make the difference between the two
I would think that the most straightforward way to do it would be to pass the clicked element into the loadXMLDoc() as a parameter, and then get the parent of that element. Something like this:
HTML
<div id="cut_oak_tree">
<img src="http://www.pbpixels.com/x/images/oak.png" onclick="loadXMLDoc(this), myFunction()">
<img src="http://www.pbpixels.com/x/images/oak.png" onclick="loadXMLDoc(this), myFunction()">
</div>
JS
function loadXMLDoc(clickedElement) {
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) {
clickedElement.parentNode.innerHTML = xmlhttpinnerHTML = xmlhttp.responseText; //ask for this.
}
}
xmlhttp.open("POST","xxx",true); //the xxx's represent my website
xmlhttp.send();
}
NOTE: I'm not 100% sure that I have the logic right, since you changed your original post, while I was typing up my answer. :)
UPDATE #2: I found the original code in the edit history . . . my code should be correct now.

How to autorefresh XML in Javascript

Below is the code that I am having trouble with -
<script type="text/javascript" language="javascript">
function loadXMLDoc()
{
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)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","<%=StatsURL%>",true);
xmlhttp.send();
}
function timedRefresh(timeoutPeriod) {
setTimeout(function(){loadXMLDoc(); autoRefresh();},timeoutPeriod);
}
</script>
And this is called in -
<body onload="JavaScript:timedRefresh(50000);">
<div id="myDiv"></div>
</body>
I want to refresh the page/load the XML every 5 seconds however the above code does not appear to work. I have read (http://www.htmlgoodies.com/tutorials/getting_started/article.php/3479551/Reloading-The-Page.htm) that you can use META tags ()to refresh the page as well.
Any help to get this code working would be greatly appreciated.
ANSWER
Change the code to the below -
window.onload = startInterval();
function startInterval()
{
setInterval("loadXMLDoc();", 5000);
}
That's because you refresh the page every 50 secs (50000 milliseconds). Change it to 5000 and it'll work.

Cannot get a 'bad response' from Ajax call

I'm trying to use Ajax to tell me whether my server is up or not. I've made a simple page with just one Ajax call. When the server is up, it comes back with the xmlhttp.responseText. IF the server is down it is supposed to say "SERVER DOWN"...but when I load the page, then turn off Apache, it still says that the server is up. Is there some other way I should be doing this?
<!DOCTYPE html>
<html>
<head>
<script>
var xmlhttp;
var url = "http://192.168.0.5/ajax_info.txt";
function loadXMLDoc(url,cfunc)
{
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=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction()
{
loadXMLDoc(url,function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
else
{
document.getElementById("myDiv").innerHTML = "Server Down!";
}
});
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction()">Change Content</button>
</body>
</html>
Thanks for the help
Your page is probably cached, use a cache buster in the url. e.g.
xmlhttp.open("GET",url+'?_dc='+(new Date()).getTime(),true);

Run php script every x mins using ajax request

got this file 'functions.php':
<?php
function test ($url){
$starttime = microtime(true);
$valid = #fsockopen($url, 80, $errno, $errstr, 30);
$stoptime = microtime(true);
echo (round(($stoptime-$starttime)*1000)).' ms.';
if (!$valid) {
echo "Status - Failure";
} else {
echo "Status - Success";
}
}
test('google.com');
?>
I want to run it every 10seconds or so, i was told to use ajax request but i dont completely understand how it works. I tried creating a new file 'index.php', and then had this written in it:
<script>
var milliSeconds = 10000;
setInterval( function() {
//Ajax request, i dont know how to write it
xmlhttp.open("POST","functions.php",true);
xmlhttp.send();
}, milliSeconds);
</script>
I put both files into ftp but nothing happens, can someone help me write a propper ajax request?
Edit: eddited typo, still doesnt work tho
var milliSeconds = 1000;
setInterval( function() {
var xmlhttp;
if (window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
console.log ( xmlhttp.responseText );
}
}
xmlhttp.open("POST","functions.php",true);
xmlhttp.send();
}, milliSeconds);
You have to load xmlhttp request object according to the browser ( xmlhttp=new XMLHttpRequest(); ), then set an event handler when the xmlhttp state changes ( xmlhttp.onreadystatechange=function() ). When it changes check if the status is 200 (success) then do whatever you want with the response. ( I printed it to console )
So, it sounds like your only problem is that you don't know how to write an XHR request. Take a look at Using XMLHttpRequest. Comment on this answer with your questions.
xmlhttp.open("POST","funkction.php",true);
should be:
xmlhttp.open("POST","functions.php",true);

how to store a xmlhttprequest into a variable

I have a quick question that you brainy guys perhaps have the answer to.
Why does this work
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url,cfunc)
{
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=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction()
{
loadXMLDoc("ajax_info.txt",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xlmhttp.responseText;
}
});
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction()">Change Content</button>
</body>
</html>
but if I replace
document.getElementById("myDiv").innerHTML=xlmhttp.responseText;
whit this
var txt=xlmhttp.responseText;
document.getElementById("myDiv").innerHTML=txt;
it don't work anymore, txt is
undefined
. How can I store the xlmhttp.responseText into a string, or into a variable that I can perform a search on? Please give an example on how I can do it. Thanks in advance =)
Might be because you have misspelled variable "xmlhttp" - you have "xlmhttp" in your code.

Categories