So far I have been able to get data from MYSQL and display it as a checklist using PHP and HTML. Now I would like to limit the number of checkboxes that can be selected at a time. Javascript doesn't seem to be working with my PHP code.
EDIT: I've included my JScript below which is currently not workng. This JScript only works when I use it with manually created html checklists but not the one I have made below using MYSQL data. How can I fix my Javascript part so this works?
Here is my code:
<?php
$username = "root";
$password = "test";
$hostname = "localhost";
$dbname = "major_degrees";
$str='';
// Create connection
$conn = new mysqli($hostname, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT degree_name FROM majors";
$result = $conn->query($sql);
$out = '';
$cnt = 0;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$cnt++;
$out .= '<input id="cb_' .$cnt. '" class="someclass" type="checkbox" />' .$row['degree_name']. '<br/>';
}
echo $out;
}
$conn->close();
?>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<script>
$out.on("click", ":checkbox", function(event){
$(":checkbox:not(:checked)", this.form).prop("disabled", function(){
return $(this.form).find(":checkbox:checked").length == 2;
});
});
</script>
try this:
<script>
$(".someclass").change(function() {
var count = $(".someclass:checked").length; //get count of checked checkboxes
if (count > 3) {
alert("Only 3 options allowed..!");
$(this).prop('checked', false); // turn this one off
}
});
</script>
Related
Im looking at outputting mysql query results into a table on a php page where the 1st column of the table is the result and the 2nd column is populated with a Javascript timer
however my goal is to have it so that when data comes into the mysql database it display on the table and then when it stops being picked up by the query remove it from the table
the issue i face however is im not sure how to do this without resetting the javascript timer everytime the query is run,
I have gone through a couple of questions that have mentioned to use ajax and this would be fine but im not sure what i would put the HTML side
EDIT:
the below is now my second attempt code using ajax but i cant get the table to display it errors as unexpected token < line 27
my current page load Code to call the data is as followed:
PHP
<?php
header('Content-type: application/json');
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
# header('Content-Type: applicaton/json');
$sql = "SELECT
*
FROM
(SELECT
beacon,location,
COUNT(location) AS counter
FROM `track`
WHERE `date` = CURDATE() and `time` > NOW() - interval 60 second
GROUP BY beacon) AS SubQueryTable
ORDER BY beacon + 0 ASC;";
$result = $conn->query($sql);
$result = mysqli_query($conn , $sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
$conn->close();
?>
HTML
$.get('vendor/fetch.php', function(response) {
console.log(response);
var row;
response.forEach(function(item, index) {
console.log(item);
(unexpexted token here)
<table id="table">
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr style="background-color: <?php echo $row['item.location'];?>">
<td><?php echo $row['item.beacon'];?></td>
<td> <span class='minutes'>00</span>:<span class='seconds'>00</span>
</td>
</tr>
<?php }
mysqli_close($con);
?>
</table>
});
});
function updateTable() {
//console.log('function called');
$.get('vendor/fetch.php', function(response) {
response.forEach(function(item, index) {
console.log(item.beacon);
});
});
var updateTableInterval = setInterval(updateTable, 100);
};
</script>
</head>
<body>
<script>
var sec = 0;
function pad(val) {
return val > 9 ? val : "0" + val;
}
var timer = setInterval(function () {
$(".seconds").html(pad(++sec % 60));
$(".minutes").html(pad(parseInt(sec / 60, 10)));
}, 1000);
</script>
</body>
I am trying to implement a dynamic drop-down list using Ajax and PHP. Based on the index value in the first option list, second one should give me list of names with that id.
select1.php :
<html>
<head>
<link rel="stylesheet" type="text/css" href="select_style.css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'fetch1.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("new_select").innerHTML=response;
}
});
}
</script>
</head>
<body>
<p id="heading">Dynamic Select Option Menu Using Ajax and PHP</p>
<center>
<div id="select_box">
<select onchange="fetch_select(this.value);">
<option>Select ID</option>
<?php
$host = 'localhost';
$user = 'admin';
$pass = 'admin';
$dbname='kancha';
$conn = new mysqli($host, $user, $pass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select distinct id from test";
$select= $conn->query($sql);
if ($select->num_rows > 0) {
while($row = $select->fetch_assoc()) {
echo "<option value='".$row['id']."'>".$row['id']."</option>";
//echo "<option value=>".$row['id']."</option>";
}
} else {
echo "0 results";
}
?>
</select>
<select id="new_select">
</select>
</div>
</center>
</body>
</html>
fetch1.php
<?php
if(isset($_POST['get_option']))
{
$host = 'localhost';
$user = 'admin';
$pass = 'admin';
$dbname='kancha';
$conn = new mysqli($host, $user, $pass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_POST['get_option'];
//echo '$id';
$sql = "select id, name from test where id='$id'";;
$find= $conn->query($sql);
if ($find->num_rows > 0) {
while($row = $find->fetch_assoc()) {
//echo "<option>".$row['name']."</option>";
echo "<option value='".$row['id']."'>".$row['name']."</option>";
}
} else {
echo "0 results";
}
exit;
}
?>
My database looks something like this :
SELECT * from test;
id name
1 Name1
2 Name2
1 Name3
The first drop down works just fine. However the second drop down isn't working.
I have attached the screenshot of it as well. Is there a problem in sending data across the files or what? Not able to figure out where has the code gone wrong.
For the second option list, when I have selected 1, I should be getting Name1 and Name3 as options but I get none.
EDIT: Corrected javascript in select1.php
You are setting the content for new_select with the wrong variable.
It should be response rather than val
Change to:
document.getElementById("new_select").innerHTML=response;
And assign value to your return options.
Like:
echo "<option value='".$row['id']."'>".$row['name']."</option>";
And change your sql string to the following for the above to work.
$sql = "select id, name from test where id='$id'";
And make sure your jquery.js include is being loaded.
Add value to the Option in selectbox, right now there is no value passing from the fetch_select()
After i searched for this solution on this site, nothing i found. Here is basic php code, just for testing.
index.php
<input type="checkbox" name="chk" id="chk" value="1" />
<button type="button" name="" id="submit">TEST</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var check = $('#chk').val();
$.ajax({
url:"qry.php",
method:"POST",
data: {check:check},
success:function(data)
{
//alert(data);
window.location.reload();
}
});
});
});
</script>
qry.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "check";
// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
if($_REQUEST['chk'] == true){
$stok = '1';
}
elseif ($_REQUEST['chk'] == false) {
$stok = '0';
}
$query = "INSERT INTO test(checked) VALUES('$stok')";
$result = mysqli_query($connect, $query);
if ($result === TRUE) {
echo "Zahtev je uspešno poslat!";
} else {
echo "Error: " . $query . "<br>" . $connect->error;
}
?>
How to set checkbox checked true or false into mysql and then echo if in html? It's always set to 0 in mysql boolen.
<input type="hidden" name="chk" id="chk" value="1" <?php if ($checked == '1') {echo 'checked';} else {} ?>/>
I tried everything from this site and nothing works.
Try this Jquery. This will get rid of the always value 1 problem you're having. What this code does is when you click on the "submit" button it check the status of your check box. If the check box is checked then the code will take the checked check box value and send that in the ajax function if it's not checked then the value 0 get assigned and that will be sent using the ajax.
Doing this will reduce the work has to be done by the back end PHP. I also made some changes to your PHP code as well.
$(document).ready(function() {
$(document).on('click', '#submit', function() {
if ($("#chk").is(":checked")) {
var chk = $('#chk').val();
}else{
chk = 0;
}
$.ajax({
url: "qry.php",
method: "POST",
data: {
check: chk
},
success: function(data) {
//alert(data);
window.location.reload();
}
});
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="chk" id="chk" value="1" />
<button type="button" name="" id="submit">TEST</button>
You will see that the way I'm inserting the data is a bit different from the way you have done. I'm using mysqli_ prepared statements which makes SQL injection a hard to do.
$query = $connect -> prepare("INSERT INTO test(checked) VALUES (?)";
$query -> bind_param("i", $_REQUEST['check']);
if ($query -> execute()) {
echo "Zahtev je uspešno poslat!";
} else {
echo "Error: " . $query . "<br>" . $connect->error;
}
jsFiddle if you want to test it.
You write the value into check, but read it back from $_REQUEST['chk']. That won't work. Change that to $_REQUEST['check'].
You are using val() to get the state of the checkbox, you should use checked.
Also, you are possibly open to SQL injection, start using prepared statements.
Add another line while sending the AJAX request.
While sending the value of checkbox, send 1 or 0.
It will reduce our work at PHP end.
So, the code should be:
var check = $('#chk').is(":checked");
check = (check) ? 1 : 0;
Final code should be:
<input type="checkbox" name="chk" id="chk" value="1" />
<button type="button" name="" id="submit">TEST</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var check = $('#chk').val();
check = (check) ? 1 : 0;
$.ajax({
url:"qry.php",
method:"POST",
data: {check:check},
success:function(data) {
//alert(data);
window.location.reload();
}
});
});
});
</script>
And PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "check";
// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
$stok = $_REQUEST['chk'];
$query = "INSERT INTO test(checked) VALUES('$stok')";
$result = mysqli_query($connect, $query);
if ($result === TRUE) {
echo "Zahtev je uspešno poslat!";
}
else {
echo "Error: " . $query . "<br>" . $connect->error;
}
?>
I have 2 php files one that retrieve from database, other one take each value came from the database. the problem: data is being sent as whole not row by row. so I can not have each value seperatly. I am trying to find smart way to do so.
first file:
$host = 'localhost';
$user = 'root';
$pass = '';
$db_name="bbbb";
$conn = new mysqli($host, $user, $pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$data = array(); // create an array
while( $row = $result->fetch_assoc()) {
echo $row ['input']; //if my database have 2 rows one with value t1 and other with t2.
}
?>
second file:
<script src = "https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script>
$(document).ready(function(){
retrieveData();
});
function retrieveData(){
$.post('quick.php',{}, function(data){
window.alert(data);
});
}
</script>
the output i have is a single alert with (t1 t2)
my desire output to be 2 alerts window. first one with value t1 second with value t2.
try This:
use json to your server side,
while( $row = $result->fetch_assoc()) {
echo json_encode($row['input']);
}
and on your second file:
$.post('quick.php',{}, function(data){
window.alert(data);
},"json");
I am trying to show data from the database in my textbox. But when I start the script I am getting no results. I tested the script in different ways and i figured out that the variable: $product1 is empty. Does anybody know how I can fix this?
index.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM forms";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control select2' id='product1' name='product1' onChange='getPrice(this.value)' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<body>
<!-- Your text input -->
<input id="product_name" type="text">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('.product1 option:selected').val();
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
</body>
</html>
get.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error)
{
die('Connection failed: ' . $conn->connect_error) ;
}
else
{
$product1 = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT) ;
$query = 'SELECT price FROM forms WHERE id=" . $product1 . " ' ;
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0)
{
$result = mysqli_fetch_assoc($res) ;
echo $result['price'];
}else{
echo 'no results';
}
}
?>
Change
var selectedItem = jQuery('.product1 option:selected').val();
To
var selectedItem = jQuery('#product1 option:selected').val();
You are selecting a class with name product1, but you set only an ID with this name. Id's are specified with # and classes with .
Update on your script, because you used getPrice(this.value);
<script>
function getPrice(selectedItem) {
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
TIP:
Did you know that you can use jQuery.ajax and jQuery('selector') also like this: $.ajax and $('selector') :-)
You have not a form tag in your HTML. The default form Method is GET.
In Your get.php you try to get a POST Variable with filter_input
The function filter_input returns null if the Variable is not set.
Two possible solutions:
1. Add a form to your html with method="post"
2. Change your php code to search for a GET variable