ldoroni
ldoroni

Reputation: 103

Ajax code dose not working properly

Sorry for my english...

why this ajax code dosen't work properly ?

when I call the POST variable in the page that i send for him the info, its show me that the POST variable is not exist...

Can anybody explain why it is happening ?

part of the ajax code:

var xhr = new XMLHttpRequest();
xhr.open("POST",url,true);
xhr.onreadystatechange = function() {
    if( this.readyState == 4 && this.status == 200) {
        document.getElementById(name).innerHTML = this.responseText;
    }
};
xhr.send("info="+str+"&info_1="+info_1+"&info_2="+info_2);
return false;

Upvotes: -1

Views: 94

Answers (1)

Pyrech
Pyrech

Reputation: 592

Some headers must be included for POST request:

xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");

Edit :

My script use a variable called 'params'. So add a var at the beginning of your script and put in it the content of your request :

var params = "info="+str+"&info_1="+info_1+"&info_2="+info_2;

And replace in the call of xhr.send "info="+str+"&info_1="+info_1+"&info_2="+info_2; by params:

xhr.send(params);

Here is the final script:

var xhr = new XMLHttpRequest();
var params = "info="+str+"&info_1="+info_1+"&info_2="+info_2;
xhr.open("POST",url,true);
xhr.onreadystatechange = function() {
    if( this.readyState == 4 && this.status == 200) {
        document.getElementById(name).innerHTML = this.responseText;
    }
};
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(params);
return false;

Upvotes: 1

Related Questions