SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 33
  1. #1
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    364
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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:

    PHP 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!

  2. #2
    Grüße aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,000
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    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?

  3. #3
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    364
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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:

    HTML Code:
    <script type="text/javascript">
    
       $(function(){
    
        $('#myform').on('click', 'input', function(){
    
        $.ajax({
                type:'GET',
                data: 
    	   
            });
    
    
    });
    });
    
      
    </script>
    Thank you for your help.

  4. #4
    Grüße aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,000
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    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.

  5. #5
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    364
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey Pullo,

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


    HTML 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.

    PHP Code:

    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!

  6. #6
    Grüße aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,000
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hey,

    No problem

    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?
    Last edited by Pullo; Nov 19, 2013 at 14:04. Reason: typo

  7. #7
    Grüße aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,000
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    So, as promised here's a demo:

    index.php
    Code:
    <!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
    Code:
    <?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

  8. #8
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    364
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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. 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:
    PHP Code:
    if (isset($_POST['fruit'])) {
    $query="SELECT…WHERE...&& $something"
    $r = @mysqli_query($dbc$q);
    while (
    $rowmysqli_fetch_array($rMYSQLI_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?

  9. #9
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    364
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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'.



    HTML Code:
    <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?

    PHP Code:
    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.

  10. #10
    Grüße aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,000
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Ok, so if I understand you correctly, you're asking how to pass multiple parameters to your PHP script?

    That would be this:

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

    Does that help?

  11. #11
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    364
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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!

  12. #12
    Grüße aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,000
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    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.

  13. #13
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    364
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

  14. #14
    Grüße aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,000
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    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:

    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>
    Code:
    <?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/1...able-in-jquery
    http://coding.smashingmagazine.com/2...table-designs/
    http://tympanus.net/codrops/2012/11/...ling-with-css/
    Last edited by Pullo; Nov 22, 2013 at 07:39. Reason: Added references

  15. #15
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    364
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  16. #16
    Grüße aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,000
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    Quote Originally Posted by RedBishop View Post
    I hope this hasn't taken up too much of your time.
    No problems, man.
    It was fun to piece together.

    Quote Originally Posted by RedBishop View Post
    If you have a spare moment, may I just ask where "TRUE" in the statement $where = ' WHERE TRUE'; comes from?
    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?

  17. #17
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    364
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok, got it! Thanks for the speedy reply.

    Enjoy the weekend!

  18. #18
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    364
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

    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:

    Code:
     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:
    PHP Code:
    if (isset($_POST['fruit'])){

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


    HTML Code:
     <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> 

  19. #19
    Grüße aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,000
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    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.

    Code:
    <!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>

  20. #20
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    364
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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!!

  21. #21
    Grüße aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,000
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    Quote Originally Posted by RedBishop View Post
    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?
    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?

    Quote Originally Posted by RedBishop View Post
    Do I need to include console.log?
    No, this is just to demonstrate what the variables would contain at this point.

  22. #22
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    364
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey Pullo,

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

    PHP Code:
    $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.


    PHP Code:
     if (isset($_POST['fruit'])){

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



  23. #23
    Grüße aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,000
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Quote Originally Posted by RedBishop View Post
    could please show me how to pass the checkbox values so that I can retrieve those with my current PHP code
    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:

    Code JavaScript:
    // 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:

    Code JavaScript:
    $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:

    Code JavaScript:
    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

    Here's the complete code:

    index.html
    Code:
    <!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
    Code:
    <?php 
      print_r($_POST);
    ?>

  24. #24
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    364
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Morning Pullo,

    thank you so much for helping me and for explaining what the code is doing. 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.

  25. #25
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    364
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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'.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •