xmlhttp.readyState is not changing - javascript

i was trying to build a application that demonstrate the use of ajax. as i am a newbie in ajax i couldnt able to find the error for my code. xmlhttp object is creating, rest of the things are not working,
the ready state is not changing to 1 or more than that, i have tried by printing all status values.
<html>
<head>
<title>Home</title>
<script type="text/JavaScript">
function process()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp.readyState==4 && xmlhttp.readyState==0)
{
food= document.getElementById("username").value;
xmlhttp.open("GET","food.php?food="+food,true);
xmlhttp.onreadystatechange=handleServerResponse();
xmlhttp.send();
}
else
{
setTimeout("process()",1000);
}
}
response function,
function handleServerResponse()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
xmlResponse=xmlhttp.ResponseXML;
xmlDocumentElement= xmlResponse.documentElement;
message=xmlDocumentElement.firstChild.data;
document.getElementById("status").innerHTML="message";
setTimeout("process()",1000);
}
}
</script>
</head>
<body >
<form method="post">
<fieldset><center><h2>Login</h2></center>
<label>Username</label>
<input type="text" id="username" value="" maxlength="20" />
<div id="status" ></div>
<input type="button" value=" Login " onClick="process()" />
</fieldset>
</form>
</body>
</html>
php code is below
<?php
echo "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>";
echo "<response";
$food=$_GET['food'];
if($food=="ajith")
echo "Successs";
else
echo "Invalid";
echo "</response>";
?>

var is not optional, use it.
First var xmlhttp; is a local variable, so you would not be able to use it in the other method. Needs to be moved outside of the process function.
Your if check is is impossible
xmlhttp.readyState==4 && xmlhttp.readyState==0
How can something be 2 values at once?
xmlhttp.readyState==4 || xmlhttp.readyState==0
Next issue is the fact you are not assigning an event handler you are calling it
xmlhttp.onreadystatechange=handleServerResponse();
needs to be
xmlhttp.onreadystatechange=handleServerResponse;
There is no ResponseXML, there is responseXML
"message" is a string, not the variable you defined beforehand.
var xmlhttp;
function process () {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
var food= document.getElementById("username").value;
xmlhttp.open("GET","food.php?food="+food,true);
xmlhttp.onreadystatechange=handleServerResponse;
xmlhttp.send();
} else {
//alert("Can not make Ajax request");
}
}
function handleServerResponse () {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var xmlResponse=xmlhttp.responseXML;
var xmlDocumentElement= xmlResponse.documentElement;
var message=xmlDocumentElement.firstChild.data;
document.getElementById("status").innerHTML = message;
window.setTimeout(process,1000);
}
}

Related

My AJAX script is not giving any output

index.php:-
<!DOCTYPE html>
<html>
<head>
<script src="food.js"></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
</head>
<body onloadd="process()">
<div class="container">
<h2 class="page-header">The Chuff Bucket</h2>
<strong>Enter the food you want to order:</strong><br><br>
<input type="text" class="form-control" id="userInput">
<div id="underInput">
</div>
</div>
</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','loaf','sandwich','pizza');
if(in_array($food, $foodArray))
{
echo 'We do have'.$food.'!';
}
elseif($food=='')
{
echo 'Enter a food chomu';
}
else
{
echo 'We have no'.$food;
}
echo '</response>';
?>
food.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("Cannot create the object!!");
}
else
{
return xmlHttp;
}
}
function process() {
if(xmlHttp.readyState == 0 || xmlHttp.readyState == 4)
{
var food = encodeURIComponent(document.getElementById("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;
xmlDocElm = xmlResponse.documentElement;
msg = xmlDocElm.firstChild.data;
document.getElementById("underInput").innerHtml = '<span style="color:blue;">'+msg+'</span>';
setTimeout('process()',1000);
}
else
{
alert("Something is wrong!!");
}
}
}
I just started with AJAX and this is my first code. I have even free hosted it. Here is the url:- Chuff Bucket
I have no idea what is wrong with the code. I have done the same as shown in the tutorial.
This isn't doing what you think:
xmlHttp.onreadystatechange = handleServerResponse();
This is invoking the handleServerResponse function immediately (which doesn't do anything, because xmlHttp.readyState isn't 4 at that time), and setting the result of that function to the onreadystatechange callback. Since that function doesn't return anything, that result is undefined.
Don't invoke the function, just set it like a variable as the callback:
mlHttp.onreadystatechange = handleServerResponse;
There is javascript framework offering a simplified way to use Ajax request like jQuery Ajax.
Using this kind of framework is a good way to simplify your code and to not repeat yourself DRY.
A jQuery version :
<script>
$(document).on('keyup', '#userInput', function(){
var food = $(this).val(); // # <= means ID
$.get('foodstore.php', 'food='+food, function(response){
$('#underInput').html(response);
});
});
</script>

PHP ajax call failure

I am new to ajax and trying to create AJAX->PHP connection. I am using the following code
file1.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<input type="text" id='demo'>
<input type="button" onclick='ajaxCall()' value='23' >
<script>
function ajaxCall()
{
document.getElementById('demo').value="343434";
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.requeststate==4 && xmlhttp.status==200){
document.getElementById('demo').value="4444343434";
document.getElementById('demo').value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
</script>
</body>
</html>
and the corresponding test.php
<?php
echo "me";
?>
Now when I click the button, the value of textbox is changing to 343434 but not changing on AJAX call, even it does not change to 4444343434. I'm currently runnning php 5.5.6 on ubuntu 14.04LTS.
Change xmlhttp.requeststate to xmlhttp.readyState
Try use the following crossbrowsing function
function getXmlHttp(){
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
And change xmlhttp = new XMLHttpRequest(); to xmlhttp = new getXmlHttp();
And this work without jQuery.

Send poll results with SUBMIT button

I have the following code for a poll:
<div id="pollE2">
How's the weather today?<br />
<form>
<input type="radio" name="voteE2" value="a" onclick="VoteNow(this.value)" /> Good
<input type="radio" name="voteE2" value="b" onclick="VoteNow(this.value)" /> Bad
</form>
</div>
Where the "VoteNow" function looks like this (it send the results to the "resultsE2.php" file...):
function VoteNow(int) {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("pollE2").innerHTML=xmlhttp.responseText; }
}
xmlhttp.open("GET","resultsE2.php?voteE2="+int,true);
xmlhttp.send(); }
When the user chooses one option from the pull, the results show directly, but I want the user to be able to click on a SUBMIT button before doing it.
I tried to use document.getElementById(formID).submit() but I'm not sure how to incorporate it in the code.
Any suggest
ions?
Change your HTML
<form id="vote-form">
Change your code
function VoteNow(vote) {
//Added line
var xmlhttp;
var vote = getRadioButtonValue();
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("pollE2").innerHTML=xmlhttp.responseText; }
}
xmlhttp.open("GET","resultsE2.php?voteE2="+vote, true);
xmlhttp.send();
}
var form = document.getElementById("vote-form");
form.onsubmit = function {
VoteNow();
// Prevent the form from submitting
return false;
};
function getRadioButtonValue() {
//http://stackoverflow.com/questions/9618504/get-radio-button-value-with-javascript
}

Javascript is not working on ajax call

I've a multiple select on my code with the onchange function ajax call,when the value is passed through the ajax it gets data from database and plot the chart by highcharts script,my problem is javascript is not worrking on ajax call,please suggest anything best,thanks in advance
source.php
<script>
function something(str)
{
if (str=="")
{
document.getElementById("div1").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("div1").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","destination.php?q="+str,true);
xmlhttp.send();
} </script>
<body>
<select multiple="multiple" onchange="something(this.value);">
<option>value1</option>
......
<option>valuen</option></select>
<div id="div1"></div>
destination.php
on here (destination page) get data from the database using the requested value from ajax
<?php
include("config.php");
$var=$_REQUEST['str'];
$query=mysql_query("select * from table where column=$var");
while($row=mysql_fetch_array($query))
{
$value[]=$row['data'];
}
<script>
<!--- here my highcharts script for ploting graph by the above fetching value from database --!>
</script>
?>

xmlHttp.status==200 is never true

I have a project and I'm using ajax and php. The problem is that the status of the XMLHttpRequest() is never 200. None of the solutions I've searched is working so I'm asking here. I copy/paste here the script and the php file which ajax sends a variable.
The script
function categoryfilter(int) {
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 $$ xmlHttp.status == 200) {
document.getElementById("test").innerHTML = xmlHttp.responseText;
alert("GOOD");
}
}
xmlHttp.open("GET","ajax_livecategorysearch.php?category=" + int, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send();
}
The php file
<?php echo "whatever"; ?>
The html code
<input id="category" name="category" type="radio" checked="checked" onclick="categoryfilter(this.value);" >
When I delete the condition xmlHttp.status==200, the function returns error 404 page not found.
You have a typo in the code:
if (xmlHttp.readyState==4 $$ xmlHttp.status==200)
should be
if (xmlHttp.readyState==4 && xmlHttp.status==200)

Categories

Resources