Send Json Data from JavaScript to PHP

Send JSON data from Javascript to PHP?

I've gotten lots of information here so I wanted to post a solution I discovered.

The problem: Getting JSON data from Javascript on the browser, to the server, and having PHP successfully parse it.

Environment: Javascript in a browser (Firefox) on Windows. LAMP server as remote server: PHP 5.3.2 on Ubuntu.

What works (version 1):

1) JSON is just text. Text in a certain format, but just a text string.


2) In Javascript, var str_json = JSON.stringify(myObject) gives me the JSON string.


3) I use the AJAX XMLHttpRequest object in Javascript to send data to the server:

request= new XMLHttpRequest()
request.open("POST", "JSON_Handler.php", true)
request.setRequestHeader("Content-type", "application/json")
request.send(str_json)
[... code to display response ...]

4) On the server, PHP code to read the JSON string:

$str_json = file_get_contents('php://input');

This reads the raw POST data. $str_json now contains the exact JSON string from the browser.

What works (version 2):

1) If I want to use the "application/x-www-form-urlencoded" request header, I need to create a standard POST string of "x=y&a=b[etc]" so that when PHP gets it, it can put it in the $_POST associative array. So, in Javascript in the browser:

var str_json = "json_string=" + (JSON.stringify(myObject))

PHP will now be able to populate the $_POST array when I send str_json via AJAX/XMLHttpRequest as in version 1 above.

Displaying the contents of $_POST['json_string'] will display the JSON string. Using json_decode() on the $_POST array element with the json string will correctly decode that data and put it in an array/object.

The pitfall I ran into:

Initially, I tried to send the JSON string with the header of application/x-www-form-urlencoded and then tried to immediately read it out of the $_POST array in PHP. The $_POST array was always empty. That's because it is expecting data of the form yval=xval&[rinse_and_repeat]. It found no such data, only the JSON string, and it simply threw it away. I examined the request headers, and the POST data was being sent correctly.


Similarly, if I use the application/json header, I again cannot access the sent data via the $_POST array. If you want to use the application/json content-type header, then you must access the raw POST data in PHP, via php://input, not with $_POST.

References:

1) How to access POST data in PHP: How to access POST data in PHP?

2) Details on the application/json type, with some sample objects which can be converted to JSON strings and sent to the server: http://www.ietf.org/rfc/rfc4627.txt

send json object from javascript to php

Excellent answer by Phil, however since the OP title says

send json object from javascript (not jQuery ) to php

this is how to do it with (vanilla) javascript, in case it helps somebody looking for this method:

var jsondata;
var flickr = {'action': 'Flickr', 'get':'getPublicPhotos'};
var data = JSON.stringify(flickr);

var xhr = new XMLHttpRequest();
xhr.open("POST", "../phpincl/apiConnect.php", !0);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(data);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// in case we reply back from server
jsondata = JSON.parse(xhr.responseText);
console.log(jsondata);
}
}

Notice we still need to convert the server's response into a javascript object using JSON.parse()

Now, on the server side (based on Phil's answer) if you are sending back a response to the client, you could do:

header('Content-type: application/json');
$json = file_get_contents('php://input');
$json_decode = json_decode($json, true);
$json_encode = json_encode($json_decode);
echo $json_encode;

NOTE:

The reason behind decoding first and then encoding back the raw json input is to properly escape slashes in (possible) URLs within the data, e.g.

json_encode will convert this URL

http://example.com

into

http:\/\/example.com

... which is not the case in the OP but useful in some other scenarios.

How to post JSON from javascript to 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"];

Sending JSON object from PHP to Javascript

Now that the form is added, it is clear what the problem is: You make an ajax call on page load, without any parameters, and when you make a change to your select, you submit the form the old-fashioned way, without using ajax. This causes a page reload where your ajax call is fired again, again without any parameters.

What you need to do is:

  1. Load your form but without the onhange handler;
  2. Do not fire the ajax call on page load;
  3. Instead, add an event handler for when the select is changed, set the correct data type and send the data you need to send.

The end result would look something like:

<form action="">
<select name="param1">
<option value="">Choose a zipcode </option>
<option value="92507">92507</option>
<option value="30078">30078</option>
<option value="92606">92606</option>
<option value="30004">30004</option>
<option value="32034">32034</option>
<option value="37160">37160</option>
</select>
</form>
<script>
$(document).ready(function() {
$('select').on('change', function(event) {
// Make sure the form does not get submitted the old-fashioned way
event.preventDefault();

// Your ajax call, including the parameter, data type and method
$.ajax({
type: "GET", // GET to match your php script
url: "page.php",
dataType: 'json', // Let jQuery parse the results
data: $('form').serialize(), // Send you data
success: function (obj) {
console.log(obj); // this will be an object for valid json
document.getElementById("demo").innerHTML = "UV INDEX" + "<br>" + "Zip code: " + obj[0].ZIP_CODE + "<br>";
}
});
});
});
</script>

How do I use jQuery.post to send JSON data to a php script?

Using jQuery you can send data to your end point using the POST protocol. Example below

$.ajax({
url : 'taskmanager.php',
type : 'POST',
data : JSON.stringify(dataStore),
success : function(res) {
// Successfully sent data.
console.log(res);
},
error: function(err) {
// Unable to send data.
console.log(err);
})
});

You may also use the $.post method, its just a preference. $.ajax provides with some extra flexibility, in case you maybe want to update your protocol to GET instead of post or numerous other instances...

More info on this here: http://forum.jquery.com/topic/what-should-i-use-post-vs-ajax

How to capture json data on php that is sent with ajax (no jquery)

To get an array, add the true argument to json_decode().
In your code:

$body = json_decode(file_get_contents("php://input"), true);
var_export($body);

To add the JSON data in $_POST, you can use this code.

In JS:

json = JSON.stringify(data);
var ajax = new XMLHttpRequest(), url = '../handler.php';
ajax.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
};
};
ajax.open('POST', url, true);
ajax.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
ajax.send('jsn='+json);

In PHP:

$arr = isset($_POST['jsn']) ? json_decode($_POST['jsn'], true) :[];
var_export($arr);

Source: https://coursesweb.net/ajax/json-from-javascript-php



Related Topics



Leave a reply



Submit