Viewed   115 times

I have a simple php file that decode my json string, passed with ajax, and stamp the result, but I can't keep the $_POST variable, why???

I try to inspect with fireBug and I can see that the POST request is sent correctly, when the php script is called, he respond Noooooooob to me, it seem any POST variable is set.

All I want is to have my array =)

JSON String generated by JSON.stringify:

[
   {
      "id":21,
      "children":[
         {
            "id":196
         },
         {
            "id":195
         },
         {
            "id":49
         },
         {
            "id":194
         }
      ]
   },
   {
      "id":29,
      "children":[
         {
            "id":184
         },
         {
            "id":152
         }
      ]
   },
   ...
]

JavaScript

$('#save').click(function() {
  var tmp = JSON.stringify($('.dd').nestable('serialize'));
  // tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
  $.ajax({
    type: 'POST',
    url: 'save_categories.php',
    dataType: 'json',
    data: {'categories': tmp},
    success: function(msg) {
      alert(msg);
    }
  });
});

save_categories.php

<?php
  if(isset($_POST['categories'])) {
    $json = $_POST['categories'];
    var_dump(json_decode($json, true));
  } else {
    echo "Noooooooob";
  }
?>

 Answers

5

Your code works if you remove dataType: 'json', just tested it.

$('#save').click(function() {
  var tmp = JSON.stringify($('.dd').nestable('serialize'));
  // tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
  $.ajax({
    type: 'POST',
    url: 'save_categories.php',
    data: {'categories': tmp},
    success: function(msg) {
      alert(msg);
    }
  });
});
Wednesday, August 3, 2022
5

Code example with JSON.stringify:

<html>
    <head>
       <title>jQuery Test</title>
       <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
       <script type="text/javascript">
           $(document).ready(function() {
               $("#submit").click(function(){
                   $.ajax({
                       url: "text.php",
                       type: "POST",
                       data: {
                           amount: $("#amount").val(),
                           firstName: $("#firstName").val(),
                           lastName: $("#lastName").val(),
                           email: $("#email").val()
                       },
                       dataType: "JSON",
                       success: function (jsonStr) {
                           $("#result").text(JSON.stringify(jsonStr));
                       }
                   });
               });
           });
       </script>
    </head>

    <body>
        <div id="result"></div>
        <form name="contact" id="contact" method="post">
            Amount: <input type="text" name="amount" id="amount"/><br/>
            firstName: <input type="text" name="firstName" id="firstName"/><br/>
            lastName: <input type="text" name="lastName" id="lastName"/><br/>
            email: <input type="text" name="email" id="email"/><br/>
            <input type="button" value="Get It!" name="submit" id="submit"/>
        </form>
    </body>
</html>

text.php

<?php
    $amount      = $_POST["amount"];
    $firstName   = $_POST["firstName"];
    $lastName    = $_POST["lastName"];
    $email       = $_POST["email"];
    if(isset($amount)){
        $data = array(
            "amount"     => $amount,
            "firstName"  => $firstName,
            "lastName"   => $lastName,
            "email"      => $email
        );
        echo json_encode($data);
    }
?>
Friday, October 21, 2022
 
chrissr
 
2

When not using url rewriting (google mod_rewrite and pretty URL's), your parameters typically are going to be passed as a normal HTTP GET request. Here is an example of how your URL structure might look:

url: 'ListProduk.php?action=SelectData'

And then, in your PHP, you might handle it based on the action that is requested (Note: The action parameter is not something specific to web development, it's just an arbitrary name I assigned. It could be foo=SelectData as well)

if ($_POST['action'] == 'SelectData') {
   // Run the code for selecting data
}

Finally, you wouldn't want to "return" the JSON data. You need to output it with the correct headers. It would look something like this:

header('Content-Type: application/json');
echo json_encode($data);
Friday, December 16, 2022
5

here is a simple one

here is my test.php for testing only

<?php

// this is just a test
//send back to the ajax request the request

echo json_encode($_POST);

here is my index.html

<!DOCTYPE html>
<html>

<head>

</head>
<body>

<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>




<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        // click on button submit
        $("#submit").on('click', function(){
            // send ajax
            $.ajax({
                url: 'test.php', // url where to submit the request
                type : "POST", // type of action POST || GET
                dataType : 'json', // data type
                data : $("#form").serialize(), // post data || get data
                success : function(result) {
                    // you can see the result from the console
                    // tab of the developer tools
                    console.log(result);
                },
                error: function(xhr, resp, text) {
                    console.log(xhr, resp, text);
                }
            })
        });
    });

</script>
</body>
</html>

Both file are place in the same directory

Saturday, December 17, 2022
 
4

Request method property is type instead of method ($.ajax({ method : "POST" is actually $.ajax({ type : "POST") and $_POST['data'] should be $_POST['id'].

Friday, November 18, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :