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. :)
Related
<li>
<a id="collection" href="collections.php">
<span class="glyphicon glyphicon-th white"> Collections</span>
</a>
</li>
<script>
$(document).ready(function(){
$("#collection").click(function(){
$.ajax({
type: 'POST',
url: 'pagination.php',
success: function(data) {
$('#cont').show();
}
});
});
});
</script>
pagination.php :
<?php
require_once "database.php";
$db = new Database();
$perPage = 9;
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$startAt = $perPage * ($page - 1);
$queryTotalRow = "SELECT COUNT(*) FROM image";
$rsetTotalRow = $db->query($queryTotalRow);
$fetchTotalRow = mysqli_fetch_array($rsetTotalRow);
$totalPages = ceil($fetchTotalRow["0"] / $perPage);
$links = "";
for ($i = 1; $i <= $totalPages; $i++) {
$links .= ($i != $page ) ? "<li><a href='collections.php?page=$i'>Page $i</span></a></li> "
: "<li><a href='collections.php?page=$i'>Page $page</a></li> ";
}
$paginationQuery = "select name,image,price,description from image LIMIT $startAt, $perPage";
$result = $db->query($paginationQuery);
if($result){
echo '<div class="containerCollection" id="cont" style="display:none" >';
while($row = mysqli_fetch_array ($result)){
echo '<div style="float:left" class="divEntry">';
echo "<div align='center' class='nameEntry'>".$row['name']."</div>";
echo '<div align="center"><img src="'.$row['image'].'" class="imageEntry"/></div>';
echo "<div align='center' class='priceEntry'>".$row['price']."</div>";
echo "<div class='descEntry'>".$row['description']."</div>";
echo '</div>';
}
echo "<div class='text-center' style='clear:both'>";
echo "<ul class='pagination'>";
echo $links;
echo '</ul>';
echo '</div>';
echo '</div>';
}
?>
why is this not working ? i trigger an ajax call from collection button click , then i want to return some echoes wrapped in div which i set to hide, then i want to show it.
edit : fully updated my pagination.php seems like at fault .
edit2 : solver using this solution jQuery showing div and then Disappearing
Your response isn't on the page yet. You've just echoed it in a Ajax call.
In your success function take the returned data put it on the page then try and show it i.e
success: function(data) {
$('body').append(data);
$('body #cont').show();
}
This is assuming the data is being returned correctly, I'd put something in our pagination.php that says return json_encode($row) then you have the data in a JSON format in your success function to build the elements you want.
Check your payload and responses in the browser when running the code make sure it returns data. You can then specify an explicit html type to be returned in your ajax, finally append the html like follow:
Apply html:
<!--html-->
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery-1.11.3.js"></script>
<script language="javascript" type="text/javascript" src="script.js"></script>
</head>
<body>
<h1>Test header</h1>
<h2 id="idTxt"></h2>
</body>
</html>
Apply javascript:
//javascript
$(document).ready(function() {
var data = 'name=getData'; //data parameter passed through to execute specific functions
$.ajax({
type: "POST",
url: "function.php",
data: data,
dataType: 'json',
success: function(data) {
$("#idTxt").append(data["html"]);
console.log(data["html"]);
},
error: function(data) {
//console.log(data);
}
});
});
Apply php:
//php
<?php
if (isset($_POST["name"]))
{
$string = "<h4> Hi there </h4>"; //build up html as string
$obj = new stdClass();
$obj->html = $string;
echo json_encode($obj);
}
?>
Also try to replace your POST with a get maybe, remember you are trying to get html response data from the server. Good luck hope it helps. :)
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);
I am trying to make a webapp and I have used a php, ajax and mysql search function from another site.
It currently allows me to search the database and return what I want. The only problem I am having is that it returns the results in a simple text box. I want to be able to return the results in a table.
The search simply searches the database for forename, surname, address etc... This is the code I have.
php:
<?php
include('config.php');
if(isset($_GET['search_word']))
{
$search_word=$_GET['search_word'];
$sql=mysql_query("SELECT * FROM info WHERE CONCAT(Forename,' ',Surname) LIKE '%$search_word%'or Address1 LIKE '%$search_word%' or Address2 LIKE '%$search_word%' or Postcode LIKE '%$search_word%' or DOB LIKE '%$search_word%' ORDER BY ID DESC LIMIT 20 ");
$count=mysql_num_rows($sql);
if($count > 0)
{
while($row=mysql_fetch_array($sql))
{
$result = $row['Forename'].' '.$row['Surname'].' '.$row['DOB'].' '.$row['Address1'].' '.$row['Address2'].' '.$row['Postcode'];
$bold_word='<b>'.$search_word.'</b>';
$final_msg = str_ireplace($search_word, $bold_word, $result);
?>
<li><?php echo $final_msg; ?></li>
<?php
}
}
else
{
echo "<li>No Results</li>";
}
}
?>
This is connecting into the database and pulling out the results. I then have my html etc...:
script:
$(function() {
//-------------- Update Button-----------------
$(".search_button").click(function() {
var search_word = $("#search_box").val();
var dataString = 'search_word='+ search_word;
if(search_word=='')
{
}
else
{
$.ajax({
type: "GET",
url: "searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<img src="ajax-loader.gif" align="absmiddle"> Loading Results...');
},
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
// $("#MainTable").append(data);
if(html.length > 0)
{
$("#MainTable tr:not(:first-child)").remove();
}
for(var i = 0; i < html.length; i++)
{
var date = new Date(html[i]["Timestamp"]*1000);
html[i]["Timestamp"] = date.getHours()+":"+date.getMinutes();
$("#MainTable").append("<tr><td><a href='#' id='info"+data[i]["ID"]+"' data-role='button' data-theme='b' data-icon='check' data-iconpos='notext' class='id'></a></td><td>"+data[i]["Timestamp"]+"</td><td>"+data[i]["ID"]+"</td><td>"+data[i]["Forename"]+" "+data[i]["Surname"]+"</td><td class='hidden'>"+data[i]["ID"]+"</td><td>"+data[i]["DOB"]+"</td><td class='hidden'>"+data[i]["Address2"]+"</td><td class='hidden'>"+data[i]["Town"]+"</td><td class='hidden'>"+data[i]["City"]+"</td><td class='hidden'>"+data[i]["County"]+"</td><td>"+data[i]["Address1"]+"</td><td>"+data[i]["Postcode"]+"</td><td class='hidden'>"+data[i]["Phone2"]+"</td><td class='hidden'>"+data[i]["DOB"]+"</td></tr>");
if(data[i]["Completed"] == "1")
{
$("#MainTable tr:last-child td").addClass("lineThrough");
}
$("#MainTable tr:last td:first a, #MainTable tr:last td:last a").button();
}
}
});
}
return false;
});
//---------------- Delete Button----------------
});
I have tried a few different things such as changing the +Data+ in the table script to html or tried adding append(html) but I am having no luck and when I search I am instead getting undefined in my table or it is blank completely.
This is the HTML for my table:
<table data-role="table" id="MainTable" data-mode="columntoggle">
<tr><th> </th><th>ID Number</th><th>Name</th><th>DOB</th><th>Address</th><th>Postcode</th></tr>
<tr><td colspan='7'>No data currently available, connect to the internet to fetch the latest appointments.</td></tr>
</table>
Would appreciate any help with this. Hope this makes sense.
Instead of outputting this in your php page:
while($row=mysql_fetch_array($sql))
{
$result = $row['Forename'].' '.$row['Surname'].' '.$row['DOB'].' '.$row['Address1'].' '.$row['Address2'].' '.$row['Postcode'];
$bold_word='<b>'.$search_word.'</b>';
$final_msg = str_ireplace($search_word, $bold_word, $result);
?>
<li><?php echo $final_msg; ?></li>
Loop through the results outputting them in the table format you need, e.g:
echo "<tr>";
echo "<td>".$row['Forename']."</td>";
echo "<td>".$row['Surname']."</td>";
//etc
echo "</tr>"
Then take that response and fill the containing table with (jquery AJAX) something like:
.done(function( response ) {
$('#MainTable').html(response);
}
Changes:
if($count > 0)
{
while($row=mysql_fetch_array($sql))
{
$result = $row['Forename'].' '.$row['Surname'].' '.$row['DOB'].' '.$row['Address1'].' '.$row['Address2'].' '.$row['Postcode'];
$bold_word='<b>'.$search_word.'</b>';
$final_msg = str_ireplace($search_word, $bold_word, $result);
?>
<tr>
<td> </td>
<td><?=$row['id']?></td>
<td><?=$final_msg?></td>
<td><?=$row['address']?></td>
<td><?=$row['postcode']?></td>
</tr>
<?php
}
}
else
{
echo "<li>No Results</li>";
}
Changes in the JS
$.ajax({
type: "GET",
url: "searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<img src="ajax-loader.gif" align="absmiddle"> Loading Results...');
},
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
$("#MainTable").append(html); //<-- append the data from the ajax
}
});
i'm still fresh in using AJAX and i'm having hard time with it.can you please help me with this? i actually have a dropdown and when i select an item in that dropdown a table of queries should print to the tbody.here's my code:
the PHP code:
<select id="proj_id" name="proj_id" onchange="myFunction(this.value)">
<option value="none">---select project---</option>
<?php
//Projects
$r = #mysql_query("SELECT `proj_id`, `proj_name` FROM `projects`");
while($rows = mysql_fetch_assoc($r)) {
$proj_id = $rows['proj_id'];
$proj_name = $rows['proj_name'];
echo '<option value='.$proj_id.'>'.$proj_name.'</option>';
}
?>
</select>
<table>
<thead>
<tr>
<th>Project Name</th>
<th>Material Name</th>
<th>Quantity</th>
<th>Status</th>
</tr>
</thead>
<tbody id="project_estmat">
<?php
//Display Requests
$r = #mysql_query("SELECT `proj_name`, `mat_name`, `req_qty`, `stat_desc` FROM `requests` JOIN `projects` USING(`proj_id`) JOIN `materials` USING(`mat_id`) JOIN `status` ON(requests.stat_id = status.stat_id)");
while ($row = mysql_fetch_array($r)) {
echo '<tr>';
echo '<td>'.$row['proj_name'].'</td>';
echo '<td>'.$row['mat_name'].'</td>';
echo '<td>'.$row['req_qty'].'</td>';
echo '<td>'.$row['stat_desc'].'</td>';
echo '</tr>';
}
?>
</tbody>
</table>
jS CODE:
function myFunction(value){
if(value!="none")
{
$.ajax(
{
type: "POST",
url: 'content/admin/requests.php',
data: { proj_id: value},
success: function(data) {
$('#project_estmat').html(data);
}
});
}
else
{
$('#project_estmat').html("select an item");
}
}
and I have this PHP code that should be in the #project_estmat which is a table. And I think this is where the problem lies. Because everytime I select an item, nothing is printing in the table. It shows empty data.
<?php
if (isset($_POST['proj_id'])) {
$r = #mysql_query("SELECT `proj_name`, `mat_name`, `req_qty`, `stat_desc` FROM `requests` JOIN `projects` USING(`proj_id`) JOIN `materials` USING(`mat_id`) JOIN `status` ON(requests.stat_id = status.stat_id)");
if($r){
while ($row = mysql_fetch_array($r)) {
echo '<tr>';
echo '<td>'.$row['proj_name'].'</td>';
echo '<td>'.$row['mat_name'].'</td>';
echo '<td>'.$row['req_qty'].'</td>';
echo '<td>'.$row['stat_desc'].'</td>';
echo '</tr>';
}
}
exit;
}
?>
you have wrapped $.ajax function with, ${
it should be like the following, and try using change, and remove the inline function calling when you do this,
$('#proj_id').change(function() {
var value = $(this).val();
if(value!="none"){
$.ajax({
type: "POST",
url: 'content/admin/requests.php',
data: { proj_id: value},
success: function(data) {
$('#project_estmat').html(data);
alert(data);//check whats coming from the server side
}
});
}
});
tested out with a simplified php code to the server end such as the following,
<?php
if (isset($_POST['proj_id'])) {
echo '<tr>';
echo '<td>A</td>';
echo '<td>B</td>';
echo '<td>C</td>';
echo '<td>D</td>';
echo '</tr>';
}
?>
everything looks fine except you have a '$' extra in your if condition
if(value!="none")
${ //here
removing the '$' sign should work...
You shouldn't use the function mysql_query since its deprecated as of PHP 5.5.0 and will be removed (http://php.net/manual/en/function.mysql-query.php). You better use the PHP PDO class (http://php.net/manual/en/book.pdo.php).
Dont suppress your error using '#' error_compression operator. Remove the # symbol from mysql_query and try debugging your code.
Try building a string and sending it back.
$str = '';
if($r){
while ($row = mysql_fetch_array($r)) {
$str .= '<tr>';
$str .= '<td>'.$row['proj_name'].'</td>';
$str .= '<td>'.$row['mat_name'].'</td>';
$str .= '<td>'.$row['req_qty'].'</td>';
$str .= '<td>'.$row['stat_desc'].'</td>';
$str .= '</tr>';
}
return $str;
}
Then when the loop is done we can send the string back. While the dataType property .ajax() uses intelligent parsing to decide what type of data is being sent back and how to construct the returned object, you should just declare it.
$.ajax({
type: "POST",
url: 'content/admin/requests.php',
data: { proj_id: value},
dataType:'html',
success: function(data) {
$('#project_estmat').html(data);
}
});
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 . :-)