简体   繁体   中英

Sending an array from jquery to PHP and back

I have a list of options (categories) of projects that the user can see. By selecting the categories, the div below should update with the lists of projects matching said categories.

Despite using the following answer, almost verbatim, Send array with Ajax to PHP script , I am still unable to retrieve any results, and yet no errors show up either.

The jquery:

// filter for projects
var $checkboxes = $("input:checkbox");

function getProjectFilterOptions(){
    var opts = [];

    $checkboxes.each(function(){
        if(this.checked){
            opts.push(this.name);
        }
    });

    return opts;
}

$checkboxes.on("change", function(){
    var opts = getProjectFilterOptions();

    //alert(opts);

    var categories = JSON.stringify(opts);

    $.ajax({
        url: "/web/plugins/projcat.php",
        type: "POST",
        dataType: "json",
        data: {data : categories},
        cache: false,

        success: function(data) {
            $('#projects').html(data);
            //alert(data);
        }
    });

});

the php (still in testing, so not filled out):

<?php

if(isset($_POST['categories'])) {

    //echo "testing";
    $data = json_decode(stripslashes($_POST['categories']));
    print_r($data);
}
?>

Where is the error?

Try this:

JS

...    
// dataType: "json",   // remove that; you're not sending  back JSON string
data: {categories : categories},
cache: false,
...

PHP

<?php

if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['categories'])) {

    //echo "testing";
    $data = json_decode(stripslashes($_POST['categories']));

    // .. process the $data

    print_r($data);
    return;
}
?>

Your desired array is in $_POST['data'] and not in $_POST['projcats'] . Change data: {data : categories}, to data: { projcats: categories }, to use $_POST['projcats'] .

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