Assuming your server supports PHP, you could also use a PHP Session.
http://www.php.net/manual/en/reserved.variables.session.php
Answer from BassT on Stack OverflowVideos
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
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.
If this is your real server side code then...its completely insecure. You should never pass variables posted by users directly into your queries.
$query2 = "insert into booking(cust_email, cust_mobile, cust_name) values('$mail','$mobile','$name')";
At least escape the values using "mysql_real_escape_string", or use prepared statements. And...dont use mysql anymore, use mysqli, which is almost identical to what you are using, but not deprecated soon.
Also, you are json encoding a string that doesnt need to be json encoded, its just a piece of text and not valid json code. This may be why @SimarjeetSingh Panghlia answer doesnt work for you.
instead of json_encoding that value, encode a structured array.
$response = array( "status" => true );
if(isset($_POST['type']))
{
if($_POST['type']=="booking"){
$name = mysql_real_escape_string( $_POST ['Name'] ));
$mobile = mysql_real_escape_string($_POST ['Mob_Num']);
$mail = mysql_real_escape_string($_POST ['Email']);
$query1 = "insert into customer(userName, userContactNumber, email) values('$name','$mobile','$mail')";
$query2 = "insert into booking(cust_email, cust_mobile, cust_name) values('$mail','$mobile','$name')";
$result1 = mysql_query($query1);
$result2 = mysql_query($query2);
$id = mysql_insert_id();
$response["message"] = "Welcome Mr/Mrs ".$name." Thanks for booking home services your booking id is = ".$id;/* make sure you strip tags etc to prevent xss attack */
}
}
else{
$response["status"] = false;
$response["message"] = "Invalid format";
}
echo json_encode($response);
/* Note that you are making the query using ContentType:"application/json", */
which means you should respond using json regardless if query is successful or not. I would also recommend using a simple jQuery plugin called jStorage, that allows easy get/set of objects without having to serialize them.
You can use sessionStorage to store and retrieve JSON Data.
var complexdata = [1, 2, 3, 4, 5, 6];
// store array data to the session storage
sessionStorage.setItem("list_data_key", JSON.stringify(complexdata));
//Use JSON to retrieve the stored data and convert it
var storedData = sessionStorage.getItem("complexdata");
if (storedData) {
complexdata = JSON.parse(storedData);
}
To remove sessionStorage Datas after using use sessionStorage.clear();
$login = $json['registration']['first_name']
What you have shown is not JSON, but PHP's array. I am assuming this is the structure of the data you want to be sent to the server.
You can do it like that (remember, there are no associative arrays in JavaScript!):
on Javascript side do something similar to this:
var data = { 'registration': { 'first_name': 'test', 'location': { 'name': 'Santa Ana', 'id': '1.08081209215E+14' }, 'gender': 'female', 'password': 123654789 } }and then use
datain eg. jQuery .post() as the second parameter.on the PHP side just read from
$_POSTas you read multi-dimensional associative arrays. In this case it should look similar to:// I have made assumption here (you do not have // 'login' variable in your example) $login = $_POST['registration']['first_name']; $pass = $_POST['registration']['password']; $gender = $_POST['registration']['gender']; $name = $_POST['registration']['first_name']; $carray = fns_create_talent($login, $pass, $gender, $name);
Here you go.
You have a couple of different ways to accomplish this:
- You should be able to first set the actual
idand then include theGet_Users.phpfile like this. Notice that you should not echo out the output fromGet_Users.php, instead only return the encoded json data usingreturn json_encode($arr);:
// set the id in $_GET super global
$_GET['id'] = 1;
// include the file and catch the response
$result = include_once('Get_Users.php');
- You can also create a function that can be called from
UserView.php:
// Get_Users.php
<?php
function get_user($id) {
// connect to and query database here
// then return the result as json
return json_encode($arr);
}
?>
// In UserView.php you first include the above file and call the function
include_once('Get_Users.php');
$result = get_user(1);
- You could also use
file_get_contents(). Notice that you need to make sure so thatallow_url_fopenis enabled in yourphp.inifile for this to work:
$result = file_get_contents('http://example.com/Get_Users.php?id=1');
To enable allow_url_fopen you need to open up your loaded configuration file and set allow_url_fopen=1 and finally restart your webserver.
- You could also use curl to achieve the same result:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, 'http://example.com/Get_Users.php?id=1');
$result = curl_exec($ch);
curl_close($ch);
- An ajax request could also be made to get the result. This example uses jQuery:
$(document).ready(function() {
$.get({
url: 'Get_Users.php',
data: 'id=1',
success: function(response) {
// response contains your json encoded data
// in this case you **must** use echo to transfer the data from `Get_Users.php`
}
});
});
Change UsersView.php to like this
$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['CONTEXT_PREFIX'];
$url = "get_users.php?id=" . $id;
$url = $actual_link.$url;
$json = file_get_contents($url);
$result = json_decode($json, true);
This will work fine.
I did this not too long ago in PHP. Here's an example of "passing the request". (You'll need to enable PHP cURL, which is pretty standard with most installations.)
<?php
//Get the JSON data POSTed to the page
$request = file_get_contents('php://input');
//Send the JSON data to the right server
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://location_of_server.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8"));
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$data = curl_exec($ch);
curl_close($ch);
//Send the response back to the Javascript code
echo $data;
?>
One way to bypass the Same-Origin policy is to use cURL to do the actual transmitting.
I'll give an example using PHP, but you could easily do this on any server side language.
Set up a script on your server, for example send.php
First you point your ajax to send.php
var json = JSON.stringify(object);
$.ajax({
type: 'POST',
url: send.php,
data: json,
dataType: 'json',
success: function(data){console.log(data);},
failure: function(errMsg) {
console.log(errMsg);
},
});
Then your php script to forward it:
<?php
// Initialize curl
$curl = curl_init();
// Configure curl options
$opts = array(
CURLOPT_URL => $externalscriptaddress,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => 'field1=arg1&field2=arg2'
);
// Set curl options
curl_setopt_array($curl, $opts);
// Get the results
$result = curl_exec($curl);
// Close resource
curl_close($curl);
echo $result;
?>
Can you not just require page2.php?
What I mean is:
page3.php -> AJAX request to page1.php
page1.php -> $request = json_decode(AJAX request from page3.php)
require page2.php
page2.php -> process $request
populate $response
page1.php -> echo json_encode($response)
page3.php -> AJAX response from page1.php
on page2.php write echo json_enode($return_data)
and retrieve on page3.php by json_decode($output,true); and store into $_SESSION variable and
on page3.php retrieve data by $_SESSION['']
Reference:
json_encode
json_decode