obmon
obmon

Reputation: 337

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?

Upvotes: 0

Views: 71

Answers (2)

user1299518
user1299518

Reputation:

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;
}
?>

Upvotes: 1

Charlotte Dunois
Charlotte Dunois

Reputation: 4680

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

Upvotes: 0

Related Questions