xmlHttp.status==200 is never true - javascript

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)

Related

AJAX is returning readystate=1

I am using Flask with Python. From the Flask method I am trying to return HTML table rows in an AJAX call.
The HTML page has:
<div>
<table id="tableQuestions">
</table>
//AJAX Requests to get
function loadQuestions() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
alert(xmlHttp.readyState + " " + xmlHttp.status);
if (xmlHttp.readyState==4 && xmlHttp.status == 200) {
var response = xmlHttp.responseText;
console.log(response);
document.querySelector("#tableQuestions").innerHTML=response;
}
xmlHttp.open("GET", '/gS', true);
xmlHttp.send(null);
}
}
The Flask route has:
#test.mix() returns html table rows
#gbp.route('/gS')
def gS():
test=mn()
response = make_response(test.mix(quesCount=4),200)
response.mimetype="text/html"
In the Safari debugger I can see that the responseText has the table data from the server, but readystate remains 1 and status = 0.
Could you please suggest how I can overcome this issue?
You have
xmlHttp.open("GET", '/gS', true);
xmlHttp.send(null);
inside your xmlHttp.onreadystatechange callback function, which leads to strange effects.
The following code (untested) should behave better:
//AJAX Requests to get
function loadQuestions() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", '/gS', true);
xmlHttp.onreadystatechange = function() {
alert(xmlHttp.readyState + " " + xmlHttp.status);
if (xmlHttp.readyState==4 && xmlHttp.status == 200) {
var response = xmlHttp.responseText;
console.log(response);
document.querySelector("#tableQuestions").innerHTML=response;
}
}
xmlHttp.send(null);
}

xmlhttp.readyState is not changing

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);
}
}

How to send a string to php with POST [duplicate]

This question already has answers here:
Send POST data using XMLHttpRequest
(13 answers)
Closed 8 years ago.
I'm sending a string via xmlhttp in javascript using the following code:
function SendPHP(str, callback) {
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) {
callback(xmlhttp.responseText); //invoke the callback
}
}
xmlhttp.open("GET", "testpost.php?q=" + encodeURIComponent(str), true);
xmlhttp.send();
}
and some test php:
$q = $_GET['q'];
echo $q;
That worked fine until I started sending a larger string in which case I get the "HTTP/1.1 414 Request-URI Too Long" error.
After a bit of research I found out I need to use "POST" instead. So I changed it to:
xmlhttp.open("POST", "sendmail.php?q=" + str, true);
And:
$q = $_POST['q'];
echo $q;
But this does not echo anything when using POST. How can I fix it so it works like when I was using GET but so it can handle a large string of data?
edit I'm now trying it with:
function testNewPHP(str){
xmlhttp = new XMLHttpRequest();
str = "q=" + encodeURIComponent(str);
alert (str);
xmlhttp.open("POST","testpost.php", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
alert (xmlhttp.responseText);
}
}
};
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(str);
}
You should not provide your href with URL parameters, instead of this you should send() them. For addition, you should always encode your parameters with encodeURIComponent() (At least when your request is using the Content-type "application/x-www-form-urlencoded").
your javascript function :
function testNewPHP(){
var str = "This is test";
xmlhttp = new XMLHttpRequest();
str = "q=" + encodeURIComponent(str);
alert (str);
xmlhttp.open("POST","testpost.php", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
alert (xmlhttp.responseText);
}
}
};
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(str);
}
javascript :
function testNewPHP(){
var str = "This is test";
xmlhttp = new XMLHttpRequest();
str = "q=" + encodeURIComponent(str);
alert (str);
xmlhttp.open("POST","testpost.php", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
alert (xmlhttp.responseText);
}
}
};
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(str);
}
testpost.php in your home directory :
<?php
var_dump($_POST);
OUTPUT :
array(1) {
["q"]=>
string(12) "This is test"
}

Preload image doesn't always appear

I have created a simple ajax request:
var params = "postdata=" + mydata;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("data").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "data.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
And this is the HTML code:
<div id="data">
<img src="/images/preload.gif" />
<b style="color:#9ca6dc;font-size:12px;">Wait</b>
</div>
The problem is that the preload.gif and "Wait" text appears only sometimes and not always.
Why ? How can I resolve that ?
The only explanation is that AJAX request works too quickly to see the content (as Alessandro Pezzato said). If you don't see it the readyState of XMLHTTP request had to change.
Or you have some other Javascript which runs asynchronously and does changes on the same content.

Simple XMLHttpRequest (Google Weather)

Hello I want to get xml from Google Weather
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.open("GET", "http://www.google.com/ig/api?weather=london&hl=en", true);
xmlhttp.send(null);
xmlDoc=xmlhttp.responseXML;
It`s not working . Thanks
XMLHttpRequest is asynchronous. You need to use a callback. If you don't want to use a full-fledged library, I recommend using Quirksmode's XHR wrapper:
function callback(xhr)
{
xmlDoc = xhr.responseXML;
// further XML processing here
}
sendRequest('http://www.google.com/ig/api?weather=london&hl=en', callback);
If you absolutely insist on implementing this yourself:
// callback is the same as above
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "http://www.google.com/ig/api?weather=london&hl=en", true);
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState != 4) return;
if (xmlhttp.status != 200 && xmlhttp.status != 304) return;
callback(xmlhttp);
};
xmlhttp.send(null);
Edit
As #remi commented:
I think you'll get a cross domain access exception : you can't make an ajax request to an other domain than your page's. no ?
Which is (for the most part) correct. You'll need to use a server-side proxy, or whatever API that Google provides, instead of a regular XHR.
You can't do this via javascript to to it being a cross-domain request. You'd have to do this server-side.
In PHP you'd use CURL.
What you are trying to do can't be done with Javascript.
Ok here is the code :
<html>
<body>
<script type="text/javascript">
var xmlhttp;
var xmlDoc;
function callback(xhr)
{
xmlDoc = xhr.responseXML;
// further XML processing here
}
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "http://www.google.com/ig/api?weather=london&hl=en", true);
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState != 4) return;
if (xmlhttp.status != 200 && xmlhttp.status != 304) return;
callback(xmlhttp);
};
xmlhttp.send(null);
alert(xmlDoc);
</script>
</body>
</html>
It doesn`t returns any errors but alert returns undefined.

Categories

Resources