0

AJAX works fine, but $_POST does not have a value.

What I have tried:

  • $data = json_decode(file_get_contents('php://input'), true); & $post = json_decode($data); into storecart.php
  • Changing the data into 'jCart=' + jData'
  • removing datatype (Jaromanda X)
  • answer (Umakant Mane)

cart is an array of objects

Javascript:

        $(document).ready(function(){
            $("#showcart").click(function(event){
                event.preventDefault();
                showcart();
                url = 'cart.php';
                $(location).attr("href",url);
            });
        });

        function showcart(){
            var jData = JSON.stringify(cart);
            $.ajax({
                url:"storecart.php",
                type:"post",
                data: {jCart : jData},
                datatype: "json",
                success: function(data){
                    console.log("SUCCESS")
                    console.log(jData);
                },
                error: function(data){
                    console.log("REDO")
                }
            });     
        }

storecart.php:

<?php
    if(isset($_POST['jCart'])){
        echo "Right";
    }else{
        echo "Wrong";
    }
?>

How do get the $_POST to accept the json.stringify?

SOLUTION:

SOLVED:

All i did was add a form that has a hidden value

<form id = "postform" action = "cart.php" method = "post">
  <input type = "hidden" id="obj" name="obj" val="">
  <input type = "submit" value = "Show Cart" id = "showcart">
</form>

In the Javascript:

$(document).ready(function(){
  $("#showcart").click(function(){
    var json = JSON.stringify(cart)
    $('#obj').val(json);
    $('#obj').submit();
  });
});

Thank you for everyone that has answered but hope this helps.

Jokes.me
  • 11
  • 2
  • 1
    `What I have tried:` - have you tried **not** setting `dataype: "json",` - also, see http://stackoverflow.com/a/18867369/5053002 – Jaromanda X Oct 09 '16 at 11:35
  • 1
    ^ that, if you're expecting to get JSON back from the server, you can't send just `Right` ! – adeneo Oct 09 '16 at 11:38
  • @Jaromanda X, the first dot point was from the link that you gave – Jokes.me Oct 09 '16 at 11:43
  • So... if you solved it yourself, don't edit your question but add it as an answer instead, and then accept that as the correct answer – Rene Pot Oct 11 '16 at 12:34

1 Answers1

-1
 $(document).ready(function(){
 var data = {one:"one", two:"two", three:"three"};
 var jsonData = JSON.stringify(data);
  $("#clickme").click(function() {
  $.ajax({
  url:"demo.php",
  type:"POST",
  data:{cart:jsonData},
  success:function(response){
      console.log(response);
  }, error:function(err) {
    console.log(err);
 }

 })
 }); 
 });

PHP

  <?php

 if(isset($_POST['cart'])){
    echo "Right";
  }else{
    echo "Wrong";
  }
?>
Umakant Mane
  • 1,001
  • 1
  • 8
  • 9