I have made an AJAX code for an on-line food store but when i am running it, it is not showing the correct output i.e. a pop up saying something went wrong always pops up. I want to know what is the problem in my code, is it something to do with the connection handlers or the JS script
Here is my index.php code
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>AJAX</TITLE>
<SCRIPT type = "text/javascript" src = "JS/store.js"></SCRIPT>
</HEAD>
<BODY onload = "process()">
<H3>Foodstore</H3>
Enter the food you would like to order:
<INPUT type = "text" id = "user_input" placeholder = "Food Item" />
<DIV id = "output_area" />
</BODY>
</HTML>
Here is my JS code that I am using
var XML_HTTP = create_XML_HTTP_request_object();
function create_XML_HTTP_request_object() {
var XML_HTTP;
if(window.ActiveXObject) {
try {
XML_HTTP = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
XML_HTTP = false;
}
} else {
try {
XML_HTTP = new XMLHttpRequest();
} catch(e) {
XML_HTTP = false;
}
}
if (! XML_HTTP) {
alert('Cant create the object!!');
} else {
return XML_HTTP;
}
}
function process() {
if((XML_HTTP.readyState == 0) || (XML_HTTP.readyState == 4)) {
food = encodeURIComponent(document.getElementById("user_input").value);
url = "process.php?food=" + food;
XML_HTTP.open("GET", url, true);
XML_HTTP.onreadystatechange = handle_server_response;
XML_HTTP.send(null);
} else {
setTimeout('process()', 1000) ;
}
}
function handle_server_response() {
if(XML_HTTP.readyState == 4) {
if(XML_HTTP.status == 200) {
XML_response = XML_HTTP.responseXML;
XML_document_element = XML_response.documentElement;
message = XML_document_element.firstChild.data;
document.getElementById("output_area").innerHTML = '<SPAN style = "color:blue">' + message + '</SPAN>';
} else {
alert('Something went wrong!!');
}
}
}
Here is my PHP code that i am using
<?php
header('Content-Type: text/xml');
echo '<?XML version = "1.0" encoding = "UTF-8" standalone = "yes" ?>';
echo '<response>';
$food = $_GET['food'];
$food_array = array('tuna' , 'bacon' , 'loaf' , 'cheese' , 'pizza') ;
if(in_array($food , $food_array)) {
echo 'We do have ' . $food . ' !!';
} elseif($food == '') {
echo 'Enter a food item';
} else {
echo 'Sorry we don\'t sell ' . $food . ' !!';
}
echo '</response>';
?>
Firefox at least does NOT like the Processing Instruction
<?XML ... ?>
issues error not well-formed
... works fine with
<?xml ... ?>
However, while your code wont work, it WONT result in the alert ... the fact that your getting the alert suggests your browser can't find process.php
(it should be in the same folder as your HTML file)
and an added note ... Edge doesn't like upper case HTML tags, it doesn't break, but it has a sook about them
As an alternative to the ajax functions you posted, consider the following:
function _ajax( url, options ){
var factories=[
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject('Msxml2.XMLHTTP'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.3.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.4.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.5.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.6.0'); },
function() { return new ActiveXObject('Microsoft.XMLHTTP'); }
];
/* Try each factory until we havea winner */
for( var i=0; i < factories.length; i++ ) {
try { var req = factories[ i ](); if( req!=null ) { break; } }
catch( err ) { continue; }
};
var method=options.hasOwnProperty('method') ? options.method.toUpperCase() : 'POST';
var callback=options.hasOwnProperty('callback') ? options.callback :false;
if( !callback ){
alert( 'No callback function assigned' );
return false;
}
var headers={
'Accept': "text/html, application/xml, application/json, text/javascript, "+"*"+"/"+"*"+"; charset=utf-8",
'Content-type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
};
/* The main parameters of the request */
var params=[];
if( options.hasOwnProperty('params') && typeof( options.params )=='object' ){
for( var n in options.params ) params.push( n + '=' + options.params[n] );
}
/* Additional arguments that can be passed to the callback function */
var args=options.hasOwnProperty('args') ? options.args : {};
/* Assign callback to handle response */
req.onreadystatechange=function(){
if( req.readyState ) {
if( req.status==200 ) options.callback.call( this, req.response, args );
else console.warn( 'Error: '+req.status+' status code returned' );
}
}
/* Execute the request according to desired method */
switch( method ){
case 'POST':
req.open( method, url, true );
for( header in headers ) req.setRequestHeader( header, headers[ header ] );
req.send( params.join('&') );
break;
case 'GET':
req.open( method, url+'?'+params.join('&'), true );
for( header in headers ) req.setRequestHeader( header, headers[ header ] );
req.send( null );
break;
}
}
You could then use it like this:
function process(){
call _ajax( this, 'process.php', { 'method':'get', 'callback':handle_server_response, params:{ 'food':food } } );
}
function handle_server_response(response){
try{/* this is not tested! */
var XML_document_element = response.documentElement ;
var message = XML_document_element.firstChild.data ;
document.getElementById("output_area").innerHTML = '<SPAN style = "color:blue">' + message + '</SPAN>' ;
}catch(err){
console.warn('oops, an error occurred: %s',err);
}
}
For future ajax requests you would only have to supply different arguments to the _ajax
function rather than rewrite each time. Also, rather than popup a warning message that the user might not understand the errors get logged to the console.
Personally however I'd recommend using JSON rather than XML if there is no specific need to use XML. It's much easier to read and write programatically, requires fewer bytes to transmit and is less prone to anomolies with odd characters.