简体   繁体   中英

Recover data from JQuery.post()

I'm using a $.post() to push data to a php file. But the $_POST is empty when I make a var_dump of it.

JS script :

 $('#Notes').on("click", function (e) {
        e.preventDefault();
        let $id = $(document).getUrlParam("varname");
        let $text = $(this).attr('data');
        let $notes = prompt("Modifier la note", $text);
        console.log($text, $id, $notes);


        if ($notes !== null || $notes !== "") {
            $.post(
                '../buckets/update_note.buckets.php',
                {
                    id: $id,
                    notes: $notes,
                },
                function (data) {
                    console.log('Data Id : ',data.id);
                    console.log('Data Name : ',data.name);
                })
                .then(r =>{
                   location.replace('../buckets/update_note.buckets.php');
            })
         }

in php file :

<?php

var_dump($_POST);
var_dump($_GET);

The 1st console.log in js show me the values of the 3 variables but the console.log in the callback show me undefined . But I see in the network debugger:

Form Data
id: xxxx
notes: xxxx

Any idea?

I believe, data will be text in your case. You need to use json_encode() in you php to print complex objects. Then in your JS you can use JSON.parse() to restore object or define application/json content type in your POST query. Something like:

// php
$json = json_encode([
  'post' => $_POST,
  'get'  => $_GET
]);

// js
function (response) {
  const data = JSON.parse(response);
}

You can try in this way.

JQuery CODE

$('#Notes').on("click", function (e) {
        e.preventDefault();
        let $id = $(document).getUrlParam("varname");
        let $text = $(this).attr('data');
        let $notes = prompt("Modifier la note", $text);
        console.log($text, $id, $notes);
        if ($notes !== null || $notes !== "") {
            $.post(
                '../buckets/update_note.buckets.php',
                {
                    id: $id,
                    notes: $notes,
                },
                function (data) {
                var data=$.parseJSON(data);
                    console.log('Data Id : ',data.id);
                    console.log('Data Name : ',data.notes);
                })
                .then(r =>{
                   //location.replace('../buckets/update_note.buckets.php');
            })
         }

PHP CODE

  echo json_encode($_POST);

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