send data on button click from javascript to database - php

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 . :-)

Related

While loop Mysql updating checkboxes where to start

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
})
}
}

Load the next 10 record via Ajax Search Box using PHP MySQL and JQUERY

I have see the example about search box using JQuery and mysql, But the view more function no work. how to improve the program. When i click the view more i can see the next 10 record. Thanks
<script type="text/javascript">
$(document).ready(function()
{
$("#keywords").keyup(function()
{
var kw = $("#keywords").val();
if(kw != '')
{
$.ajax
({
type: "POST",
url: "search.php",
data: "kw="+ kw,
success: function(option)
{
$("#results").html(option);
}
});
}
else
{
$("#results").html("");
}
return false;
});
$(".overlay").click(function()
{
$(".overlay").css('display','none');
$("#results").css('display','none');
});
$("#keywords").focus(function()
{
$(".overlay").css('display','block');
$("#results").css('display','block');
});
});
</script>
<div id="inputbox">
<input type="text" id="keywords" name="keywords" value="" placeholder="Type Your Query..."/>
</div>
</div>
<div id="results"></div>
<div class="overlay"></div>
we extract the value of that key and send it to the search.php
<?php
include('db.php');
//file which contains the database details.
?>
<?php
if(isset($_POST['kw']) && $_POST['kw'] != '')
{
$kws = $_POST['kw'];
$kws = mysql_real_escape_string($kws);
$query = "select * from wp_posts where post_name like '%".$kws."%' and (post_type='post' and post_status='publish') limit 10" ;
$res = mysql_query($query);
$count = mysql_num_rows($res);
$i = 0;
if($count > 0)
{
echo "<ul>";
while($row = mysql_fetch_array($res))
{
echo "<a href='$row[guid]'><li>";
echo "<div id='rest'>";
echo $row['post_name'];
echo "<br />";
echo "<div id='auth_dat'>".$row['post_date']."</div>";
echo "</div>";
echo "<div style='clear:both;'></div></li></a>";
$i++;
if($i == 5) break;
}
echo "</ul>";
if($count > 5)
{
echo "<div id='view_more'><a href='#'>View more results</a></div>";
}
}
else
{
echo "<div id='no_result'>No result found !</div>";
}
}
?>
press the view more result will not show more result.
If I'm not mistaken, you want to bring next 10 with ajax ?
This situation behaves as a pagination,
You have to store the current click count in javascript . Wİthout clicking more button, the variable of clickCount is 0, when you click more ,then your variable clickCount=1 ,
while sending ajax , send clickCount to the php.
$.ajax
({
type: "POST",
url: "search.php",
data: "kw="+ kw+"&clickCount="+clickCount,
success: function(option)
{
$("#results").html(option);
}
});
You can query with limit&offset (clickCount )*10, itemCountForEachMoreClick = limit 0,10
when click more
limit 10,10
when click one more
limit 20,10. Do not forget to reset clickCount on keyPress !
php Side
$count = isset($_REQUEST["clickCount"])? $_REQUEST["clickCount"]:0;
$limitAndOffset = $count*10.",10";
$query = "select * from wp_posts where post_name like '%".$kws."%'
and (post_type='post' and post_status='publish') limit ".$limitAndOffset ;

losing TR onclick action after calling AJAX the second time

What I would like to do is call the PHP file which creates a table but I'm not that familiar with JQuery. Please help. I'm losing the onclick and the highlighting that I have in the TR after calling the AJAX the second time.
$.ajax({
url: 'save-all.php',
async: false,
data: $(this).serialize(),
type: 'POST',
success: function (msg) {
if (msg == 'true') {
$.get('orgs-list.php', {}, function (data) {
$('#tbl-content1').replaceWith($(data));
$("#success").show().fadeOut(3000);
});
} else {
$("#error").show().fadeOut(3000);
} //end #msg==true
} //end #success
}); //end #ajax
And the PHP file:
$stid = oci_parse($connection, 'SELECT org_id, agency, pobox, address1, address2, city, state, zipcode, realty_organizations.org_type AS org_type, realty_orgtype.org_type AS agencytype
FROM wflhd_admin.realty_organizations, wflhd_admin.realty_orgtype
WHERE realty_organizations.org_type = realty_orgtype.typeid
ORDER BY agency');
oci_execute($stid);
$nrows = oci_fetch_all($stid, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW);
?>
<table id='tbl-content1' cellpadding='3' width='100%' cellspacing='0' border='1' style='font-family:verdana; font-size: 11px;' >
<?
for ($i=0; $i<=$nrows; $i++) {?>
<tr id="row_<? echo $res[$i]['ORG_ID']; ?>" onClick="DoNavOrg('<? echo $res[$i]['ORG_ID']; ?>','<? echo $res[$i]['AGENCY'] ?>','<? echo $res[$i]['POBOX'] ?>','<? echo $res[$i]['ADDRESS1']; ?>','<? echo $res[$i]['ADDRESS2']; ?>','<? echo $res[$i]['CITY']; ?>','<? echo $res[$i]['STATE']; ?>','<? echo $res[$i]['ZIPCODE']; ?>','<? echo $res[$i]['ORG_TYPE']; ?>'); return false;">
}
To me this sounds like you have it the first time because onDocumentReady the first TR is binded as an DOM element, and that's why jQuery is picking it up.
After you add HTML/DOM elements dynamically, you should BIND them to the functionality you need, with .bind()
http://api.jquery.com/bind/
So try do to something like this,
$( ".your-newly-added-tr" ).bind( "click", function() {
// call what ever you need, "DoNavOrg" or anything else...
});
Hope it helps. :)

jquery get element replaced by text

jQuery.ajaxSettings.traditional = true;
$(document).ready(function(){
$(".wijstoe").change(function(){
var id = $(this).children('#test').map(function() {
return $(this).text();
}).get();
var mw = $("option").val();
var opg = "Opgeslagen !";
$("#loading").css("display","block");
$.post("wijstoe.php",
{mw:mw, id:id},
function(data,status)
{
$("#loading").css("display","none");
$(this).children('#tester').html(opg);
});
});
});
HTML / PHP :
echo "<td>$row[2]</td>";
echo "<td id='test1'>";
echo "<div class='wijstoe'>";
echo "<div id='test' style='display:none;'>".$row[0]."</div>";
echo "<form><select>";
if($_SESSION['uname'] == 'admin') {
$querya="select uname from users";
$resulta = mysql_query($querya);
while ($rowa = mysql_fetch_row($resulta)) {
echo "<option>".$rowa[0]."</option>";
}
echo "</select></form>";
echo "<div id='tester'>DIDI</div>";
echo "</div>";
echo "</td>";
}
This does not get the text from id tester (DIDI) replaced by the text opgeslagen.
When I don't use $(this) it works but then it works for every div with id tester, i just want this specific div to have the text replaced.
So this works :
$(this).children('#tester').html(opg);
This does not work :
$('#tester').html(opg);
$.post("wijstoe.php",
{mw:mw, id:id},
function(data,status)
{
$("#loading").css("display","none");
$(this).children('#tester').html(opg);
});
The $(this) at the location listed will be the POST method.
Having multiple elements with the same ID is not a good practice. Change to a class when using on multiple elements.
var tester = $(this).find('.tester');
$.post("wijstoe.php",
{mw:mw, id:id},
function(data,status)
{
$("#loading").css("display","none");
$(tester).html(opg);
});
try
$(this).find('#tester').html(opg);

Make <tr> rows clickable and load result in div using jQuery

I have two questions:1. How can I make my table rows clickable and still load ajax content in the div ajaxContent? 2. How can I add a loading-animation in the <div id='ajaxContent'>
this is students.php
<?php
echo "<table id='tblStudents'>\n";
echo "<thead><tr>\n";
echo "<td>Namn</td>\n";
echo "<td>Personnummer</td>\n";
echo "<td>Startdatum</td>\n";
echo "<td>Slutdatum</td>\n";
echo "</tr></thead>\n";
echo "<tbody>\n";
while ($row = mysql_fetch_assoc($list_students)) {
$count = ($count + 1) % 2; //will generate 0 or 1 and is used to alternatve the css classes row0 and row1 in the loop result
echo "<tr class='row$count'>\n";
echo "<td><a class='ajaxCall' href='#' rel='".$row['student_id']."'>" . $row['student_firstname'] . "</a> " . $row['student_lastname'] . "</td>\n";
echo "<td>" . $row['student_socialnr'] . "</td>\n";
echo "<td>" . $row['student_startdate'] . "</td>\n";
echo "<td>" . $row['student_enddate'] . "</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
}
?>
<div id='ajaxContent'></div>
<script src="js/jfunc.js"></script>
This is jfunc.js
$('a.ajaxCall').click(function() {
var rowId = $(this).attr('rel');
$.ajax({
type: "get",
url: '/page/editstudent.php',
data: { student_id: rowId },
success: function(data) {
$('#ajaxContent').html(data);
}
});
});
Use event-delegation and listen for all clicks on the table.
$("#tblStudents").on("click", "tr", function(e){
var row_id = $("td:first a.ajaxCall", this).attr("rel");
$("#ajaxContent").html("Loading...");
$.ajax({
url: "/page/editstudent.php",
data: { 'student_id':row_id },
success: function(data){
$("#ajaxContent").html(data);
}
});
});
Side-issues
You don't need to add a classname of 0 or 1 to each table-row. With pure CSS you can target even and odd rows to style them differently:
#tblStudents tr:nth-child(even) {
background: #f1f1f1;
color: #999;
}
Additionally, I would encourage you to store the student id on a data attribute instead of the rel attribute. This is what the data attributes exist for. You could even store them on the <tr> itself. More about those at http://api.jquery.com/data/#data-html5.
1 a add a click event on each tr
$('#tblStudents').on('click', 'tr', function(e) {
// do something
]);
1 b prevent the click event bubling on ajaxCall
$('a.ajaxCall').click(function(e) {
e.preventDefault();
e.stopPropagation();
var rowId = $(this).attr('rel');
$.ajax({
type: "get",
url: '/page/editstudent.php',
data: { student_id: rowId },
success: function(data) {
$('#ajaxContent').html(data);
}
});
2 before requesting the ajax url, insert an image into ajaxContent. once the request has been completed the image will be overwritten with the new html

Categories