John Beasley John Beasley - 18 days ago 5
Javascript Question

JQUERY AJAX send search criteria to PHP return JSON

I am trying to send a group of variables to a PHP script via AJAX.

Typically, this is what I'd do:

$('.submitSearch').on('click', function()
{
var rep = $('#rep').val();
var num = $('#num').val();
var uid = $('#uid').val();
// and so on
// then I could send each variable to a PHP script
$.post('api/summary.php', {rep: rep, num: num, // and so...}, function(data)
{
console.log(data);
});
});


That's how I'd normally do it.

But now, I am trying send all of the parameters in a single variable I calling searchCriteria, as follows:

$('.submitSearch').on('click', function()
{
var searchCriteria =
{
rep: $('#rep').val(),
num: $('#num').val(),
uid: $('#uid').val(),
// and so on...
}

// then send them to the php script

$.post('api/summary.php', searchCriteria, function(data)
{
console.log(data);
});
});


Then, in the PHP script, retrieve all of the parameters from the variable for processing:

<?php
if($_POST['searchCriteria'] == true)
{
// get the parameters
// build the query
// return JSON
}

?>


My question is: How do I get all of the parameters out of $_POST['searchCriteria'] in the PHP script?

Answer

If you want everything in a single $_POST parameter, you need to wrap in another object:

$.post('api/summary.php', {searchCriteria : searchCriteria }, function(data) {
    ...
});

In the PHP, you would then access them as nested arrays.

$sc = $_POST['searchCriteria']
$rep = $sc['rep'];
$num = $sc['num'];
$uid = $sc['uid'];

I'm not sure what you expect to gain by adding this extra level of wrapping.