Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2361
  • Last Modified:

Checkbox On Check/Uncheck Update Database With jQuery

Hi Experts,

I am looking for a simple script to help solve a scripting idea of mine. I am looking for a simple script that when a checkbox is checked, the database is updated with the value, and when a checkbox is unchecked, the database is updated again without the value.

I'd like to be able to display this information in a box as well, so when a checkbox is checked, update database, query database again and show rows in box on page via jQuery without page refresh.

Can someone help guide me with a simple script? I appreciate your time and viewing of my post. Thank you.
0
SevenAteAnthony
Asked:
SevenAteAnthony
  • 8
  • 7
1 Solution
 
dkellnerCommented:
I give you the logic, hope you can adapt to your situation:
(iframe is only needed once for all checkboxes)

<iframe name="serverConn" style="display:none"></iframe>
<input type=checkbox onclick="serverConn.location='setvalue.php?value='+(this.checked?1:0)">

Now setvalue.php gets a request everytime your checkbox is clicked - and you can update your DB. Then, if you need a callback too, you can output something like:

<script> parent.myCallback("<?php print $successFlag ?>") </script>

...so that the iframe will run a javascript that calls your myCallback function on the original page.  This is useful if you want to acknowledge for the user that the update has happened.

Ask if you're not sure how it works.
0
 
SevenAteAnthonyAuthor Commented:
dkellner,

Thanks so much for your help. I've used your knowledge and have created 3 files as follows tweaking it to a bit more my standards needed for the script:

File 1: connect.php (used for database connection)

File 2: checkbox.php (used as UI)

<?php

include('connect.php');

?>
<html>

<head>

<title>
Checkbox On Checked Update Database With jQuery
</title>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>

<style type="text/css">
body {
font-family: Arial;
font-size: 12px;
}
.items {
border: 1px solid black;
width: 400px;
}
</style>

</head>

<body>

<div name="serverConn" class="items">
<?php echo $items; ?>
</div>

<br /><br />

<div style="height: 30px; width: 200px; border: 1px solid black;"><input type=checkbox onclick="serverConn.location='checkbox_update.php?value='+(this.checked?1:0)">Item 1</div>
<div style="height: 30px; width: 200px; border: 1px solid black;"><input type=checkbox onclick="serverConn.location='checkbox_update.php?value='+(this.checked?1:0)">Item 2</div>

</body>

</html>

Open in new window


File 3: checkbox_update.php (used for the SQL statements)

<?php

include('connect.php');

if (isset($_GET['value'])) {

$value = mysql_real_escape_string($_GET['value']);

mysql_query("INSERT INTO Items (ItemID, AccountID, Email) VALUES ('', '1', 'test@test.com')");

$getItemsQuery = mysql_query("SELECT * FROM Items WHERE AccountID='1'");

while ($getItems = mysql_fetch_array($getItemsQuery)) {

$itemID = $getItems['ItemID'];
$email = $getItems['Email'];

$items = "<p>ItemID: ".$itemID." | Email: ".$email."</p>";

}

}

?>

Open in new window


The script is currently not working, just my luck. Could you perhaps help me a bit further with this?

Thank you kindly.
0
 
dkellnerCommented:
I'm not sure what you're trying to achieve but as I see, you're using an INSERT statement so every click on the checkbox will add a new row instead of updating an existing one (as I thought it should).  Can you make this point clear for me?

I'd do something like this:

UPDATE foo SET switch='$value' WHERE ........

Now of course you can pass further values in $_GET so maybe you'll need a serverConn call like "checkbox_update.php?user=231545&option=newsletter&value=1" - to switch the newsletter reception of use 231545 to ON, for example.  Again, these are not real-life examples, just trying to show you what channels you have to pass your information.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
SevenAteAnthonyAuthor Commented:
Thanks for the further comment. My issue right now is the script isn't even inserting a new row. Perhaps you could please toss me a pointer as to why?

I'm adding multiple rows because it's items for multiple users, hence the AccountID tag, so the update statement with the switch wouldn't be possible, because there are thousands of items.

Any idea how I can get the script to process the PHP?
0
 
dkellnerCommented:
- What does MySQL say?  (output mysql_error() after the query)
- Field names are case sensitive.  Are they spelled exactly like this in the database?
- You're not using the $value (1/0 state of the checkbox) anywhere. Intentional?

0
 
SevenAteAnthonyAuthor Commented:
Thanks for noticing those issues. I will address. My hunch though is that the jQuery is not working itself. I just changed checkbox_update.php to just echo "Test"; and nothing came out. Is there anything wrong with the jQuery?
0
 
dkellnerCommented:
Whoa!  Now I see.  The IFRAME tag is missing.  The one named "serverConn".  You're referring to it but it's not there.

If you prefer AJAX btw, you can implement the same thing with it.  Many ppl like that way better. Me personally, I prefer IFRAMEs because they can easily be debugged (if you remove the display:none part, you'll see the iframe itself and you can use it as a debug screen), so let's just stick with it for now.

As I see you have more checkboxes, now what I wrote to you is just the principle of how to do this, but with more than 1 items you'll need to pass WHICH checkbox issued the call.  It's something like:

checkbox-update.php ? sender=cbx1 & value=...

(omit the spaces inside, they're for readability only)

It's important to not just copy/paste but UNDERSTAND what I write to you.  Maybe I even make a mistake sometimes - it would be a madness to always try everything -, but the logic of it all should be clear.  I don't want to give you a single fish but a whole fishing kit instead so that you do the rest :)

Let's see what happens!
I check back tomorrow (3:16am here)

0
 
SevenAteAnthonyAuthor Commented:
dkellner,

Thank you for the reply. Wow, I didn't realize that it HAD to be an iFrame tag. Must be something to do with that "location" part, huh? Is there anyway I could avoid iFrames and use a <div> tag? As I mentioned above when I put the code up here, I took your advice and coded it/changed it as to what I needed. I love jQuery, and I'm still trying to understand it and learn it the way I did other languages: but using it and testing it.

Anyway, how can I get that badboy to work with a <div>? I've got the PHP end covered: just wanted to get a barebones script going as I know the multiple checkboxes will need extra, of course.

Thank you so much for your help so far.
0
 
dkellnerCommented:
IFRAME in this case is not for displaying anything but to communicate with the server.  There's no need to have a DIV "instead of" the iframe since it will be invisible.

IFRAMEs are one way to communicate in the background.
AJAX is another.

Make an AJAX GET request with the same URL as you'd do with the IFRAME, and there you go.  The only difference is the callback style - I don't use AJAX so I can't help you with that.

The core part is to send a background request.  This can be done with any of the above.
0
 
SevenAteAnthonyAuthor Commented:
Thanks. My issue is, I don't want to hide the information in the "iFrame". I want to display is as it's updated to the user so they can see what is "in queue".

Another issue I noticed is that I can not display variables from checkbox_update.php in the iFrame?

I am looking for a jQuery solution to this. Is the code you've helped me with jQuery?

Thank you, dkellner.
0
 
dkellnerCommented:
You still don't seem to understand the role of the iframe here.  Don't mind it; it's only for something in the background.  What the user sees is up to you.

Check this example:

http://dkellner.hu/example016.php
0
 
SevenAteAnthonyAuthor Commented:
Okay, thanks. So I see what you've done there. However, I am a bit confused on how you've passing PHP variables over from the second page that processes the SQL...

Thank you so much for supplying such a wonderful demo to assist me. You are an Internet hero.
0
 
dkellnerCommented:
There are two demos on dkellner.hu
For both I provide you the source code.

http://dkellner.hu/example016.php  (using IFRAMEs)
<?php

if(!$_GET) {
	?>
	<title> Remote request demo for SevenAteAnthony / ExpertsExchange</title>
	<iframe name="sc" src="about:blank" style="display:none"></iframe>
	<input type=checkbox onclick="disp('Connecting to server...');sc.location='?cb=1&state='+(this.checked?1:0);"> Checkbox 1<br>
	<input type=checkbox onclick="disp('Connecting to server...');sc.location='?cb=2&state='+(this.checked?1:0);"> Checkbox 2<br>
	<input type=checkbox onclick="disp('Connecting to server...');sc.location='?cb=3&state='+(this.checked?1:0);"> Checkbox 3<br>
	<div id="display" style="border:1px solid silver;margin:10px;"></div>

	<script type='text/javascript'>

		function disp(s) {document.getElementById("display").innerHTML=s;}

	</script>
	<?
	exit;
}

usleep(500*1000);
$checkbox_number = $_GET["cb"];
$checkbox_state  = $_GET["state"];

?>
<script type='text/javascript'>

	parent.disp("Saved the fact that checkbox #<?=$checkbox_number?> is <?=$checkbox_state?"on":"off"?>");

</script>
<?

Open in new window


http://dkellner.hu/example017.php  (using AJAX)
<?php

if(!$_GET) {
	?>
	<script type='text/javascript' src='jquery.latest.js'></script>
	<title> Remote AJAX request demo for SevenAteAnthony / ExpertsExchange</title>
	<input type=checkbox onclick="saveCbxState(1,this.checked?1:0)"> Checkbox 1<br>
	<input type=checkbox onclick="saveCbxState(2,this.checked?1:0)"> Checkbox 2<br>
	<input type=checkbox onclick="saveCbxState(3,this.checked?1:0)"> Checkbox 3<br>
	<div id="display" style="border:1px solid silver;margin:10px;"></div>

	<script type='text/javascript'>

		function disp(s) {document.getElementById("display").innerHTML=s;}

		function saveCbxState(whichOne,setToWhat) {
			$.get("example017.php",{cb:whichOne,state:setToWhat},function(whatWeGot) {
				alert("Got response:\n''"+whatWeGot+"''");
			});
		}

	</script>
	<?
	exit;
}

usleep(500*1000);
$checkbox_number = $_GET["cb"];
$checkbox_state  = $_GET["state"];

?>
Saved the fact that checkbox #<?=$checkbox_number?> is <?=$checkbox_state?"on":"off"?>
<?

Open in new window


Both are simplified to death - just to make clear where the magic happens.
As you'll see there's little difference between the above - only HOW they call the server script.
Don't copy/paste things without knowing what they actually do!

In both examples, the script itself acts as the HTML form and the server that saves the values.  Don't be confused - or tell me if you are.
0
 
SevenAteAnthonyAuthor Commented:
Okay, that makes perfect sense, then. I see what you've done. Thanks very much for all your help and helping further my knowledge. I appreciate it highly.
0
 
dkellnerCommented:
:)
It's all in a day's work for Confuse-a-Cat!
(c) Monty Python
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

  • 8
  • 7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now