XMLHttpRequest not working - no errors - javascript

I am trying to get this simple request working but I am not having much luck.
I have the "test.txt" file in the server folder as my html file containing the script provided below.
I viewed the file in Chrome, Firefox and IE11 with the same result. I can only see the "Initial text in the html page.." text from the html page. No errors and the text from my test.txt file is not getting displayed.
Could anyone please point me what the issue with my code is?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp
if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
else{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp:
}
function process(){
if(xmlHttp){
try{
xmlHttp.open("GET","test.txt", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
catch(e){
alert( e.toString() );
}
}
}
function handleServerResponse(){
output = document.getElementById('output');
if(xmlHttp.readyState==1){
output.innerHTML += "Status 1: server connection established <br />"
}
else if(xmlHttp.readyState==2){
output.innerHTML += "Status 2: request received <br />"
}
else if(xmlHttp.readyState==3){
output.innerHTML += "Status 3: server processing <br />"
}
else(xmlHttp.readyState==4){
if(xmlHttp.status=200){
try{
text = xmlHttp.responseText;
output.innerHTML += "Status 4: request is finished and response is ready<br />"
output.innerHTML += text;
}
catch(e){
alert( e.toString() );
}
}
else{
alert( xmlHttp.statusText );
}
}
}
</script>
</head>
<body onload="process()">
Initial text in the html page..<br>
<br>
<div id="output">
</div>
</body>
</html>

Ok, I figured it out....
it was one typo and one ommision
return xmlHttp: -> should be ; instead
and forgot "else"
else(xmlHttp.readyState==4){ -> should be else if (xmlHttp.readyState==4){

Related

Why won't this javascript code work in Wordpress post?

I have xml file test.xml with the content
<?xml version= "1.0" encoding= "UTF-8" ?>
<LIST><script />
<ONEP>
<LINK>/wordpress/new_1.html</LINK>
<CHAPTER >One 1</CHAPTER>
</ONEP>
<ONEP>
<LINK>/wordpress/new_2.html</LINK>
<CHAPTER>One 2</CHAPTER>
</ONEP>
</LIST>
I want to load this content into my Wordpress page so I insert the code which is given below into my Wordpress page directly.
<div id="demo">
</div>
<script type="text/javascript">
window.onload = function() {
loadXMLDoc();
};
function loadXMLDoc( ) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET", "../wordpress/test.xml", true);
xmlhttp.send( );
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<strong>Chapter</strong>";
var x = xmlDoc.getElementsByTagName("ONEP");
for (i = 0; i <x.length; i++) {
table += "<br/><a href=\".." +
x[i].getElementsByTagName("LINK")[0].childNodes[0].nodeValue +
"\">" +
x[i].getElementsByTagName("CHAPTER")[0].childNodes[0].nodeValue +
"</a>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
Now I preview the page.Nothing is found in the page.
I even tried the code using the plugin "Jquery in posts and page" but still the code does not work.I am completely lost.Note the code works perfectly fine in normal html file.It is not working only in Wordpress page and posts.Any help please.
Thank you in advance.
Try Below code to get data from xml file into PHP:
if (file_exists('path to test.xml')) {
$xml = simplexml_load_file('path to test.xml');
echo '<pre>';
print_r($xml);
} else {
exit('Failed to open test.xml.');
}
you will get multidimensional array with all tags and inner content into PHP.

javascript notification checker script Uncaught Reference Error

I have this notification checker and i don't know whats wrong with this js code, i have errors on checkMessage() : Uncaught Reference Error: checkMessage is not defined
the js code:
function checkMessage(){
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() //when the request is submitted...
{
if (xmlhttp.readyState==4 && xmlhttp.status==200 //...and everything is ok...
{
if(xmlhttp.responseText>0){ // if the response text is greater than 0
document.title="("+xmlhttp.responseText+")"+"My Social Network - Welcome";
document.getElementById('checkMsg').innerHTML="<b>" + xmlhttp.responseText+" Notifications</b>";
}
else
document.title="My Social Network - Welcome";
document.getElementById('checkMsg').innerHTML="No notifications";
}
}
xmlhttp.open("GET","checkMessage.php?user_id="+"1",true);
xmlhttp.send();
}
the checkmessage.php code:
<?php
include 'dbm.php'; //database settings from an external file
$user = $_SESSION['user'];
$get_count_messages = mysql_query("SELECT message FROM notifications ");
$row = mysql_num_rows($get_count_messages); // count how many rows the query returned
echo "$row"; //return the value
?>
The html code:
<html>
<head>
<script type="text/javascript" src="notifications.js"></script>
<script type="text/javascript">
setInterval("checkMessage()", 1000);
</script>
</head>
<body>
<div id="checkMsg"></div>
</body>
</html>
It's just a simple example to make a difference betwen the number of notifications
if (xmlhttp.readyState==4 && xmlhttp.status==200 //...and everything is ok...
{
var title = "";
var message;
if(xmlhttp.responseText > 0)
{
title += "(" + xmlhttp.responseText + ")";
if(xmlhttp.responseText > 1)
message = "<b>" + xmlhttp.responseText + " Notifications</b>";
else
message = "<b>" + xmlhttp.responseText + " Notification</b>";
}
else
message = "No notifications";
title += "My Social Network - Welcome";
document.title = title;
document.getElementById('checkMsg').innerHTML= message;
}
I think your setInterval function should look like:
setInterval(checkMessage, 1000);
Because setInterval expect a function as parameter.

Insert XML node value inside iframe src

Been trying everything and all i get is a blank page ...
The XML is provided by URL format and contains many nodes but i just want to take out the username and place it inside a iframe scr url.
optimal this will repeat for until no more usernames on that xml
Here is what i got so far
<script type="text/javascript">
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", "http://xml.url/here", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
y=xmlDoc.documentElement.childNodes;
for (i=0;i<y.length;i++)
{
if (y[i].nodeType!=3)
{
//This code for printing attribute of a tag(you have to give attribute name).
document.write("<br>" + y[i].getAttributeNode('username').nodeName + ": ");
document.write(y[i].getAttributeNode('username').nodeValue + "<br>");
for (z=0;z<y[i].childNodes.length;z++)
{
if (y[i].childNodes[z].nodeType!=3)
{
//This is for Node Name.
document.write(y[i].childNodes[z].nodeName + ": ");
//This is for Node Value.
document.write(y[i].childNodes[z].textContent + "<br>");
}
}
}
}
</script>
<iframe src="http://blablabla + 'username' + blablabla " height="300" width="400" style="border: none;"></iframe>

Ajax won't Display on web page

I am currently trying to use a Ajax in netbeans using JavaScript and PHP file. The following code I should click the button and the contents of the php fill should appear but it doesn't. When I use firebug in firefox the response shows the full php file has returned but will not display on webpage. Why???
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script>
function getXMLHttp() {
var xmlHttp
try {
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
//Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest() {
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "ajax.php", true);
xmlHttp.send(null);
}
function HandleResponse(response) {
document.getElementById('ResponseDiv').innerHTML = response;
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<input type='button' onclick='MakeRequest();' value='Use AJAX!!!!'/>
<div id='ResponseDiv'>
This is a div to hold the response.
</div>
</body>
</html>
My PHP file is
<?php
echo "This is a php response to your request!!!!!!";
?>
Apart from the fact that HTML code is barely decent, why not use jQuery?
<button id="get" onClick="return false;">jQuery get</button>
<div id="result"></div>
<script type="text/javascript">
$("#get").click(function() {
$.get( "ajax.php", function( data ) {
$( "#result" ).html( data );
});
});
</script>
PHP is server side and is not made to be run on the client side. Your response should come from a URL and not the contents of a file. Ensuring that your response contains on HTML and not PHP should lead you to your solution.
Try replacing your PHP file with
<p>This is a php response to your request!!!!!!</p>
If this enables you to show your content, you have your problem and solution.

First small foodstore-project with ajax - does not execute

I have just started to learn Ajax and have watched a tutorial on how to write a small input that checks whether a foodstore has something in stock or whether it hasn't.
I have double-checked the code several times but it still does not execute anything. I would be glad if anyone could help me here.
The code is basically three files:
Index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
<h3>The Food Store</h3>
<p>Enter the food you would like to have:</p>
<input type="text" id="userInput">
<div id="underInput"/>
</body>
</html>
foodstore.php
<?php
header('Content-Type: text/xml');
echo '<xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna', 'bacon', 'beef', 'ham');
if(in_array($food,$foodArray)) {
echo 'We do have '.$food'!';
echo '</response>';
}
}
?>
and finally the foodstore.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject() {
var xmlHttp;
if(window.ActiveXObject) {
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
xmlHttp = false;
}
}else{
try{
xmlHttp = new XMLHttpRequest();
} catch(e){
xmlHttp = false;
}
}
if(!xmlHttp)
alert("Cant create that object!");
else {
return xmlHttp;
}
}
// This is now the communication part!
function process() {
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
food = encodeURIComponent(document.getElmentById("userInput").value);
xmlHttp.open("GET", "foodstore.php?food=" + food, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('process()',1000);
}
}
function handleServerResponse() {
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML = '<span styel="color:blue">' + message + '</span>';
setTimeout('process()',1000);
}else{
alter('Something went wrong!');
}
}
}
I would really appreciate some help. I also read in the youtube-comments that jQuery would rather be easier to use as far as the js part goes. Is that true?
Many thanks!
In the foodstore.js you have a litlle problem you have writed document.getElmentById("userInput").value and it must be
document.getElementById("userInput").value

Categories