JS: Processing form as a POST but retrieving as a GET? - javascript

Retrieving the data with PHP, I cannot use $_POST; but $_GET. Why? Am I sending my form data incorrectly?
I'd have thought request.open("POST" would process the form as a POST and not GET? How may I sent it as a POST?
var request = new XMLHttpRequest();
request.open("POST","email.php?text=" + textarea.value + "&email=" + email.value, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var resp = request.responseText;
console.log(resp);
}
};
request.send();

Because you're adding data inside the URL.
Change your request to:
request.open("POST","email.php", true);
request.setRequestHeader("Content-length", 2); // 2 here is the no. of params to send
....
request.send("text=" + textarea.value + "&email=" + email.value);
Docs: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

The reason is you are sending the variables in the url that is why you are getting in get. See this example post
var http = new XMLHttpRequest();
var url = "get_data.php";
var params = "lorem=ipsum&name=binny"; // all prams variable here
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);

Related

my set request header is not working it is not setting parameters to my url on running the function

I m trying to make a post request to the server by clicking a button
FYI this code is in HTML file
<button onclick="vf()" >click</button>
<!---script---->
<script>
function vf(){
var http = new XMLHttpRequest();
///aServe= anyserver
var url = 'aServer';
var myName = 'name=me';
http.open('POST', url, true);
///setting header
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseURL);
}
}
http.send(myName);
};
</script>

Not able to echo POST paramenters sent in ajax, inside PHP

I am sending two parameters inside the send method to index.php. But the PHP returns an error "Undefined index". echo $_POST['fname'];
submit.addEventListener("click", function(e){
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open("POST", "index.php", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log(result);
}
}
xhr.send("fname=Henry&lname=Ford");
});
In order to send form data through Ajax, you have to specify the content type of the request. In you case it will be 'application/x-www-form-urlencoded:
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
So your code will be:
submit.addEventListener("click", function(e){
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open("POST", "index.php", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log(result);
}
}
xhr.send("fname=Henry&lname=Ford");
});

Add header to http request

My first post here.
I'm using droidscript and I have to include an header that contains a specific user and a password in order to retrieve a token. I'm having trouble because I don't know where to include those headers.
That's the code I'm using:
function btn_OnTouch(){
var url = "myurl";
SendRequest(url);
}
//Send an http get request.
function SendRequest(url){
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
HandleReply(httpRequest);
};
httpRequest.open("GET", url, true);
httpRequest.send(null);
app.ShowProgress("Loading...");
}
//Handle the servers reply (a json object).
function HandleReply(httpRequest){
if (httpRequest.readyState == 4){
//If we got a valid response.
if (httpRequest.status == 200){
txt.SetText("Response: " + httpRequest.status + httpRequest.responseText);
}
//An error occurred
else
txt.SetText("Error: " + httpRequest.status + httpRequest.responseText);
}
app.HideProgress();
}
The told me I should probably include the headers like this, but I don't know where to put them in my code.
httpRequest.setRequestHeader(“username”, “myuser”);
httpRequest.setRequestHeader(“password”, “mypass”);
You need to do it just after calling the open method like this:-
httpRequest.open("GET", url, true);
httpRequest.setRequestHeader("username", "myuser");
httpRequest.setRequestHeader("password", "mypass");
httpRequest.send(null);

How to display POST values which are coming from javascript XMLHttpRequest() in php

I am sending parameters using XMLHttpRequest() javascript function to another php page in Json formate, but $_POST['appoverGUID'] not getting post values.
Here is my Javascript code.
function loadPage(href){
var http = new XMLHttpRequest();
var url = json.php;
var approverGUID = "Test";
var params = JSON.stringify({ appoverGUID: approverGUID });
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/json; charset=utf-8");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById('bottom').innerHTML = http.responseText;
}
}
http.send(params);
}
And here is my json.php file code.
if(isset($_POST['appoverGUID'])){
echo $_POST['appoverGUID'];
}
First of all remove these headers since they will be send automatically by the browser and it's the right way to do it.
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
This code is a cross browser solution and it's tested.
// IE 5.5+ and every other browser
var xhr = new(window.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
var params = "appoverGUID="+approverGUID;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.setRequestHeader("Accept", "application/json");
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
console.log(JSON.parse(this.responseText));
}
}
}
xhr.send(params);
xhr = null;
You need use json_decode. Some like this:
if ("application/json" === getallheaders())
$_JSON = json_decode(file_get_contents("php://input"), true) ?: [];
Fill params this way (did no escaping/encoding of approverGUID content, here..):
params = "appoverGUID="+approverGUID;
Also see:
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

(AJAX/PHP) Why is my POST request not working in this brief example?

Here is my JavaScript:
var xhr = new XMLHttpRequest();
xhr.open("POST", "pants.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var slot = document.getElementsByTagName("section")[0].innerHTML = xhr.responseText;
}
}
xhr.send("name=Sarah");
I am sending "name=Sarah" to testpage.php via POST, and when I get a response, I'm doing to display it on my page.
And here's pants.php:
echo $_POST['name'];
So I should just be displaying "Sarah" on the page. But instead, I get the error ": Undefined index: name". I can't seem to understand why this is...
You should add the following:
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
This header is mandatory for POST requests

Categories

Resources