0

I'm working on shopping cart. Now I need to pass the array of objects added into shopping cart which is stored in localStorage to php page in order to insert into database.

console.log(localStorage.getItem("shoppingCart"));

Above logs out, the following:

[{"name":"Banana","price":1.33,"count":5},{"name":"Apple","price":1.22,"count":5},{"name":"Shoe","price":22.33,"count":1}]

Now I'm trying to pass this JSON string to a php page called submit_cart.php and retrieve the string in php page correctly, how do I do that? Currently it's sending and receiving empty data.

$("#submit-cart").click(function(event){
                console.log("****TEST LOG ***");
                console.log(localStorage.getItem("shoppingCart"));
                var data = localStorage.getItem("shoppingCart");
                $.ajax({
                  type: "POST",
                  dataType: "json",
                  url: "submit_cart.php",
                  data: data,
                  success: function(data) {
                    console.log("******success******");
                    console.log(data);//this logs []
                  }
                 });
            });

In submit_cart.php

<?php
$return = $_POST;
$return["json"] = json_encode($return);
$data = json_decode($return["json"], true);

echo json_encode($return["json"]);
  ?>

EDITED as suggested answer and it's working now:

$("#submit-cart").click(function(event){
                console.log("****TEST LOG ***");
                console.log(localStorage.getItem("shoppingCart"));
                var data = localStorage.getItem("shoppingCart");

            $.ajax({
            type: "POST",
            dataType: "json",
            contentType: 'application/json',
            url: "submit_cart.php",
            data: data,
            success: function(data) {
            console.log("******success******");
            console.log(data);//this logs []
            }
            });
            });

In submit_cart.php

<?php
$_POST = json_decode(file_get_contents('php://input'),true);

print_r($_POST);
  ?>
6
  • what is the error you are getting? Commented Apr 6, 2016 at 14:42
  • In the success function of ajax , I get empty data,meaning ajax doesn't send data correctly or php doesn't decode it correctly. Commented Apr 6, 2016 at 14:44
  • Put an alert after assigning value to data and see what value you are getting like alert(data); Commented Apr 6, 2016 at 14:46
  • Put a print_r($_POST); at the top of your PHP script, so you can see what it contains. I am pretty sure doing a json_encode() of all of the $_POST array is NOT what you want to do. Commented Apr 6, 2016 at 14:46
  • 1
    if it is already encoded in json format then why you are using json_encode($return);. remove json_encode($return); and check Commented Apr 6, 2016 at 14:46

4 Answers 4

1

On the ajax request set the content type to json and on the php side read the json from php://input

$.ajax({
  type: "POST",
  dataType: "json",
  contentType: 'application/json',
  url: "submit_cart.php",
  data: data,
  success: function(data) {
    console.log("******success******");
    console.log(data);//this logs []
  }
});
$_POST = json_decode(file_get_contents('php://input'),true);
// then use post as usual
Sign up to request clarification or add additional context in comments.

5 Comments

Hi Musa, silly question, why do you use file_get_contents('php://input') rather than just using $_POST as delivered by PHP. I am just interested, not picking holes!
$_POST is only populated for certain content types, json is not one of them
An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request. php.net/manual/en/reserved.variables.post.php
@Musa, I get the string of data in the submit_cart.php but before that I noticed html warning in that page..
Just try outputting the whole dataset echo json_encode($return);
1

Both are wrong if you want to get the values from $_POST. You need to send key-value pairs to the server and then you can access them in $_POST by these keys.

To send everything in 1 variable, you could do something like:

...
var data = {json: localStorage.getItem("shoppingCart")};
...

Note that sending an object is always a good idea as jQuery will take care of encoding the data correctly when you use an object.

And then you can get it in php like:

// you only need this, no additional encoding / decoding
$data = json_decode($_POST["json"], true);

2 Comments

i get null in the php and success function
@Keren Can you post the corrected code below the original version in your question?
0

Your data is already encoded as you mention in your question console.log(localStorage.getItem("shoppingCart"));

output is

[{"name":"Banana","price":1.33,"count":5},{"name":"Apple","price":1.22,"count":5},{"name":"Shoe","price":22.33,"count":1}]

So in your ajax request

data: { json_data:data} ,

in this case data work as object and it is easy to fetch value.

and in php file

echo $_POST["json_data"];

2 Comments

but why am I not getting anything in the success function?
check your browser console for what data is sending by the ajax request.
0

You are not sending any data to the target page here.Inside the ajax send the data with data: parameter.Then instead of using success function use .done() function outside the ajax.The done function is better in terms of result handling.You can check whether your data is transmitting or not by using the developer tool network.There all the request and response data is shown.Hopefully this will solve the problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.