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?
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.
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?
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.
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?
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.
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:
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?
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’.
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’]}’”;}
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.
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:
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’]}’”;
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.
<?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.
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?
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.
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:
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'])){
}
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.
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?