How can I send JSON data from Javascript in the browser, to a server and have PHP parse it there?
-
1json_decode might be what you're looking for? – Corbin Dec 22 '11 at 04:59
-
1this will help you: [send json data from javascript][1] [1]: http://stackoverflow.com/questions/1255948/post-data-in-json-format-with-javascript – jogesh_pi Dec 22 '11 at 04:59
-
This might help you http://stackoverflow.com/search?q=Send+JSON+data+from+Javascript+to+PHP – Arfeen Dec 22 '11 at 05:00
-
1Hey all, thanks for the answers. Actually, I have a complete solution as well. I wanted to post it to this site because I come here all the time for information and wanted to finally provide some information. But I just created my account, and it won't allow me to post the answer for 8 hours :( – kermit Dec 22 '11 at 05:08
11 Answers
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
-
5Another thing that can happen, and this applies to version 1, is that magic_quotes might be turned ON in your PHP.ini file. what happens is that instead of receiving a json of type {"name":"Penguin"} .. you may find .. {\"name\":\"Penguin\"} ... You can use the php function stripslashes() on your GET or POST data/globals in order to get rid of them and process your json correctly. – penguinsource Mar 31 '13 at 00:33
-
1Can I know what's the third parameter in the `request.setRequestHeader` is for? – Gowtham Jan 27 '14 at 13:07
-
2@Gowtham that's an error. Good catch. It should be in the open() function. I'm going to correct it now. Details here: http://www.w3.org/TR/2014/WD-XMLHttpRequest-20140130/ and here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest – kermit Feb 06 '14 at 05:36
-
1@kermit Can you please mention some security practices I should follow in the serverside? – Gowtham Feb 06 '14 at 13:02
-
2@Gowtham 1) Encrypt the connection with PKI; 2) Use PHP sessions along with a login mechanism (meaning force users to select a username and password stored in a table); 3) Know the difference between encryption (AES) and a one-way hash (MD5, SHA1); 4) Don't allows users to list files on the server; 5) Use a single point of entry file on the server, which calls another hidden file to do processing you want; 6) Don't allow remote root logins to server; 7) Learn iptables (soon nftables) - close down unneeded ports. 8) Use Fail2ban if you administer the server. – kermit Feb 06 '14 at 20:14
-
1You write "This reads the raw POST data". That is not fully correct. It reads the "body" of any request. Practically this could also be a PUT request. Technically it could even be any other request such as GET / DELETE / HEAD which all normally are meant to ignore the body. – OderWat May 27 '15 at 13:08
-
For `application/x-www-form-urlencoded`, wouldn't you need to URL-encode the string first? – Pyromonk Jan 25 '21 at 10:56
Javascript file using jQuery (cleaner but library overhead):
$.ajax({
type: 'POST',
url: 'process.php',
data: {json: JSON.stringify(json_data)},
dataType: 'json'
});
PHP file (process.php):
directions = json_decode($_POST['json']);
var_dump(directions);
Note that if you use callback functions in your javascript:
$.ajax({
type: 'POST',
url: 'process.php',
data: {json: JSON.stringify(json_data)},
dataType: 'json'
})
.done( function( data ) {
console.log('done');
console.log(data);
})
.fail( function( data ) {
console.log('fail');
console.log(data);
});
You must, in your PHP file, return a JSON object (in javascript formatting), in order to get a 'done/success' outcome in your Javascript code. At a minimum return/print:
print('{}');
See Ajax request return 200 OK but error event is fired instead of success
Although for anything a bit more serious you should be sending back a proper header explicitly with the appropriate response code.
-
4
-
1@Nate the question was how to do in JS but this answer is using jQuery also, so it's not pure JS ;) – Anatol Bivol Jun 13 '17 at 13:08
Simple example on JavaScript for HTML input-fields (sending to server JSON, parsing JSON in PHP and sending back to client) using AJAX:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<body>
<div align="center">
<label for="LName">Last Name</label>
<input type="text" class="form-control" name="LName" id="LName" maxlength="15"
placeholder="Last name"/>
</div>
<br/>
<div align="center">
<label for="Age">Age</label>
<input type="text" class="form-control" name="Age" id="Age" maxlength="3"
placeholder="Age"/>
</div>
<br/>
<div align="center">
<button type="submit" name="submit_show" id="submit_show" value="show" onclick="actionSend()">Show
</button>
</div>
<div id="result">
</div>
<script>
var xmlhttp;
function actionSend() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var values = $("input").map(function () {
return $(this).val();
}).get();
var myJsonString = JSON.stringify(values);
xmlhttp.onreadystatechange = respond;
xmlhttp.open("POST", "ajax-test.php", true);
xmlhttp.send(myJsonString);
}
function respond() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('result').innerHTML = xmlhttp.responseText;
}
}
</script>
</body>
</html>
PHP file ajax-test.php :
<?php
$str_json = file_get_contents('php://input'); //($_POST doesn't work here)
$response = json_decode($str_json, true); // decoding received JSON to array
$lName = $response[0];
$age = $response[1];
echo '
<div align="center">
<h5> Received data: </h5>
<table border="1" style="border-collapse: collapse;">
<tr> <th> First Name</th> <th> Age</th> </tr>
<tr>
<td> <center> '.$lName.'<center></td>
<td> <center> '.$age.'</center></td>
</tr>
</table></div>
';
?>

- 737
- 8
- 4
This is a summary of the main solutions with easy-to-reproduce code:
Method 1 (application/json or text/plain + JSON.stringify)
var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/json") // or "text/plain"
xhr.send(JSON.stringify(data));
PHP side, you can get the data with:
print_r(json_decode(file_get_contents('php://input'), true));
Method 2 (x-www-form-urlencoded + JSON.stringify)
var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("json=" + encodeURIComponent(JSON.stringify(data)));
Note: encodeURIComponent(...)
is needed for example if the JSON contains &
character.
PHP side, you can get the data with:
print_r(json_decode($_POST['json'], true));
Method 3 (x-www-form-urlencoded + URLSearchParams)
var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(new URLSearchParams(data).toString());
PHP side, you can get the data with:
print_r($_POST);

- 41,386
- 99
- 383
- 673
PHP has a built in function called json_decode(). Just pass the JSON string into this function and it will convert it to the PHP equivalent string, array or object.
In order to pass it as a string from Javascript, you can convert it to JSON using
JSON.stringify(object);
or a library such as Prototype

- 136
- 3
There are 3 relevant ways to send Data from client Side (HTML, Javascript, Vbscript ..etc) to Server Side (PHP, ASP, JSP ...etc)
1. HTML form Posting Request (GET or POST).
2. AJAX (This also comes under GET and POST)
3. Cookie
HTML form Posting Request (GET or POST)
This is most commonly used method, and we can send more Data through this method
AJAX
This is Asynchronous method and this has to work with secure way, here also we can send more Data.
Cookie
This is nice way to use small amount of insensitive data. this is the best way to work with bit of data.
In your case You can prefer HTML form post or AJAX. But before sending to server validate your json by yourself or use link like http://jsonlint.com/
If you have Json Object convert it into String using JSON.stringify(object), If you have JSON string send it as it is.

- 5,444
- 7
- 23
- 36
-
1
-
1It is helpful, thanks. I originally posted my question with the intention of answering it instantly, originally. However, to prevent spamming and bogus accounts, the stackoverflow first-post and self-answer mechanisms are making me wait for a while. I've gotten a lot of information here and wanted to provide some information back to readers. Your answer will definitely provide information to readers. – kermit Dec 23 '11 at 05:52
-
1@kermit thanks for reply, mark any one of answer as accept, you can mark your own answer also. – Robin Michael Poothurai Dec 23 '11 at 07:11
using JSON.stringify(yourObj) or Object.toJSON(yourObj) last one is for using prototype.js, then send it using whatever you want, ajax or submit, and you use, as suggested, json_decode ( http://www.php.net/manual/en/function.json-decode.php ) to parse it in php. And then you can use it as an array.

- 2,600
- 1
- 15
- 36
<html>
<script type="text/javascript">
var myJSONObject = {"bindings": 11};
alert(myJSONObject);
var stringJson =JSON.stringify(myJSONObject);
alert(stringJson);
</script>
</html>

- 2,440
- 4
- 21
- 28
You can easily convert object into urlencoded string:
function objToUrlEncode(obj, keys) {
let str = "";
keys = keys || [];
for (let key in obj) {
keys.push(key);
if (typeof (obj[key]) === 'object') {
str += objToUrlEncode(obj[key], keys);
} else {
for (let i in keys) {
if (i == 0) str += keys[0];
else str += `[${keys[i]}]`
}
str += `=${obj[key]}&`;
keys.pop();
}
}
return str;
}
console.log(objToUrlEncode({ key: 'value', obj: { obj_key: 'obj_value' } }));
// key=value&obj[obj_key]=obj_value&

- 17
- 6
I found easy way to do but I know it not perfect
1.assign json to
if you JSON is
var data = [
{key:1,n: "Eve"}
,{key:2,n:"Mom"}
];
in ---main.php ----
<form action="second.php" method="get" >
<input name="data" type="text" id="data" style="display:none" >
<input id="submit" type="submit" style="display:none" >
</form>
<script>
var data = [
{key:1,n: "Eve"}
,{key:2,n:"Mom"} ];
function setInput(data){
var input = document.getElementById('data');
input.value = JSON.stringify(data);
var submit =document.getElementById('submit');
//to submit and goto second page
submit.click();
}
//call function
setInput(data);
</script>
in ------ second.php -----
<script>
printJson();
function printJson(){
var data = getUrlVars()["data"];
//decode uri to normal character
data = decodeURI(data);
//for special character , / ? : @ & = + $ #
data = decodeURIComponent(data);
//remove " ' " at first and last in string before parse string to JSON
data = data.slice(1,-1);
data = JSON.parse(data);
alert(JSON.stringify(data));
}
//read get variable form url
//credit http://papermashup.com/read-url-get-variables-withjavascript/
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>

- 3
- 2