I have a question how can I update the database if person unchecks or check a checkbox and update the boolean field
in mysql? For days stuck with this problem, because problem I don't know how to make a form or check if
it is validate inside of a while loop here is my code:
<?
$result= mysql_query("SELECT * FROM cars");
$counter = 1;
while($row = mysql_fetch_array($result)) {
echo '<tr>
<td>' . $counter++ . '</td>
<td><input type="checkbox"';
if ($row['show'] == true) {
echo 'checked></td>';
} else {
echo 'unchecked></td>';
}
echo '<td><img src="../xml/'.$row['cars_id'].'-1.JPG" width="120px"></td>';
echo "<td><h3> ", $row['brand']," " . $row['model'], " " . $row['type'],
" € " . $row['price'], " </h3></td>";
echo '</tr>';
}
?>
p.s. I am aware of the mysql to mysqli or pdo but it is a HUGE script...
Oh! No issue here is the solution:
Try using jquery and ajax. For example.
if ( $("#chkbx").prop('checked') == true) {
// do ajax call to update the database
} else {
// do anything if check box is unchecked
}
I am not writing the ajax call just see the jquery ajax manual. If you face any problem come back.
See the above code will create a event listener in the DOM so that when the check box is checked a event should fire.
Now I am extending my code to show you a ajax call.
if ( $("#chkbx").prop('checked') == true) {
$.ajax ({
method: "POST", // type:post or get
url: "test.php", // your php file
data: { name: "test"} // data that I want to send
}).done(function( msg ) {
alert( "Data Saved: " + msg ); // after success show msg
})
}
Now in the php file do the updating part of database or anything you want. The done function will show the msg you returned if the php file execute properly. There are numerous functions in ajax that you can use.Also try to use jquery it's handy and easy to use.
Thank you so much, now I only have to focus on how database works in Ajax
This is what I added and with this I can echo out that it does work now what rest is change the boolean value row['show']
<script type="text/javascript">
function change_checkbox(el){
if(el.checked){
alert("On");
}else{
alert("Off");
}
}
I got pretty far that all is working except for 1 particulair thing.
The problem what I now face is that I cannot send the DATA ID's from the checkbox to the test.php page how can I do this correct this is what I came up with so far:
<?
$result= mysql_query("SELECT * FROM cars");
$counter = 1;
while($row = mysql_fetch_array($result)){
echo '<tr>
<td>' . $counter++ . '</td>
<td><input id="'.$row['cars_id'].'" onchange="change_checkbox(this)" type="checkbox"';
if ($row['toon'] == true){
echo 'checked></td>';
}else
{
echo 'unchecked></td>';
}
echo '<td><img src="../xml/'.$row['cars_id'].'-1.JPG" width="120px"></td>';
echo "<td><h3> ", $row['brand']," " . $row['model'], " " . $row['type'], " € " . $row['price'], " </h3></td>";
echo '</tr>';
}
?>
</tbody>
</table>
</section>
<script type="text/javascript">
function change_checkbox(el){
var id = null;
if(el.checked){
alert("On");
$.ajax ({
method: "POST", // type:post or get
url: "test.php", // your php file
data: { id: id } // data that I want to send
}).done(function( msg ) {
alert( "Data Saved: " + msg ); // after success show msg
})
}else{
alert("Off");
$.ajax ({
method: "POST", // type:post or get
url: "test.php", // your php file
data: { name: "test"} // data that I want to send
}).done(function( msg ) {
alert( "Data Saved: " + msg ); // after success show msg
})
}
}
Related
I have a page on my website with a 20 checkboxes for each user that has an account, i want to be able to submit the checkbox when it is changed to save it to a DB. Its hard to explain, but i will attach screenshots of the code, HTML output and DB:
PHP code to get the boxes is:
<?php
for ($x = 1; $x <= 16; $x++) {
$result0 = $db->query("SELECT * FROM View WHERE `UserID` LIKE '" . $x . "'");
while($row0 = mysqli_fetch_array($result0)) {
if($row0['20']=="1"){$checked = "checked";}else { $checked = "";}}
echo "<td class=\"align_center\"><input type=\"checkbox\" name=\"20_" . $x . "\" " . $checked . "/>
";}
?>
Im hoping someone can help! PLEASE!
Thanks
The below ajax request would trigger on each checkbox change event.
You will need a PHP script to recieve the data and update your DB.
Look Ajax documentation for more details.
$("input[type='checkbox']").on("change",function(){
$.ajax({
url: "someFileToUpdateDB.php",
data: $("#myForm").serialize(),
success: function(){
console.log("Change saved.");
},
error: function(request,status,error){
console.log("ERROR: "+error);
}
});
});
I've been working on this problem for a few hours, but there is some mistake somewhere in the javascript file (I believe), but I can't figure it out.
Right now the alert(msg) gives me an Undefined index: headline/text in editPost.php.
The following PHP code is in a file profile.php. I want to retrieve the data within the <div>I want this data</div> tags (i.e. I want to retrieve the data in $row['headline'] and $row['text'].
while ($row = mysqli_fetch_array ($resultPost, MYSQLI_ASSOC)) {
echo '<h1><div contenteditable="true" data-headline="headline" data-id=' . $row['id'] . '>' . $row['headline'] . '</div></h1>';
echo '<p><div contenteditable="true" data-text="text" data-id=' . $row['id'] . '>' . $row['text'] . '</div></p>';
}
This is how I try to retrieve the data (seperate .js file):
$(document).ready(function() {
$('body').on('blur', "div[contenteditable=true]", function() {
var headline = $("div[data-name='headline']:visible").text();
var text = $("div[data-name='text']:visible").text();
$.ajax({
type: 'POST',
url: 'editPost.php',
data: {
content: $.trim($(this).text()),
id: $(this).data('id'),
headline: $(this).data(headline),
text: $(this).data(text),
},
success: function(msg) {
alert(msg);
}
});
});
});
The function above then posts the data to editPost.php, which submits the data to a database. Below is a snippet of how I do that:
$headline = $_POST['headline'];
$text = $_POST['text'];
$id = $_POST['id'];
$sql = "UPDATE blogpost SET headline = '$headline', text = '$text', edit_time = NOW(6) WHERE id = '$id'";
In the current state, when the data is sent to the database, it finds the correct table (using the id), and inserts "" in both the headline and text fields, but it updates the edit_time correctly.
Thank you!
I took a break for a few hours, and came back with more thoughts on how to solve it. After a little tweaking here and there, I finally did it.
For those of you who visit this thread at a later time, this is what I changed in order for it to work:
My profile.php snippet is now like this (I switched data-headline="headline" to name="headline" etc.):
while ($row = mysqli_fetch_array ($resultPost, MYSQLI_ASSOC)) {
echo '<h1><div contenteditable="true" name="headline" data-id=' . $row['id'] . '>' . $row['headline'] . '</div></h1>';
echo '<p><div contenteditable="true" name="text" data-id=' . $row['id'] . '>' . $row['text'] . '</div></p>';
}
My javascript file now consists of two functions with minor differences (one for each field). Yes, I'm certain there is a better way to solve this:
$(document).ready(function() {
$('body').on('blur', "div[name=headline]", function() {
var headline = $("div[name='headline']:visible").text();
$.ajax({
type: 'POST',
url: 'editPost.php',
data: {
headlineContent: $.trim($(this).text()),
id: $(this).data('id'),
headline: $(this).data(headline),
},
success: function(msg) {
alert(headline);
}
});
});
});
$(document).ready(function() {
$('body').on('blur', "div[name=text]", function() {
var text = $("div[name='text']:visible").text();
$.ajax({
type: 'POST',
url: 'editPost.php',
data: {
textContent: $.trim($(this).text()),
id: $(this).data('id'),
text: $(this).data(text),
},
success: function(msg) {
alert(text);
}
});
});
});
I changed how the elements were targeted, so targeting one element wouldn't duplicate the content over to the other element.
Finally, in my editPost.php file, I added a check to see whether or not a variable is empty. If it is empty, that means the element didn't get updated, hence why it only updates the other element.
$headline = $_POST['headlineContent'];
$text = $_POST['textContent'];
$id = $_POST['id'];
if (!empty($headline)) {
$sql = "UPDATE blogpost SET headline = '$headline', edit_time = NOW(6) WHERE id = '$id'";
} elseif (!empty($text)) {
$sql = "UPDATE blogpost SET text = '$text', edit_time = NOW(6) WHERE id = '$id'";
}
As you can see, the code itself is far from perfect (pretty horrible actually), but it works for now. I'll definitely try to improve on it in the future, but any feedback would be appreciated (I am aware this is not the place for codereview).
I'm using a star ratings system to display rating data from SQL. Each item that can be rated has unique identifyer variable $id and each rating in ratings tabl has unique identifyer $storyidr. I would like this script to display:
the average rating
the number of times the item has been rated.
The values are retirevable but they display on the page together and I can't see how to seperate them. FOr example, for an item that has an average rating of 4 and has been rated 200 times. when user clicks the data returns via AJAX looking like:
For 'response1' 4"200"
For 'response2' 4"200"
I would like to be able to seperate them to look like:
For 'response1' 4
For 'response2' 200
html page
<div id="products" style="">
<div class="rateit" data-storyidr="<?php echo $id; ?>">
</div>
<div class="averagevote">
<div style="display:block;" id="response<?php echo $id; ?>"><?php echo $avgratep; ?></div><br>
<div style="display:block;" id="response2<?php echo $id; ?>">RaTeD <?php echo $rankcount; ?> TiMeS</div>
</div>
</div>
<?php endwhile; mysqli_close($connection); ?>
<script type ="text/javascript">
$('#currentslide .rateit').bind('rated reset', function (e) {
var ri = $(this);
var value = ri.rateit('value');
var storyidr = ri.data('storyidr');
ri.rateit('readonly', true);
$.ajax({
dataType : 'json',
url: 'rate.php',
data: {storyidr: storyidr, value: value},
type: 'POST',
success: function (data) {
$('#response'+storyidr).replaceWith('Avg rating ' + data.avg + '/5');
$('#response2'+storyidr).replaceWith('Rated ' + data.cnt + ' times');
},
error: function (jxhr, msg, err) {
$('#response').append('<li style="color:red">' + msg + '</li>');
}
});
});
</script>
PHP
<?PHP
$storyidr=$_POST['storyidr'];
$mysqli = mysqli_connect($dbhost,$dbusername,$dbpasswd,$database_name) or die ("Couldn't connect to server.");
if (mysqli_connect_errno($mysqli))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO ratings (storyidr, rank, entry_date) VALUES ('$_POST[storyidr]','$_POST[value]',now());";
$sql .= "SELECT AVG(rank) AS avrank, COUNT(rank) AS countrank FROM ratings WHERE storyidr = $storyidr";
if($mysqli->multi_query($sql))
{ $mysqli->next_result();
if ($result = $mysqli->store_result())
{
$data = mysqli_fetch_assoc($result);
$avrank = $data['avrank'];
$countrank = $data['countrank'];
$avrankr = round($avrank,2);
if(is_null($avrank)){$avrank ="null";}
echo json_encode(array('avg' => $avrankr, 'cnt' => $countrank));
}
}
?>
You should only use json_encode() once and only echo the result of that function. Doing it more than once invalidates your json:
else
{
$results = array();
$results['av'] = $avrankr;
$results['cnt'] = $countrank;
echo json_encode($results);
}
Then, in your javascript, you can access data.av and data.cnt directly:
$('#response'+storyidr).replaceWith('Avg rating ' + data.av +'/5');
$('#response2'+storyidr).replaceWith(data.cnt);
You could also set the dataType parameter in your ajax call as mentioned by #barell, but normally jQuery will figure that out correctly already.
Edit: To avoid the undefined errors you are getting you should do something like:
$results = array('status' => 'fail');
...
if () {
...
if ($result)
{
$results['status'] = 'success';
$results['av'] = $avrankr;
$results['cnt'] = $countrank;
}
}
echo json_encode($results);
Now you can check for data.status first in the success callback of your ajax call and take the appropriate action:
success: function (data) {
if (data.status === 'fail') {
// show a warning message somewhere, this is just an example
alert('No results found!');
} else {
$('#response'+storyidr).replaceWith('Avg rating ' + data.av + '/5');
$('#response2'+storyidr).replaceWith('RaTeD ' + data.cnt + ' TiMeS');
}
},
I think the problem is you don't set the correct header. In the php file, before any output, put this:
header('Content-type: text/json');
And also, instead of write two objects, write it as an array:
echo json_encode(array('avg' => $avrankr, 'cnt' => $countrank));
Now it should work
Then, in your Javascript you will access this data like this:
$('#response'+storyidr).replaceWith('Avg rating ' + data.avg +'/5');
$('#response'+storyidr).replaceWith(data.cnt); // Suppose you want the count here
Strange things happen often.
The code works fine but when I alert the PHP echo from javascript it displays like this:
"< html > Login başarılı. < /html >"
click to view the screenshot
How can I get rid of that html tag in the message?
This is my javascript:
var dataString = 'user_eposta='+ eposta + '&user_sifre=' + sifre;
$.ajax({
type: "POST",
url: "bin/login.php",
data: dataString,
success: function(mesaj) {
alert(mesaj);
}
});
and this is the PHP:
<?php
$con=mysqli_connect("pantuff.com","ttoykoc","*******","db_pantuff");
if (mysqli_connect_errno($con))
{
echo "MySQL Bağlantısı yapılamıyor." . mysqli_connect_error();
} else
{
$result = mysqli_query($con,"SELECT * FROM member");
while($row = mysqli_fetch_array($result))
{
if ($row['user_eposta'] == $_POST['user_eposta'] && $row['user_sifre'] ==
$_POST['user_sifre'])
{
$adsoyad = $row['user_ad'] . " " . $row['user_soyad'];
$_SESSION['username']= $adsoyad;
setcookie("currentuser", $adsoyad, time()+(84600*30));
echo "Login başarılı.";
} else
{
echo "Kullanıcı adı ya da şifre hatalı!";
}
}
}
mysqli_close($con);
?>
alert($(mesaj).text());
alert($(mesaj).html());
$(mesaj) builds a jQuery object from html. Then text or html function fetches the message, where html gets the message with html entities in it, while text contains no entities.
A different solution, as proposed above in the comments:
Add header("Content-Type: text/plain"); in line 2 of the file outputting the text, and:
var dataString = 'user_eposta='+ eposta + '&user_sifre=' + sifre;
$.ajax({
type: "POST",
url: "bin/login.php",
data: dataString,
dataType: 'text',
success: function(mesaj) {
alert(mesaj);
}
});
So I have a php page that gets data from database and displays a table. Each td symbolises a seat in a movie theater. What i want to do is when a user clicks on one or more tds, and clicks send, the status column for each td in the database changes to 1 from 0(default). When the database is accessed next time, the td's with status=1 have a different color.
My code upto now is:
<div id="screen">SCREEN</div>
<div id="Seatings">
<?php echo "<table border='1'>
<tr>
<th>Seating</th>
</tr>";
$count=0;
echo "<tr>";
echo"<td id='Seat_rn'>A</td>";
while($row = mysql_fetch_array($sql))
{
if($count<10){
echo "<td id='Seat_A' class='count'>" . $row['Seat'] . "</td>";
}
$count++;
}
echo "</tr>";
$sql=mysql_query("SELECT * FROM Seating_para_20 Where Seat > '10'");
echo "<tr>";
echo"<td id='Seat_rn'>B</td>";
while($row = mysql_fetch_array($sql))
{
if($count>=10){
echo "<td id='Seat_B' class='count'>" . $row['Seat'] . "</td>";
}
$count++;
}
echo"</tr>";
echo "</table>";
?>
</div>
<input type="button" value="Done" name="done" onclick="window.close()">
My jquery code is:
$("td #Seat_A").click(function(){
$(this).css("background", "red");
});
$("td #Seat_B").click(function(){
$(this).css("background", "red");
});
$(document."done").click(function(){
alert(price:750 Baht);
})
I am nowhere near what i want and I'm sorry if any of my code is "amatuer-ish" but I am new to this and I have been trying very hard. Would appreciate any help that I can get.
First of all you have to add an ID to every TD on your table, i.e. Seat ID, For example:
echo "<td id='Seat_A' data-seat='". $row['id'] ."'class='count'>" . $row['Seat'] . "</td>";
Then send this ID to your PHP script with Ajax:
$("td #Seat_A").click(function(){
var seat_number = $(this).data("seat");
$.ajax({
type: 'POST',
url: "/take_a_seat.php",
data: 'seat_number='+seat_number,
success: function(data){
$(this).css("background", "red");
}
dataType: "json"
});
});
On the PHP script you have to do what you want to the seat with this ID and return true or false as a result. Let's suppose you have a field named reserved in your database table. You can get the unique ID and update that row to reserved = 1 for example.
Try this easy to use ajax script to accomplish your task
Features: you can show an gif img before send data to db in beforeSend section get response from php file in success section hide img after data inset in db in complete section and show successful or not success msg
var myVar = 'your desire data you want to send to db';
$.ajax({
type: "POST",
url:"scripts/dummy.php",
data:"myVar="+myVar,
beforeSend: function()
{
},
success: function(resp)
{
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
}); //end Ajax
Javascript is client side. Your database is server side.. So you have to use php to change your database entries.
In short, if you want to execute PHP stuff without reloading page, than use AJAX. You can use it with your favorite JQuery.
This is an overview. For existing records you should some thing like this
<?php
$count=1;
$res = mysql_query("SELECT * FROM Seating_para_20 Where Seat > '10'");
while($row = mysql_fetch_array($sql)) {
if($row['status']==1) {
$tdcolor = 'red';
} else {
$tdcolor = 'blue';
}
?>
<td id="td-<?php echo $count;?>" sytle="background-color:<?php echo $tdcolor; ?>" onclick="reserveseat(<?php echo $count; ?>);" >
<?php
$count++;
}
?>
For changing after page load you will do ajax operation
<script type="text/javascript" language="javascript">
function reserveseat(count) {
$.ajax({
type: 'POST',
url: "bookseat.php",
data: '',
success: function(data){
$("#td-"+count).css("background-color", "red");
}
});
}
</script>
In bookseat.php you will change the status ... :-) Read about ajax from here . :-)