How to retrieve value from database on check box click? - javascript

Hi i have three check box where i want that which one check box i select regarding that check box value should retrieve from database
Here is my check box
<input type="checkbox" name="test" value="X-Ray" style="margin-top:10px;margin-left:120px;"><label>X-Ray</label>
<input type="checkbox" name="test" value="Ecg" style="margin-top:10px;margin-left:20px;"><label>ECG</label>
<input type="checkbox" name="test" value="Blood Test" style="margin-top:10px;margin-left:20px;"><label>Blood Test</label>
mysql query
SELECT SUM(price) from test where test='x-ray' or test='' or test='bloodtest'
how can i get my desired output? Any help will be appreciated.

You could get a hold on the specific input checkbox using the jquery selector :checked. So something like this in your javascript should get you started :
$( "input" ).on( "click", function() {
var sel = $( "input:checked" ).val();
//Here you can just make a simple ajax request to a php script passing the
//specific checkbox value and let that script perform the mysql query.
$.post( "test.php", { test: sel })
.done(function( data ) {
alert( "Completed");
});
});
Your test.php script could look something like this:
<?php
$test = $_POST["test"];
//Replace with your sql database credentials
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT SUM(price) from test where test='".$test."'");
mysqli_close($con);
?>
This is a barebone starting template of how you could proceed with your problem. Ofcourse, the specific use case could vary. For instance you could make a get request instead of a post request and make your php script interact and fetch data differently.
I just gave you an example of how the workflow would look like in simple jquery and php. So you just get the value of input checkbox and pass on the value to a script that interacts with the database and fetches the specific SUM. You should probably read some documentation on Jquery Ajax or PHP Mysql to get a better hang of this. Hope it helps.

I think that the best solution to this is to output all the prices as a JavaScript variable somewhere on the page, Let's alter the HTML a little bit.
<input type="checkbox" class="chkbox-update" name="test" value="X-Ray"><label>X-Ray</label>
<input type="checkbox" class="chkbox-update" name="test" value="Ecg"><label>ECG</label>
<input type="checkbox" class="chkbox-update" name="test" value="Blood Test"><label>Blood Test</label>
Now, the prices. Use PDO to itterate through results and construct a JSON-formatted variable:
<script>
var prices = {"X-ray": 3900, "ECG": 2000, "Blood Test": 1200};
</script>
Then use JavaScript to update the price field, I'm using jQuery for this.
$('.chkbox-update').click(function() {
var total;
$.each($('.chkbox-update'), function(k,v) {
total += prices[$(this).val()];
});
$('#result').text('The total price is '+total);
});
Make Sure that the key for the prices variable matches the value of the <input>

Related

How to send a selected (out of many) input values to DB using ajax?

first post so be gentle :)... OK, I'm trying to create a very simple inventory ordering site, but i'm having issues with the following:
Let's say you have (n) items in your inventory, so based on that number i run a 'for' loop and list a hidden input field with an ID of that inventory item and display a button to order. For example:
<form>
for ($i=0; $i<$num_items;$i++) {
<input type="hidden" name="item" value="<?=$ID[$i]?>">
<input type="submit" value="Order" onclick="InsertIntoDB()">
}
</form>
Now, lets say a user want to order only 2 item out of 5 in inventory. They would click on corresponding "Order" buttons and the appropriate hidden input values would be send to DB without redirecting (it would be a seamless experience for a user where once the user clicks on buttons they want the page will not reload or redirect). Here's the script that i have for the button click:
<script type="text/javascript">
function InsertIntoDB (){
var order = $('form input[name="item"]').val();
$.post('send_to_DB.php', {updateDB:order} ); }
</script>
This is what i have for send_to_DB.php file:
|code for connecting to DB|
$writetoDB=$_POST['uptadeDB'];
foreach ($writetoDB as $n) {
$insert = "UPDATE `test` SET onorder=1 WHERE ID='$n'";
mysql_query(insert);
}
I am struggling to get those 2 values that user clicked into the DB. Any help would be much appreciated, lost many hours of sleep due to this one :). Thanks!!!
The form will send values for all the inputs in it. One way of overcoming this could be trying to enclose each set of inputs in its own uniquely identified form inside the iteration loop. But consider the following solution which will achieve the required purpose without using a form, and with a single button instead of two inputs for each item:
For the the inputs in the test.php file, assuming that array $ID is already defined:
<?php
$num_items = count($ID);
for ($i=0; $i<$num_items;$i++) {
?>
<button type="button" value="<?=$ID[$i]?>" onclick="InsertIntoDB(this.value)">Order<?= $i + 1 ?></button>
<?php } ?>
For the posting script in the test.php file:
<script type="text/javascript">
function InsertIntoDB (order){
$.post('send_to_DB.php', {updateDB:order} );
}
</script>
For the handler send_to_DB.php file:
$writetoDB=$_POST['updateDB'];
$insert = "UPDATE `test` SET onorder=1 WHERE ID='$writetoDB'";
mysql_query($insert);
In the above $insert query, you might want to use SET onorder = 1 + onorder in order to keep track of the number of orders for each item.
However.......: I hope you are aware that we should stop using mysql_query: http://php.net/manual/en/function.mysql-query.php
Try this out
<form>
for ($i=0; $i<$num_items;$i++) {
//<input type="hidden" name="item" value="<?=$ID[$i]?>">
<input type="submit" value="Order" onclick="InsertIntoDB(<?=$ID[$i]?>)">
}
</form>
So that in your script you can try this
<script type="text/javascript">
function InsertIntoDB (order){
$.post('send_to_DB.php', {updateDB:order} );
}
Where order will now have the value id of the selected order

Dynamic form PHP / Javascript

Code is below.... I have dropdown menu - that is using PHP to query SQL, in order to populate the dropdown menu options, which is working fine.
You will see below - the sql query is statically configured, I would like to make this more dynamic.
Ideally id like another drop down menu on the same page with statically configured country options, and then when the customer selects which country my PHP script updates with the country in the sql query that php is using....
So for example where in my script below it says;
WHERE country ='SE'
I want it to populate with which ever country the user has selected in the pull down menu, so it could be 'FR', 'DE' or whatever country code has been selected.
I suspect this may be javascript? or maybe php can do this...?
I'm very much a novice level - so if you can be of assistance as much detail, or script as possible please :)
<html>
<body>
<form name="search" action="\cgi-bin\eu.py" method="get">
<?php
require_once 'db.inc.php';
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$sqlSelect="SELECT * FROM clnts WHERE country ='SE' ORDER BY clnt_name";
$result = $mysqli -> query ($sqlSelect);
if(mysqli_num_rows($result)){
$select= '<select name="select">';
while($rs=mysqli_fetch_array($result)){
$select.='<option value="'.$rs['mgmt_ip'].'">'.$rs['clnt_name'].'</option>';
}
}
$select.='</select>';
echo $select;
?>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
You can POST the selected dropdown value to the same page. You can do this automatically by using an 'onChange()' event on the dropdown menu.
Use this to POST to the same page and then get the value for the selected option and use that in your query...
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
add this at the top of you PHP....
if(isset($_POST['select']))
{
$selected_country_var = " country = '" . $_POST['select'] . "' ";
}else
{
$selected_country_var = " ";
}
edit your query to ...
$sqlSelect="SELECT * FROM clnts WHERE" . $selected_country_var . " ORDER BY clnt_name";
now edit your option/dropdown to have the onChnange event...
<select name="select" onchange="this.form.submit()">';
Let me know if I should clarify or if you need additional functionality.
It's usually not a "clean" solution to put together both server and client side code on the same page.
It's actually a better practice to put the server code on a seprate file for example 'handler.php' or 'api.php' and then call it using XMLHttpRequest (more commonly known as AJAX) ...
then, when using ajax you can pass data to the server using POST or GET variables and have it process the data.
that way you can create client side which is more fluent, and communication between the server and the client will be more "tidy"
in your case if you have say 'handler.php' on the server and use jquery ajax you could do something like :
client.html
$.ajax({
url : 'path_to_handler.php',
method : 'POST',
data : { countryCode : 'IL', otherVar : 1 },
onSuccess : function(result){
// do whatever with the data
}
});
and on the server
handler.php
if( isset($_POST['contryCode']) ){
// query the db and have the result returned as json
echo json_encode($result_query);
}

multiple number of php queries based on js clicks

I am fairly new to js. Here I have a js script that adds a text box input on click for queries to a database using php based mysql. Each new added textbox has an id name with a successive number at the end for the number of added text boxes from the js button, like id_0, id_1, etc. I am wondering if its possible to run the php query for each successive textbox individually. The problem I am having is keeping track of how many new text boxes have been added to know how many iterations of the query I should run since the click number is a js variable. Is there a way to iterate a php query based on the number of js clicks, or specifically, a js variable? (or am i think of doing this in the wrong way?)
script to add input box:
<input id="btnAdd" type="button" value="Add" />
<br />
<br />
<div id="TextBoxContainer">
</div>
<br />
<input id="btnGet" type="button" value="Get Values" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var click_number = 0;
$("#btnAdd").bind("click", function () {
var div = $("<div />");
click_number++;
console.log(click_number);
div.html(GetDynamicTextBox("id"+click_number));
$("#TextBoxContainer").append(div);
});
$("body").on("click", ".remove", function () {
$(this).closest("div").remove();
click_number--;
console.log(click_number);
});
});
function GetDynamicTextBox(value0) {
return '<label>Input <textarea rows="1" name="id_'+ value0 +'"><?php echo $_POST["id_'+ value0 +'"]; ?></textarea></label> ';
}
</script>
for the php part, I turn the $_POST variable into a php variable and run a simple query to the database matching the php variable to a specific column. So far I can only do this if I know how many $_POST variables there will be.
The way I do this (it may not be the best way), is to have a hidden HTML input which contains the number of textboxes you have created. Each time you add a new text box in JS you increment the value of your hidden input.
Then you can make a loop in PHP to get each POST element.
You don't need to know how many $_POST variables there are if you write the query dynamically. Just be sure that all your POST indexes match up with column names in the table:
For example, if you have:
$_POST['name']="bob"
$_POST['age'] = "102"
You can dynamically turn that into a query..
// First, for security, we should create an array
// with column names to check against to avoid SQL injection
$tableColumns = array("name", "age", "birthday", "favorite_color");
// This will contain the data that we want to insert
$insertables = array();
// Get the data from the post variables that
// are named after columns in our table
foreach($_POST as $k->$v)
if(in_array($k, $insertables))
$insertables[$k] = $v;
// Create a a query dynamically
// I'm assuming you're using PDO since you didn't specify
$sql = $pod->prepare("INSERT INTO `table` (`".implode("`, `", array_keys($insertables))."`) VALUES (:".implode(", :", array_keys($insertables)).")");
// Execute it
$sql->execute($insertables);
Now you can send any POST data you want and if the POST key exists as a column in the table it will be inserted.

How to GET value from an input checkbox to use it in a query to show information

I'm trying to GET information about rooms and towers in an orientation system. It is a search device throw checkboxes. The point is to select each option to filter the information retrived from the database.
The problem is that the values i'm trying to GET are not even echoing, so I can't use them in the query. On the other hand they are showing in the URL and if I add a submit button I can GET the information I want, but the idea here is to get the information instantly without the button.
This is the refresh code i'm using
var auto_refresh = setInterval(
function()
{
$("#results").load("searchroom.php").fadeIn("slow");
}, 1000);
$.ajaxSetup({ cache: false });
This is how i'm saving the values that are selected in the URL
$('input[type="checkbox"]').on('change', function(e){
var data = $('input[type="checkbox"]').serialize(),
loc = $('<a>', {href:window.location})[0];
$.post('/showbytipo.php?'+data);
if(history.pushState){
history.pushState(null, null, loc.pathname+'?'+data);
}
});
This are the HTML inputs
<form method="GET" action="searchroom.php" id="myform" name="myform">
<p>TIPOLOGIA</p>
<ul>
<li><input class="tipologia" id="tipologia"name="tipologia" type="checkbox" value="services" ><label>Serviços</label></li>
<li><input class="tipologia" name="tipologia" type="checkbox" value="class"><label>class</label></li>
</ul>
<p>TORRE</p>
<ul>
<li><input class="torre" name="torre" value="a" type="checkbox" value="a" ><label>A</label></li>
<li><input class="torre" name="torre" value="b" type="checkbox" value="b"><label>b</label></li>
</ul>
</form>
<div id="results" >
</div>
This is the PHP code to GET the values from the url
<?php
include("connect.php");
$tipo=$_GET['tipologia'];
echo $tipo;
$torre=$_GET['torre'];
echo $torre;
//$tipo='services';
$sql = "select * from rooms where tower='$torre' AND floor='$piso' AND typology='$tipo'";
//$sql = "select * from rooms where typology='$tipo'";
$query = mysql_query($sql) or die ("erro na query");
while($row = mysql_fetch_array($query)) {
echo $row["name"];
echo $row["tower"];
echo $row["typology"];
}
echo 'ola';
?>
Apart from that you have serious security issues by having get variables straight to your query, your input fields are named the same. e.g.: name="tipologia" and name="torre" has 2 instances and in the url only the second one will take effect (if it's selected).
If you want to pass multiple values your names should be like: name="tipologia[]" and this way you will see them in php as an array.
Also I know it's irrelevant, but why you are using $.post since you want to pass the values as get? Why don't you use $.get instead?
Edit:
I didn't saw that refresh part of the question.
You don't pass any variables in the refresh call if you want to pass variables the code should be like:
var auto_refresh = setInterval(
function()
{
$("#results").load("searchroom.php", $('#myform').serialize()).fadeIn("slow");}, 1000);
$.ajaxSetup({ cache: false });
I hope you know what are you doing, because the whole concept with refresh is quite messy to me, but still you have problem with the empty values from checkboxes:
You should have a javascript code which update a separate hidden field, which hold the state of the tipologia or torre fields. otherwise you can't rely on the checkboxes, their value will be always the last one checkbox.
Of course the easiest way is to use radio buttons and then you won't have this problem with the hidden field.
For debugging the variables you should use var_dump($_GET['torre']) and it will give you exactly what is in it. So, if it's empty you should see it or if it's undefined you will see null.
hope that helps.

checkbox error in editing using php

I just wanted to share my problem regarding checkbox here, because i know many can help me here. i have an array of checkboxes named skills[] and i stored the checked checkbox in a single column in my database because this is an application form project. I use implode() to separate the skills selected in the database by:
$skills = implode(',',$skills);
now this is my real problem because I don't have any idea how to retrieve the checked checkboxes in the database because whenever i will try to edit my checked checkbox. nothing in the checkboxes are checked even though the values are in the database.
the php code for getting the value of skills:
$skills = $wpdb->get_results("SELECT skills FROM php_employee_skills WHERE id=13");
if($skills!=null){
foreach($skills as $value):
$skills=$value->skills;
endforeach;
}else{
echo"<div class='updated' style='height:50px; font-size:12px;'>"."<br>".$message." in table skills in database"."</div>";
}
I dont have any idea what to put here in my html code to retrieve the data:
<td><input type="checkbox" name="skills[]" Value="C# Java" class="cbox">C# Java</td>
note: the skills in the application form which is in the form of checkbox are more than 10 so i use implode to save them in my database. is it right to use implode or explode in the situation of my application form?
Like this?
$str="php,mysql,java";
$skills=explode(",",$str);
//print_r($str2);
foreach ($skills as $chk)
{
echo '<input type="checkbox" value="'.$chk.'">'. $chk."\n";
}
Add checked attribute for checked checkbox
<td><input type="checkbox" name="skills[]" Value="C# Java" class="cbox" checked>C# Java</td>
that's no problem if you working only in the checkbox. but if you trying to list who have specified "skill" in database, you should separate them.
if ( $skills != null ) {
foreach ( $skills as $skill) {
....
}
}
Please make sure you read about coding standards in WP. It can improve your code to follow them.
Now, the next problem ist that you need a way to identify your skill:
<td><input type="checkbox" name="skills[]" value="C# Java" class="cbox" <?php echo (in_array('C# Java', $skills) ? 'checked' : '' ) ?> /> C# Java</td>
In this line, you check if the skill is in your skillset. If so, you add the checked attribute, else nothing happens.

Categories