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

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

Related

adding a href in ajax while using codeigniter and getting data from curl

I want to add a link inside AJAX and needs a html.tpl[i]['nip'] in a tag because I want to display another view that required data with the chosen nip.
This is for PHP language in framework CodeIgniter and getting data from CURL. I have tried different ways to solve it but still, display wrong when I add link function, the AJAX is not working (not display the data).
I expect the output is when the link of detail is click the will display the view of data required with the nip. I expect the output is the table working properly and can choosing the link and can display the view that the data is required with the nip.
What's going wrong?
+"<td><a href='<?php echo site_url('admin/detail/');?>' >detail</a></td>"
document.addEventListener("DOMContentLoaded", () => {
$.ajax({
url: "<?php echo site_url('Admin/piljur');?>",
dataType: "json",
type: "POST",
cache: false,
success: function(html) {
var data = "";
for (var i = 0; i < html.tpl.length; i++) {
data += "<tr><td>" + (i + 1) + "</td>" + "<td>" + html.tpl[i]['nip'] + "</td>" + "<td>" + "<td><a href='<?php echo site_url('admin/detail/'//i want to adding the value (html.tpl[i]['nip']);?>' >detail</a></td>" + "</tr>";
}
$("#datatabel").append(data);
}
})
You could separate the detail url into a variable to be used later after the ajax call success, like this :
document.addEventListener("DOMContentLoaded", () => {
let detail_url = '<?php echo site_url('admin/detail/'); ?>';
$.ajax({
url: "<?php echo site_url('Admin/piljur');?>",
dataType: "json",
type: "POST",
cache: false,
success: function(html) {
var data = "";
for (var i = 0; i < html.tpl.length; i++) {
data += "<tr><td>" + (i + 1) + "</td>" +
"<td>" + html.tpl[i]['nip'] + "</td>" +
"<td><a href='" + detail_url + html.tpl[i]['nip'] + "' >detail</a></td></tr>";
}
$("#datatabel").append(data);
}
});
}

I need to add condition or function to change picture after get a new data from database

After it receive new data from database i want to use val["id"] make condition to change picture. The fist script is script for get new data from database, the second is an example of condition that i want to do it but it not success.
function getDataFromDb() {
$.ajax({
//SELECT * FROM my_db WHERE 1 ORDER BY id DESC limit 1 (Get only newest data from database.)
url: "getData.php",
type: "POST",
data: ''
}).success(function(result) {
var obj = jQuery.parseJSON(result);
if (obj != '') {
//$("#myTable tbody tr:not(:first-child)").remove();
$("#myBody").empty();
$.each(obj, function(key, val) {
var tr = "<tr>";
tr = tr + "<td>" + val["id"] + "</td>";
tr = tr + "<td>" + val["first_name"] + "</td>";
tr = tr + "<td>" + val["last_name"] + "</td>";
tr = tr + "<td>" + val["age"] + "</td>";
tr = tr + "<td>" + val["hometown"] + "</td>";
tr = tr + "<td>" + val["job"] + "</td>";
tr = tr + "</tr>";
$('#myTable > tbody:last').append(tr);
});
}
});
}
//get new data from database every 10 second
setInterval(getDataFromDb, 10000); // 1000 = 1 second
ex. if(val["id"] > 10){
//Change picture to 1.jpg
} elseif(val["id"] > 20){
//Change picture to 2.jpg
} else {
//Change picture to 3.jpg
};
This is an example that i want to get it but i don't know all of syntax to done it
//Thank you
It seems like your ajax call is missing the id value...
$.ajax({
//SELECT * FROM my_db WHERE 1 ORDER BY id DESC limit 1 (Get only newest data from database.)
url: "getData.php",
type: "POST",
data: {id: 'YOUR-ID-GOES-HERE'}
}
.....

Calling an Ajax function based on button class name click

I have created several image buttons in php. I have assigned a common class to all of them. When I call a jquery function based on button class name click. This works fine but when I try calling an ajax function it doesn't work. There is no error seen.
PHP to create a button
function printpic($name, $picpath, $category, $pic)
{
$style = " margin=0px; background-color=transparent; border=none;";
//$functionname= "selectedpic(this.id)";
$functionname= "myCall(this.id);";
$styleimage = "HEIGHT= 120 WIDTH= 120 BORDER=0";
$eventimage1= "zoomin(this)";
$eventimage2= "zoomout(this)";
$btnclass="btnclass";
$j=0;
$spa=0;
$i=0;
for($k=0; $k<4; $k++)
{
echo "<tr>";
for($j=0; $j<4; $j++)
{
echo"<td>";
$btn= "btn".$category[$i];
echo "<span id='" . $spa. "'>";
echo "<button name='" . $btn. "'
margin ='".$style."'
class='".$btnclass."'
onClick='".$functionname."'
>";
echo "<img src='". $picpath[$i]."/".$name[$i]."'
id ='".$pic[$i]."'
alt ='".$name[$i]."'
.$styleimage.
onMouseMove='".$eventimage1."'
onMouseOut='".$eventimage2."'
>";
echo "</button >";
$spa++;
echo"</span>";
echo"</td>";
$i++;
} // wfor
echo "</tr>";
}// for
} // end function
?>
Jquery + Ajax
$(document).ready(function(e) {
$('.btnclass').click(function() {
event = event || window.event;
var target = event.target || event.srcElement;
var id = target.id;
var but = document.getElementById(id).parentNode.name;
var datastring = '&id='+ id;
$.ajax({
url: "indexverification.php",
type: "POST",
data: datastring,
success: function(responseText) { // get the response
if(responseText == 1) { alert ("hi");}
else { alert (datastring); }
} // end success
}); // ajax end
});
});
indexverification.php
<?php
session_start();
$picno=$_SESSION['picno']; // picno from db
$answer=$_SESSION['answer']; // answer from db
$id=$_POST['id']; // id of picture clicked
$ans=$_SESSION['ans']; // answer type
if (($id==$picno) && ($answer==$ans))
{
echo '1';
}
else
{
echo '2';
}
?>
I think you use the wrong syntax. Try this:
//AJAX request
$.ajax({
url: "indexverification.php",
type: "POST",
data: datastring,
})
//Success action
.success(function( html ) {
if(responseText == 1) { alert ("hi");}
else { alert (datastring); };
})
//Error action
.fail(function() {
alert("Request failed.");
});

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

send data on button click from javascript to database

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

Categories