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 Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 55006320 › how-to-pass-json-array-of-one-page-into-another-in-php
How to pass json array of one page into another in php?
March 5, 2019 - <?php session_start(); $_SESSION['json'] = isset($_POST['json']) ? $_POST['json'] : null; // other php stuffs ?> <!-- other html stuffs --> <script> var json = { your: 'json' }; (function(){ var xhr = new XMLHttpRequest(); var data = encodeURIComponent(JSON.stringify(json)); xhr.open('post', 'p1.php'); xhr.send('json='+data); })(); </script> These code send the info (json) via AJAX to p1.php ... Same as the other answer, Ajax is unnecessary here - the aim is to navigate to the second page as well, not just send the data 2019-03-05T16:28:31.407Z+00:00
🌐
Stack Overflow
stackoverflow.com › questions › 23550254 › taking-json-information-in-another-page-on-javascript
php - Taking JSON information in another page on Javascript - Stack Overflow
December 8, 2011 - $(document).ready(function(){ //start ajax request $.ajax({ url: "test.php", //force to handle it as text dataType: "text", success: function(data) { //data downloaded so we call parseJSON function //and pass downloaded data var jsonData = $.parseJSON(data); //now json variable contains data in json format alert(jsonData.firstName);//access first array alert(jsonData.series[0]);//access second array elements } }); });
🌐
Stack Overflow
stackoverflow.com › questions › 43358028 › how-can-i-access-json-data-from-another-url-inside-a-html-page
php - how can I access json data from another url inside a html page - Stack Overflow
<script> $.ajax({ // name of file to call url: 'fetch_latlon.php', // method used to call server-side code, this could be GET or POST type: 'GET' // Optional - parameters to pass to server-side code data: { key1: 'value1', key2: 'value2', key3: 'value3' }, // return type of response from server-side code dataType: "json" // executes when AJAX call succeeds success: function(data) { // fetch lat/lon var lat = data.lat; var lon = data.lon; // show lat/lon in HTML $('#lat').text(lat); $('#lon').text(lon); }, // executes when AJAX call fails error: function() { // TODO: do error handling here console.log('An error has occurred while fetching lat/lon.'); } }); </script>
🌐
Code Boxx
code-boxx.com › home › javascript send json data to php (simple examples)
Javascript Send JSON Data To PHP (Simple Examples)
October 18, 2023 - Once again, $_POST["data"] $_GET["data"] is just a JSON-encoded string. We can do a json_decode() in PHP to get the object/array.
🌐
Stack Overflow
stackoverflow.com › questions › 43587968 › send-json-data-from-one-page-and-receive-dynamically-from-another-page-using-aja
Send JSON data from one page and receive dynamically from another page using AJAX when both page are open
June 8, 2017 - I am trying to send JSON data from page1 on submit button click and try to receive this data dynamically from page2 using AJAX and print the data in console. I don't know the proper syntax to do this. One suggested code which is not appropriate. The code is given: ... <?php if(isset($_POST["submit"])){ $x = "ok"; echo json_encode($x); } ?> <!DOCTYPE html> <html> <head> <title>page1</title> </head> <body> <p>This is page is sending json data on submit button press</p> <form method="post"> <input type="submit" name="submit"> </form> </body> </html>
Top answer
1 of 11
69

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

2 of 11
17

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.

Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 61738419 › php-how-to-share-json-data-between-files
PHP - How to share JSON data between files - Stack Overflow
I changed it to this $json = file_get_contents("index.php"); $data = json_decode($json); echo $data[0]; and I still get a blank page ... You're passing true into json_decode which makes it an associative array, not an object.
Top answer
1 of 3
1

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.

2 of 3
0

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();

🌐
Appsloveworld
appsloveworld.com › php › 1349 › redirecting-post-json-data-to-another-page-to-display
Redirecting POST JSON data to another page to display
Passing POST data from one web page to another with PHP · Get JSON data from ajax call to PHP page through POST · How to store the values of listbox into an array then use it to display its data into another page php · Post Form DATA to another page after PHP Validation ·
Top answer
1 of 2
4

You have a couple of different ways to accomplish this:

  • You should be able to first set the actual id and then include the Get_Users.php file like this. Notice that you should not echo out the output from Get_Users.php, instead only return the encoded json data using return 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 that allow_url_fopen is enabled in your php.ini file 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`
    }
  });
});
2 of 2
1

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.

🌐
CodexWorld
codexworld.com › home › how to post and receive json data using php curl
How to POST and Receive JSON Data using PHP cURL - CodexWorld
August 6, 2021 - Specify the URL ($url) where the JSON data to be sent. Initiate new cURL resource using curl_init(). Setup data in PHP array and encode into a JSON string using json_encode().
Top answer
1 of 2
3

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;
?>
2 of 2
2

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;
?>
🌐
YouTube
youtube.com › codecourse
Working with JSON and PHP - YouTube
Want more? Explore the library at https://www.codecourse.com/lessonsOfficial sitehttps://www.codecourse.comTwitterhttps://twitter.com/teamcodecourse
Published   May 30, 2011
Views   157K
🌐
Stack Overflow
stackoverflow.com › questions › 44106251 › pass-json-object-from-php-to-php › 44106365
Pass JSON object from php to php - Stack Overflow
May 22, 2017 - How can I pass a JSON object from one php to another. I need to POST the JSON object, so that the second file can access it using ... <?php //set POST variables $url = 'sample2.php'; $fields = array( 'json' => urlencode($json/*your json that want to pass*/), ); //url-ify the data for the POST foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; } rtrim($fields_string, '&'); //open connection $ch = curl_init(); //set the url, number of POST vars, POST data curl_setopt($ch,CURLOPT_URL, $url); curl_setopt($ch,CURLOPT_POST, count($fields)); curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string); //execute post $result = curl_exec($ch); //close connection curl_close($ch); ?>