简体   繁体   中英

How to pass json data from one html page to other html page using javascript?

I have to pass Json data which is generated after inserting the info into datbase table, Now I have to pass this info to other page BookingConformation.html .

For example we will get the form server Welcome Mr/Mrs Mittel Thanks for booking home services your booking id is 1. So please tell me how to pass info which is get form server in javascript now I have to pass this info to other page, please help me on this.

script

<script>
    $(document).ready(function(){
        $("#register-form").validate({
            rules: {
                userName: "required",                           
                email: {
                    required: true,
                    email: true
                },                                              
                userContactNumber: "required"                       
            },
            messages: {
                userName: "Please enter your Name",
                userContactNumber: "Please enter your Mobile number",                           
                email: "Please enter a valid email address",                                           
            },
            submitHandler: function(form) {

                var uName = $('#userName').val();   
                var mailId = $('#email').val();                 
                var mobNum = $('#userContactNumber').val();

                $.ajax({                
                    url:"http://localhost/bookRoom/book.php",
                    type:"POST",
                    dataType:"json",
                    data:{type:"booking", Name:uName, Email:mailId,  Mob_Num:mobNum},                                   
                    ContentType:"application/json",
                    success: function(response){
                    //alert(JSON.stringify(response));
                    //alert("success");                     
                    alert(response);
                    var globalarray = [];
                    globalarray.push(response);
                    window.localStorage.setItem("globalarray", JSON.stringify(globalarray));
                    window.location.href = 'BookingConformation.html';
                },
                    error: function(err){                           
                        window.location.href = 'error.html';
                    }
                });
                return false; // block regular submit
            }
        });
    });
</script>

server code

    <?php
    header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
    mysql_connect("localhost","root","7128");
    mysql_select_db("service");

    if(isset($_POST['type']))
    {
        if($_POST['type']=="booking"){
            $name = $_POST ['Name'];    
            $mobile = $_POST ['Mob_Num'];
            $mail = $_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();
            $value = "Welcome Mr/Mrs ".$name."  Thanks for booking home services your booking id is =  ".$id;
            echo json_encode($value);
        }
    }
    else{
        echo "Invalid format";
    }
?>

BookingConformation.html

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            function myFunction() {
                 var globalarray = [];
                 var arrLinks =[];
                 arrLinks = JSON.parse(window.localStorage.getItem("globalarray"));
                 document.getElementById("booking").innerHTML = arrLinks;
             }
        </script>
    </head>
    <body>  
        <p id="booking" onclick="myFunction()">Click me to change my HTML content (innerHTML).</p>
    </bod

y>

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 try this

declare variable on first page

<script type="text/javascript">
    var globalarray = [];
    globalarray.push(response.d);
     window.localStorage.setItem("globalarray", JSON.stringify(globalarray));
</script>

Call that variable on second page

<script type="text/javascript">
         var globalarray = [];
         var arrLinks =[];
         arrLinks = JSON.parse(window.localStorage.getItem("globalarray"));
        console.log(arrLinks);
</script>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM