John Beasley
John Beasley

Reputation: 3075

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?

Upvotes: 0

Views: 220

Answers (2)

Barmar
Barmar

Reputation: 780818

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.

Upvotes: 2

Carlos2W
Carlos2W

Reputation: 2544

Try wrapping it in a bigger object like this :

Javascript :

$('.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 : searchCriteria }, function(data)
   {
     console.log(data);
    });
 });

PHP :

<?php
  if($_POST['searchCriteria'] == true)
  {
    $searchCriteria = json_decode($_POST['searchCriteria']);
    // Now you can for each loop throught it for example
    foreach($searchCriteria as $key => $value) {
       // Do something
    }
  } 

 ?>

Upvotes: 3

Related Questions