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

Hi everyone,

I’m using some checkboxes to update a query that returns content from a database. For this I have used PHP. Now I’m trying AJAX. Normally my query will run if a checkbox has selected with this code:

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

query = etc...

How can I write this with JavaScript? I’d like to do something like ($_POST[‘name’]) === set. After this the PHP code will run as normal. Can I do it this way?

Thank you in advance!

Hi there,

Just to be clear, you can’t use JavaScript to actually query your database.
You can use JavaScript to send an AJAX request to a PHP script (optionally passing the PHP script some data), which will query the database and return a result to the JavaSript. From within the JavaScript (usually a success callback) you will then be able to manipulate/format the returned data and display it on the page.

Is this what you mean?

Hi there Pullo,

please excuse my late reply! I have been away from my PC, so have been unable to respond to your question.

Instead of someone clicking a checkbox and submitting the form, I’d like to use Ajax so that only a click is necessary. Before my query runs, $_POST[‘name’] must have a value. What I’d like is for my JavaScript code to confirm that $_POST[‘name’] does have a value and so the query can run. I assume that this checkbox value/data is then passed to the PHP script on the same page?

This is all I could come up with:

<script type="text/javascript">

   $(function(){

    $('#myform').on('click', 'input', function(){

    $.ajax({
            type:'GET',
            data:
	
        });


});
});


</script>

Thank you for your help.

Hi there,

Sorry for the short reply, but I’m on my iPad.

Anyway, if you could make a short HTML demo form (so that I know what $_POST[‘name’] should refer to), I will make you a demo when I am at the PC later on.

Hey Pullo,

sorry, here is the form. This is just some demonstration code:

print'<form method="post" action="" id="myform">
<div class="item">
<input type="checkbox" name="fruit[melon]"  value="melon">melon
</div>
<div class="item">
<input type="checkbox" name="fruit[kiwi]" value="kiwi">kiwi
</div>
<div class="item">
<input type="checkbox" name="price[expensive]" value="expensive">expensive
</div>
<div class="item">
<input type="checkbox" name="price[cheap]" value="cheap">cheap
</div>
<input type="submit" value="select">
</form>  '; 

Now I’m not sure how to construct the PHP code so that it works with Ajax.



if (isset($_POST['fruit']['melon'])) {
$whatever[] = "fruit='{$_POST['fruit']['melon']}'";}
if (isset($_POST['price']['expensive'])) {
$whatever[] = "price='{$_POST['price']['expensive']}'";}	
if(!empty($whatever)) {
  $something = implode(' && ',$whatever);
}

if (isset($_POST['fruit'])) {
$query = "SELECT … WHERE...  && $something"; }

Please let me know if you require more info.

Thanks again!

Hey,

No problem :slight_smile:

So, just to be clear, what should happen when a user selects one or more fruit and/or one or more prices?

Would it help get you started if I made a PHP script that echoed the choices back at you (which would normally be where your data processing takes place), then had the JavaScript insert the server’s response into a div on the page?

Hi there,

So, as promised here’s a demo:

index.php

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Fruity Ajax</title>
  </head>
  <body> 
    <form method="post" action="submit.php" id="myform">
      <div class="item">
        <input type="checkbox" name="fruit[melon]"  value="melon">melon
      </div>
      <div class="item">
        <input type="checkbox" name="fruit[kiwi]" value="kiwi">kiwi
      </div>
      <div class="item">
        <input type="checkbox" name="price[expensive]" value="expensive">expensive
      </div>
      <div class="item">
        <input type="checkbox" name="price[cheap]" value="cheap">cheap
      </div>
      <input type="submit" value="select">
    </form> 
    <p>The server thinks that you have currently selected: <span id="result"></span></p>

    <script src="http://code.jquery.com/jquery-latest.js"></script> 
    <script> 
      var $checkboxes = $( "form input:checkbox" )
      $checkboxes.on("change", function(){
        var nameArray = [];
        $checkboxes.each(function(){
          if(this.checked){
            nameArray.push(this.name);
          }
        })

        $.ajax({
          type: "POST",
          url: "submit.php",
          cache: false,
          data: 'name=' + nameArray,
          success: function(res){
            $('#result').html(res);
          }
        });
      })
    </script> 
  </body> 
</html>

submit.php

<?php 
  $name = $_POST['name'];
  echo($name);
?>

As you can tell, when a user selects a check box, an AJAX request is fired off to the server (submit.php), passing the current values of all selected check boxes. The server does nothing but spit them back at the script, which then catches them and inserts them in the page.

Admittedly it’s a bit inane, but should hopefully get you going in the right direction.

Oh yeah, here’s a demo.

HTH

Hey Pullo,

I already typed out a reply offline before I saw your post above. I’m just going to include it anyway.

Thank you very much for posting the demo, and for going to so much trouble to help me out. :slight_smile: What you posted looks very helpful. I’ll try out the code and will let you know if my own code works out.

Thank you.

Cheers

The letter I wanted to post:

Hi,

I am returning some records from a database. When a user selects one or more check boxes, the query is updated with the values of the selected check boxes. In essence, the check boxes will filter the query results.

The PHP code starts with:


if (isset($_POST['fruit'])) {
$query="SELECT…WHERE...&& $something";
$r = @mysqli_query($dbc, $q);
while ($row= mysqli_fetch_array($r, MYSQLI_ASSOC)) {

//echo database records

}
}

The updated query can only run if the $_POST variable has a value. Is it possible to tell Javascript that if this variable has been set then yes, PHP, you may continue with the script? Otherwise, I’ll need to rewrite the PHP code to JavaScript code? Must I pass the $_POST value to the PHP script in order for the query to run?

Hello again Pullo,

I managed to get the check boxes working with my current website. Thank you again for you assistance.

I do have a question though – hope you don’t mind. At the moment I’m only able to filter my query with one check box value. My query will, for example, end with: && fruit = ‘melon’. However, if multiple check boxes are checked I’m going to end up with additional conditionals in my query. So my query might be && fruit = ‘melon’ && price = ‘expensive’.

<script type="text/javascript">
       $('#myform').on('click', 'input', function(){

        var checky = $(this).val();

        $.ajax({
          type: "POST",
          url: "some url",
          cache: false,
          data: 'fruit=' + checky,
          success: function(res){
            $('#someid').html(res);
          }
        });
      })
</script>

The PHP code i’ve used follows below. Should I rewrite this in JavaScript, and if so, how would I code the “data” setting in the Ajax call?


if (isset($_POST['fruit']['melon'])) {
$whatever[] = "fruit='{$_POST['fruit']['melon']}'";}
if (isset($_POST['price']['expensive'])) {
$whatever[] = "price='{$_POST['price']['expensive']}'";}
if(!empty($whatever)) {
  $something = implode(' && ',$whatever);
}

if (isset($_POST['fruit'])) {
$query = "SELECT … WHERE...  && $something"; } 

If you could help me again, that would be great!

Thank you.

Ok, so if I understand you correctly, you’re asking how to pass multiple parameters to your PHP script?

That would be this:

$.ajax({
  type: "POST",
   url: "some url",
  cache: false,
  data: 'fruit=' + checky + '&price=' + pricey,
  success: function(res){
    // Callback code here
   }
});

Does that help?

Thank you for getting back to me.

Well, I need to determine if the fruit and price variables are set before the strings can be added to the $whatever array. There might be a better way of constructing the conditionals in the query but this is all I could do. The PHP code itself could use some refinement. Is there a better way of writing the following code, using a loop perhaps?

if (isset($_POST[‘fruit’][‘melon’])) {
$whatever = “fruit=‘{$_POST[‘fruit’][‘melon’]}’”;}
if (isset($_POST[‘fruit’][‘kiwi’])) {
$whatever = “fruit=‘{$_POST[‘fruit’][‘kiwi’]}’”;}
if (isset($_POST[‘fruit’][‘mango’])) {
$whatever = “fruit=‘{$_POST[‘fruit’][‘mango’]}’”;}

Thanks!

Hey there,

I would probably construct things so that the processing is done in the JS before you send it to the PHP.
That way you can keep things a little neater.

I’m having a bad day today (coming down with something), so I apologize if you’ve explained it before and I haven’t got it, but if I can get my head round what you are trying to do then, maybe I can help you more.

Would this be a fair summary:

You have a bunch of check boxes.
Every time a check box is selected or deselected an AJAX request fires to a PHP script.
The AJAX request passes some parameters to your PHP script and the PHP script uses these parameters to build a query and fetch some records from a database.
The PHP script then returns some attribute(s) from the records it has selected to your JavaScript, which then updates the page.

Hey Pullo,

sorry to hear that you aren’t feeling well, I’m feeling rather nauseous myself from this coding. This can also wait until tomorrow.

Your summary is fine. As I mentioned the Ajax is working but will update the query with the value from only one checkbox. I need to end up with a query such as:
WHERE fruit = ‘mango’ && price = ‘expensive’. Do you think its possible to have a data setting such as the following:

data: ‘fruit[mango]=’ + checked + ‘&price[expensive]=’ + priced,

I need to “check” if, for example, $_POST[‘fruit’][‘melon’] is “checked” before the string containing the checkbox’s value is added to the whatever array. Again, I’m checking each checkbox individually because I have no idea how to construct it with a loop. All fruits will be added to the string: “fruit=‘{$_POST[‘fruit’][‘checkbox-value-here’]}’”; and all prices will be added to the string: “price=‘{$_POST[‘price’][‘checkbox-value-here’]}’”;

Thanks! - Hope you feel better soon

Hi there,

So I was thinking long and hard about the best way to do this.
Here’s a demo of what I came up with.
It’s meant to be a temporary worker database, where you can filter workers according to specific criteria.

Here’s the code:

<!DOCTYPE HTML>
<html>
  <head>
    <metacharset="utf-8">
    <title>AJAX query filter</title>
    <style>
      body{ padding: 10px; }

      h1{
          margin: 0 0 0.5em 0;
          color: #343434;
          font-weight: normal;
          font-family: 'Ultra', sans-serif;   
          font-size: 36px;
          line-height: 42px;
          text-transform: uppercase;
          text-shadow: 0 2px white, 0 3px #777;
      }
 
      h2{
          margin: 1em 0 0.3em 0;
          color: #343434;
          font-weight: normal;
          font-size: 30px;
          line-height: 40px;
          font-family: 'Orienta', sans-serif;
      }

      #employees{
        font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
        font-size: 12px;
        background: #fff;
        margin: 15px 25px 0 0;
        border-collapse: collapse;
        text-align: center;
        float: left;
        width: 700px;
      }

      #employees th{
        font-size: 14px;
        font-weight: normal;
        color: #039;
        padding: 10px 8px;
        border-bottom: 2px solid #6678b1;
      }

      #employees td{
        border-bottom: 1px solid #ccc;
        color: #669;
        padding: 8px 10px;
      }

      #employees tbody tr:hover td{
        color: #009;
      }

      #filter{ float:left; }
    </style>
  </head>
  <body> 
    <h1>Temporary worker database</h1>

    <table id="employees">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Age</th>
          <th>Address</th>
          <th>Car</th>
          <th>Language</th>
          <th>Nights</th>
          <th>Student</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>

    <div id="filter">
      <h2>Filter options</h2>
      <div>
        <input type="checkbox" id="hasCar" name="hasCar">
        <label for="hasCar">Has own car</label>
      </div>
      <div>
        <input type="checkbox" id="speaksForeignLanguage" name="speaksForeignLanguage">
        <label for="speaksForeignLanguage">Can speak foreign language</label>
      </div>
      <div>
        <input type="checkbox" id="canWorkNights" name="canWorkNights">
        <label for="canWorkNights">Can work nights</label>
      </div>
      <div>
        <input type="checkbox" id="isStudent" name="isStudent">
        <label for="isStudent">Is a student</label>
      </div>
    </div>

    <script src="http://code.jquery.com/jquery-latest.js"></script> 
    <script>
      function makeTable(data){
       var tbl_body = "";
          $.each(data, function() {
            var tbl_row = "";
            $.each(this, function(k , v) {
              tbl_row += "<td>"+v+"</td>";
            })
            tbl_body += "<tr>"+tbl_row+"</tr>";
          })

        return tbl_body;
      }

      function getEmployeeFilterOptions(){
        var opts = [];
        $checkboxes.each(function(){
          if(this.checked){
            opts.push(this.name);
          }
        });

        return opts;
      }

      function updateEmployees(opts){
        $.ajax({
          type: "POST",
          url: "submit.php",
          dataType : 'json',
          cache: false,
          data: {filterOpts: opts},
          success: function(data){
            $('#employees tbody').html(makeTable(data));
          }
        });
      }

      var $checkboxes = $("input:checkbox");
      $checkboxes.on("change", function(){
        var opts = getEmployeeFilterOptions();
        updateEmployees(opts);
      });

      updateEmployees();
    </script> 
  </body> 
</html>
<?php 
 $pdo = new PDO(connection details here);
  
  $select = 'SELECT *';
  $from = ' FROM people';
  $where = ' WHERE TRUE';
  $opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');

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

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

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

  $sql = $select . $from . $where;
  $statement = $pdo->prepare($sql);
  $statement->execute();
  $results=$statement->fetchAll(PDO::FETCH_ASSOC);
  $json=json_encode($results);
  echo($json);
?>

You have to be quite careful when passing user input from a form to a server-side script, which will then use the input it receives to construct a database query.
This is because it is entirely possible to submit data to the server-side script without using the form and if the input is not sanitized or handled correctly, you will open yourself up to an SQL injection attack.

Have a look at what I have posted above and let me know if you have any questions.

References:
http://stackoverflow.com/questions/1051061/convert-json-array-to-an-html-table-in-jquery

http://tympanus.net/codrops/2012/11/02/heading-set-styling-with-css/

Hey Pullo,

how are you doing?

That is an awesome demo! Thank you so much for assisting me with this issue - I really appreciate it. I hope this hasn’t taken up too much of your time.

If you have a spare moment, may I just ask where “TRUE” in the statement $where = ’ WHERE TRUE’; comes from?

Thank you again.

Hi there,

No problems, man.
It was fun to piece together.

Yeah, that has the benefit that you can just add to the WHERE statement without the need to remove the first AND.
If you didn’t have something like this, you would need to work out the first filter criteria and append it to the WHERE statement without an AND, then and an AND for any filter criteria that come after that.
This way you can always just write AND condition.

Does that make sense?

Ok, got it! Thanks for the speedy reply.

Enjoy the weekend!

Hey there Pullo,

I’m sorry to bug you again, but since I’m a tad thick when it comes to JavaScript/jQuery (some would say PHP as well…), I need some help. :unhappy:

I’m still unable pass the checkbox values to the PHP script. If selected, I need to pass the value of the checkboxes with name=“fruit” to the script. Same goes for the checkboxes with name=“price”. I have used various combinations from your code without success. My query should end up looking like - && fruit = ‘melon’ && price = ‘expensive’ , all depending on the checkbox selection.

I tried the following:

 var $checkbox = $( "form input[name='fruit[]']" )
      $checkbox.on("change", function(){


          if(this.checked){
         var hope = $(this).val();
	  }
)};
	
 var $checkboxes = $( "form input[name='price[]']" )
      $checkboxes.on("change", function(){


          if(this.checked){
         var less = $(this).val();
	  }
)};

Could you please help me again?

Thank you! And I hope you don’t scream when you read this.

The PHP needs looks like this:

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

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

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

Hi,

Are you sure that check boxes are the correct input element to use.
For me it seems counter intuitive that an item could be both cheap and expensive.

Doesn’t it make more sense to use radio buttons or something?

Anyway, what I would do, is attach an on change listener to the checkboxes, then when one is selected or deselected, iterate over all of them and send an array containing a list of checked boxes to the server.

E.g.

<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>Checkboxes</title>
  </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> 

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
      function makeAjaxRequest(opts){
        console.log(opts);
      }

      var $checkboxes = $( "input:checkbox" );

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

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

        makeAjaxRequest(opts);
      });
    </script>
  </body>
</html>

Hey Pullo,

thank you for getting back to me.

For me it seems counter intuitive that an item could be both cheap and expensive.

You are right about that - I still have to work out the finer details. I am just testing the functionality of using Ajax with multiple checkboxes to update my query.

The code you posted above. Do I use this as is in my webpage? How would I craft the data setting of the Ajax call given the PHP code I posted previously?
Do I need to include console.log?

Thanks a lot!!