How to post JSON from javascript to php [duplicate] - javascript

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"];

Related

Submit FORM data then return response [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have the following code which sends post data to my form and alerts the expected result, however I'm finding it hard to save this as a variable I can use outside the function, can anyone offer any help?
<script>
var http = new XMLHttpRequest();
var url = "form.php";
var params = "name=test";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.(params);
</script>
Just declare a variable and set it when the request responsed by server;
var http = new XMLHttpRequest();
var url = "form.php";
var params = "name=test";
var response;
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
response = http.responseText;
}
}
http.(params);

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 !

XMLHTTPrequest sending empty post

I've done a lot of times before, so I'm honestly confused why this is failing to pass anything. I've tried printing results (script gets a response and prints the file).
function submit_form_inpage(path, data, watchForChange){
alert(data);
watchForChange = watchForChange || false;
var request = new XMLHttpRequest();
request.open('POST', path, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
if (watchForChange == true) {
request.onreadystatechange = function () {
if (request.readyState == 4) {
document.write(request);
if (request.status==200 && request.status < 400){
var xmldata=request.responseText //retrieve result as an XML object
alert("XML:" + xmldata);
}
else{
alert("An error has occured making the request:" + request.status );
}
}
}
}
var temp_string = array_to_string_for_post(data);
var temp = JSON.stringify(data);
alert(temp);
request.send(temp);
}
My php is
print_r($_POST);
and my result is
XML: Array ()
Despite the fact that data passed in (which is double-checked right before being sent by my alert) is
{"reason":"get_stuff","build_name":"test"}
You said you were sending form encoded data.
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
Then you sent:
temp = JSON.stringify(data);
JSON is application/json not application/x-www-form-urlencoded (and isn't natively supported by PHP anyway).
Either encode your data as application/x-www-form-urlencoded or correct your content-type and parse it manually in PHP.

How to get array from ajax call in javascript

My ajax call looks like this:
request = new XMLHttpRequest();
request.open("GET","/showChamps?textInput=" + searchChamp.value,true);
request.send(null);
request.onreadystatechange = function () {
if (request.status == 200 && request.readyState == 4) {
//how do i get my array
}
};
}
I have sent an array from my node.js server but I don't know how to get that array because request.responseText does not give me back an array. Also it would be appreciated if the answer is in javascript.
Thanks in Advance!
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if(xhr.status === 200) {
var responseHTML = xhr.responseText, // HTML
responseXML = xhr.responseXML, // XML
responseObject = JSON.parse(xhr.responseText); // JSON
}
};

xhr.responseText returned null with POST

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

Categories

Resources