If (isset($_POST['name'])) { JavaScript equivalent

Hi there,

I wouldn’t do it like this in the PHP.
I would post an array containing the value of any boxes that were checked to my PHP script, then retrieve those in my PHP script and build the query accordingly.

Does that make sense?

No, this is just to demonstrate what the variables would contain at this point.

Hey Pullo,

you mean my PHP code should be like that in your demo?

$opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');

  if (in_array("hasCar", $opts)){
    $where .= " AND hasCar = 1";
  }

I could do that as well but I’d prefer to use the PHP code that I’m presently using. This is because the PHP code is working and implementing another method will be a problem again. If you could please show me how to pass the checkbox values so that I can retrieve those with my current PHP code I’d be EXTREMELY grateful!

Thank you.

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

}
if (isset($_POST['price'])){

}

Sure.

You’ll still need to attach an onchange event handler to the checkboxes, so that an AJAX request is fired every time a user selects or deselects anything:

// This selects the checkboxes
var $checkboxes = $( "input:checkbox" );

$checkboxes.on("change", function(){
  // Code here will be executed whenever a user selects or deselects a check box
})

When your AJAX request hits your PHP script, your PHP script will be expecting two arrays: “fruit” and “price”
So when the onchange code is executed we will need to construct these arrays:

$checkboxes.on("change", function(){
  var fruit = [], 
      price = [];

  $checkboxes.each(function(){
    if (this.checked){
      if(this.name === "fruit[]"){
        fruit.push(this.value);
      } else if (this.name === "price[]"){
        price.push(this.value);
      }
    }
  })

Once the price and fruit arrays are populated correctly, all that is left to do is to send them off to the PHP script via AJAX.
I would make this a separate function:


function makeAjaxRequest(fruit, price){
  $.ajax({
    type: "POST",
    url: "submit.php",
    cache: false,
    data: {fruit: fruit, price: price},
      success: function(result){
        // This code will fire when the AJAX request completes successfully.
        // result will contain the server's response
      }
    });
}

$checkboxes.each(function(){
  ...
  makeAjaxRequest(fruit, price);
})

And that should be all there is to it :slight_smile:

Here’s the complete code:

index.html

<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>Fruity AJAX 3</title>
    <link href="" rel="stylesheet" type="text/css">
  </head>
  
  <body>
    <form method="post" action="submit.php" id="myform">
      <div class="item">
        <input type="checkbox" name="fruit[]"  value="melon">melon
      </div>
      <div class="item">
        <input type="checkbox" name="fruit[]" value="kiwi">kiwi
      </div>
      <div class="item">
        <input type="checkbox" name="price[]" value="expensive">expensive
      </div>
      <div class="item">
        <input type="checkbox" name="price[]" value="cheap">cheap
      </div>
      <input type="submit" value="select">
    </form> 

    <div id="result"></div>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
      function makeAjaxRequest(fruit, price){
        $.ajax({
          type: "POST",
          url: "submit.php",

          cache: false,
          data: {fruit: fruit, price: price},
            success: function(result){
              $("#result").text("The server recieved the following values: " + result)
            }
          });
      }
      
      var $checkboxes = $( "input:checkbox" );

      $checkboxes.on("change", function(){
        var fruit = [], 
            price = [];
        $checkboxes.each(function(){
          if (this.checked){
            if(this.name === "fruit[]"){
              fruit.push(this.value);
            } else if (this.name === "price[]"){
              price.push(this.value);
            }
          }
        })

        makeAjaxRequest(fruit, price);
      })
    </script>
  </body>
</html>

submit.php

<?php 
  print_r($_POST);
?>

Morning Pullo,

thank you so much for helping me and for explaining what the code is doing. :slight_smile: The code looks simple enough so I wonder why I couldn’t have come up with something similar - I guess I’m still learning. Anyway, thanks for being so helpful and professional, and I apologise for all the time you have spent on this.

So I’ve had an opportunity to test the code. It is all working fine except that I’m only able to select one checkbox at a time. It won’t let me select a checkbox from “fruit” and a checkbox from “price”, so that the query is && fruit=‘melon’ && price=‘expensive’.

No problem. I’m just happy to help :slight_smile:

Could you elaborate on this. What won’t let you select a checkbox?
Are the values being passed to your PHP script correctly?
In other words, is the problem in the JS or in the PHP?

I’m unable to refine my selection by selecting multiple checkboxes. So if I click the melon checkbox it will display all the melons, but if I then click expensive to show only expensive melons it won’t let me do that. It will add the price=“expensive” conditional to the original query and not to the one that has already been filtered.

The PHP is working fine with JavaScript disabled.

Every time one of the check boxes is selected, your script should be firing an AJAX request to the PHP script.
Based on what parameters it was passed, the PHP script should be assembling a query and executing it.
It should then be returning the results of the query to the JavaScript which should be displaying the results on the page.

From what you describe above, it seems that the query is only executing once and that subsequent changes to the check boxes are having no effect.
Are you sure you have implemented things as described above?

Yes, I don’t why. I’ve posted the PHP code below.

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

foreach ($_POST['fruit'] as $f) {
	      $arguments[] .= "fruit='$f'";
	}
        }
if (isset($_POST['price'])){
foreach ($_POST['price] as $p) {
	      $arguments[] .= "price='$p'";
	}
}


if(!empty($arguments)) {
  $conditions = implode(' && ',$conditions);
}

From what I can see - yes. I’ve added this to the Ajax call.

success: function(response){
$(“#container”).html(response)
}

OK, well something is going wrong somewhere.
I’ll send you a PM.

Ok Pullo,

thanks a lot.

Just to be complete, I wrote this up as a tutorial.