xhr.responseText returned null with POST - javascript

Here is how my js look like
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myajaxurl.com/lyric", true);
var data = "lyric";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log(xhr.responseText);
}
}
xhr.send(data);
and my simple php
<?php
if( isset($_POST['lyric']) )
{ ?>
<?php echo "test"; ?>
//it take sometime for my php to work and return the result, i do data scraping here
<?php } ?>
I expect to see 'test' in console.log but I didn't, the ajax need send. why??

PHP doesn't seem to be able to decode a single parameter with no value when doing a post request. A simple solution would be to explicitly add = after the parameter name:
var data = "lyric=";
Example:
// index.php
print_r($_POST);
// command line
// parameter name, not value
$ curl --data "lyric" http://localhost:8888/index.php
Array
(
)
// parameter name with empty value
$ curl --data "lyric=" http://localhost:8888/index.php
Array
(
[lyric] =>
)
Compare to GET instead (with print_r($_GET)):
$ curl http://localhost:8888/index.php?foo
Array
(
[foo] =>
)

You were trying to access the data incorrectly. You need to pass the parameters just like you would do if you were making a GET request. So in the below code, the data variable can be accessed through the $_POST array, which stores the data you want.
JAVASCRIPT
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myajaxurl.com/lyric", true);
var data1 = "data=lyric";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log(xhr.responseText);
}
}
xhr.send(data1);
PHP
<?php
if( isset($_POST['data']) )
{
echo "test";
}
?>
EDIT
The header issue can be solved like this
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myajaxurl.com/lyric", true);
var data1 = "data=lyric";
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", data1.length);
http.setRequestHeader("Connection", "close");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log(xhr.responseText);
}
}
xhr.send(data1);
source:http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

Related

I want to receive a JSON (sendend by POST method of JS xmlHttpRequest()) echo from PHP

The code JS is
var xhr = new XMLHttpRequest()
//console.log(xhr)
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
console.log(xhr)
}
}
xhr.open("POST","https://testepr.harpiastudios.com.br/http-receiver.php")
xhr.setRequestHeader('Content-Type', 'application/json')
function sendText(text){
let dataToSend = {
"text": text
}
console.log(dataToSend)
xhr.send(dataToSend)
}
and the PHP Code is:
$dataToSend = json_decode(file_get_contents('php://input'));
echo($dataToSend->text);
The php file returns
Notice: Trying to get property of non-object in
I need to echo this value cause i need to use for other things. I dont know to have acces from this index of JSON

Unable to send JSON object to XMLHttpRequest

I am unable to send JSON object to XMLHttpRequest(). However, if I send string data through send(), it works. For example, the following code works:
var xhr = new XMLHttpRequest();
var url = 'https://xyz.info/api/contacts';
xhr.open("POST", url,true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
// Request finished. Do processing here.
}
}
xhr.send("apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456");
However, if I try to send data using JSON, it posts nothing to the url. The following code does not work.
var xhr = new XMLHttpRequest();
var url = 'https://xyz.info/api/contacts';
xhr.open("POST", url,true);
//xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
// Request finished. Do processing here.
}
}
xhr.send(JSON.stringify({
'apikey' :'ee6915d4ee4b4df66bba82277e3',
'firstname' : 'Kumar',
'lastname' : 'Sunder',
'phone':'5557773334'
}));
You're sending very different information in your two calls. Some sample code:
var _stringify = JSON.stringify({
'apikey' :'ee6915d4ee4b4df66bba82277e3',
'firstname' : 'Kumar',
'lastname' : 'Sunder',
'phone':'5557773334'
});
console.log(_stringify);
var _orig = "apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456"
var _encoded = encodeURI(_stringify);
console.log(_orig);
console.log(_encoded);
when your original string is printed to the console log, it looks as you would expect:
apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456
when the result of JSON.stringify is printed to the console, it returns:
{"apikey":"ee6915d4ee4b4df66bba82277e3","firstname":"Kumar","lastname":"Sunder","phone":"5557773334"}
That is, it comes complete with lots of extra double quote marks and left and right brackets. If you want to send all of that as a string (as in your initial example), you would need to URI encode the result of the JSON.stringify call. This is what happens with the "_encoded" variable, which contains:
%7B%22apikey%22:%22ee6915d4ee4b4df66bba82277e3%22,%22firstname%22:%22Kumar%22,%22lastname%22:%22Sunder%22,%22phone%22:%225557773334%22%7D
You are sending via a POST action, but then sending the data via a url string. If you want to send it that way you need to set it to GET.

How to post JSON from javascript to php [duplicate]

This question already has answers here:
send json object from javascript to php
(3 answers)
Closed 6 years ago.
I encoded an array into JSON in javascript:
var data = JSON.stringify(cVal);
And here is my ajaxrequest object:
function ajaxRequest(url, method, data, asynch, responseHandler){
var request = new XMLHttpRequest();
request.open(method, url, asynch);
if (method == "POST")
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.onreadystatechange = function(){
if (request.readyState == 4) {
if (request.status == 200) {
responseHandler(request.responseText);
}
}
};
request.send(data);
}
and I send the json to php with this ajaxrequset:
ajaxRequest("setOrder.php","POST", data , true , dosetOrder);
in php side:
$array=$_POST['data'];
but system says that the data in a undefined index in php
Create an object and stringify to json
var data = {};
data["username"] = username;
data["password"] = password;
var jsonData = JSON.stringify(data);
Send it to your endpoint
function ajaxRequest(url, method, data, asynch, responseHandler){
var request = new XMLHttpRequest();
request.open(method, url, asynch);
if (method == "POST")
request.setRequestHeader("Content-Type","application/json");
request.onreadystatechange = function(){
if (request.readyState == 4) {
if (request.status == 200) {
responseHandler(request.responseText);
}
}
request.send(data);
}
decode it at your endpoint
plain PHP
$body = json_decode(file_get_contents("php://input"), true);
echo $body["username"];
Slim Framework PHP
//example with Slim PHP framework
$body = json_decode($app->request->getBody(), true);
echo $body["username"];

Can't reach json data from AJAX POST call

Hi I am trying to create AJAX call via POST method with JSON. I do not want to use jQuery. Here's my javascript code:
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "index.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{
console.log(xhttp.responseText);
}
}
var data = "POSTdata=" + JSON.stringify({ data1 : 9, data2 : 4, data3 : 87});
xhttp.send(data);
And here's my PHP code:
if(isset($_POST['POSTdata']))
{
$version = json_decode($_POST['POSTdata']);
print_r($version);
}
else
{
echo "failure";
}
The print_r output is something like that:
stdClass Object
(
[data1] => 9
[data2] => 4
[data3] => 87
)
So simply i just don't know how to "reach" that data to use it. Could anyone help me?

How to send JSON response from python server to the javascript using ajax call

elif self.path == "/recQuery":
r = requests.get('http://example.com') # This returns some json from a request to another server.
print r.json()
self.wfile.write(r.json())
.
var http = new XMLHttpRequest();
var url = SERVER + "/recQuery";
var params = JSON.stringify({
query: search_query
});
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
console.log(http.responseText);
How can i send data from python server to javascript using ajax call. The one i am using does not return anything in the console. Can you please tell me what i am doing wrong here. I need send the response of what i get from requests.get method to the ajax call. The json should be returned to the ajax call in response. Problem is with the self.wfile.write method, When i use this i dont get anything on javascript side.
var http = new XMLHttpRequest();
var url = SERVER + "/recQuery";
var params = JSON.stringify({
query: search_query
});
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
};
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
I was not fetching the response onreadystatechange. So this works for me. Thanks !

Categories

Resources