简体   繁体   中英

Undefined index in post method of JSON object sent by jQuery AJAX

I've tried almost all suggestions but it doesn't work. My id s are working properly in the JavaScript function when I alert my array using arr['id'] . However, when I try $_POST['id'] on a different PHP file (I've used AJAX and specified the URL) is gives me an error.

scriptfile.php:

<script>
function detailsmodal(cid, pid) {
    var arr = { "cid": cid, "pid": pid };
    jQuery.ajax({
        url: '/frontend/include/detailsmodal.php',
        method: "post",
        data: arr,
        success: function(data) {
            jQuery('body').append(data);
            jQuery('#details-modal').modal('toggle');
        },
        error: function() {
            alert("something went wrong");
        }
    });
}

detailsmodal.php

<?php
echo $_POST['cid'];
?>

You could try sending your data as json like this:

        $.ajax({
            type: "POST",
            url: "/frontend/include/detailsmodal.php",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify({ cid: cid, pid: pid }),
            success: function(data) {
                jQuery('body').append(data);
                jQuery('#details-modal').modal('toggle');
            },
            error: function() {
                alert("something went wrong");
            }
        });

For the decoding you could use javascript JSON.parse

var myObj = JSON.parse(this.responseText);

or

$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["cid"];

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