简体   繁体   中英

Send json from javascript to php

I have a page where users do some stuff and on selecting next, I want to redirect them to a php file, called "Step2.php" along with some JSON information.

I built my json string and it looks like this:

[{"name":"IMG_20130726_182336.jpg","size":2280709,"type":"image/jpeg","width":null,"height":null,"lastModified":1374852216000,"fileExtension":"jpg","orientation":1,"displayed":true,"attributes":[{"title":"Name: ","value":"IMG_20130726_182336.jpg"},{"title":"Date: ","value":"no date"}]}]

Now, I sent it trough jquery POST like this:

jsonData = JSON.stringify(serializableAttributes);
    console.log(jsonData);
    $.ajax({
        type: 'POST',
        url: 'Step2.php',
        data: {"jsonData" : jsonData},
        success: function(msg) {
            console.log("Json Sent! " +msg);
            window.location("")
        },
        error: function(request,msg){
            console.log("Error : " + msg);
        }
    });

Question: Why I can`t receive anything in my Step2.php file? Am I wrongly redirect user to that page?

Code in the Step2.php files looks like this:

if(isset($_POST["jsonData"])) {
    $json = $_POST["jsonData"];
    var_dump(json_decode($json, true));
} else {
    echo "NO";
}

It always shows NO.

You can't do it like this. That's not how AJAX and POST work.

If you're simply going to Step2.php, try sending it to the page as part of the URL.

Instead of your AJAX function, simply do:

var jsonData = [YOUR DATA]; 
window.location.href="Step2.php?json="+jsonData

Or if PHP created the JSON string, you could store it as a SESSION variable.

EDIT: To venture a bit further on the SESSION variable route...

Have your AJAX script as it is now, but make a new PHP file. In this example we'll call it foo.php. Have your foo.php file setup like so:

session_start();
if($_POST){
    if(isset($_POST['jsonData'])){
        $json = $_POST['jsonData'];
        $_SESSION['jsonData'] = $json;
        //CREATE A JSON RESPONSE INIDCATING SUCCESS
        echo '{ "success" : 1 }';
    }
}

Your SUCCESS function of the AJAX call could analyze the response for the success code. If it's "1" redirect to the Step2.php page.

Just make sure that you're calling session_start() at the top of each page.

Ok so I think you misunderstand how AJAX works. You ajax request sends the json to you php and should then respond to it with the appropriate return, in your case a var_dump .

This won't hold the json in the php at all and if you go and request the php file without the POST request you won't get anything else but the output "NO" as there is no POST data you are sending.

If you do want to send a json to you php you do what you are doing now and listen to the request responds which you can see in your inspector. I am not clear on what you ultimately want to do with the data so I don't know if this is the right way.

You can post JSON to PHP

jsonData = JSON.stringify(serializableAttributes);
console.log(jsonData);
$.post("Step2.php", { json: jsonData },  function(msg) {
  console.log("image name = " + msg);
});

PHP, you simply parse:

if(isset($_POST['json'])){
   $json = $_POST['json'];
   $data = json_decode($json);
   $image = $data[0];
   echo $image->name;

   $atributes = $image->attributes;
   foreach($atributes as $atrribute){
    //echo 'title '.$atribute->title;
   }
}

Try this code in my work:

<?php
if(isset($_POST["jsonData"])) {
    $json = $_POST["jsonData"];
    $json = str_replace('\\', '', $json);
    var_dump(json_decode($json, true));
    print_r($json);
} else {
    echo "NO";
}
?>

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