passing query on the same page AJAX - php

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

Related

AJAX POST with datatables not working (using ajax loaded)

I'm trying to do this example https://datatables.net/blog/2017-03-31 everything works except the ajax request, the problem is that I'm trying to return data from a database and a barely know how to do it with ajax (newbie) this is how my code and ajax request look:
var id = 0;
$('#tablanormal tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var tdi = tr.find("i.fa");
var row = table.row(tr);
id = 0;
id = parseInt(table.row(this).data().id_sol);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
tdi.first().removeClass('fa-minus-square');
tdi.first().addClass('fa-plus-square');
} else {
// Open this row
row.child(format(row.data())).show();
tr.addClass('shown');
tdi.first().removeClass('fa-plus-square');
tdi.first().addClass('fa-minus-square');
}
});
table.on("user-select", function (e, dt, type, cell, originalEvent) {
if ($(cell.node()).hasClass("details-control")) {
e.preventDefault();
}
});
});
function format(rowData) {
var div = $('<div/>')
.addClass('loading')
.text('Loading...');
$.ajax({
method: 'POST',
url: 'datatables_ajax/items.php',
data: {idsol: id},
dataType: 'json',
success: function (json) {
div
.html(json.html)
.removeClass('loading');
},
error: function (er) {
console.error(error)
}
});
return div;
}
item.php file
<?php
include_once '../datatables_ajax/conexion.php';
$objeto = new Conexion();
$conexion = $objeto->Conectar();
$idsol = $_POST['idsol'];
$consulta = "CALL Items('".$idsol."')";
$resultado = $conexion->prepare($consulta);
$resultado->execute();
$data=$resultado->fetchAll(PDO::FETCH_ASSOC);
//print json_encode($data, JSON_UNESCAPED_UNICODE);
echo '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;"><tbody>';
foreach(['ID','item','number'] as $attribute) {
echo '<tr><th>'.$attribute.'</th>';
foreach($data as $row) {
echo '<td>'.$row[$attribute].'</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
$conexion=null;
?>
items.php returns id_sol, item_name, item_number I wanted to return it first as text(it works if you only open the file) but the table just stay in "Loading..." when trying to show it, also it would be helpful if someone help me to return that data as a table.
First
you should remove the loading text when the ajax call is complete that's inside the complete: function(){} not inside the success: function(){}.
Second
you can return the data as a table from PHP like this:
if ($resultado->rowCount()){ //meaning if the request returned some data
$data=$resultado->fetchAll(PDO::FETCH_ASSOC);
$d = [];
$i = ;
foreach($data as $val){
$d[i]['fieldName'] = $val['columnName'];
}
echo json_encode($data);
}else{ //no data returned
//error handling here
}
Third
if you want to return the data as an HTML table then do this:
if ($resultado->rowCount()){ //meaning if the request returned some data
$data=$resultado->fetchAll(PDO::FETCH_ASSOC);
$output = "
<table>
<thead>
<tr>
<th>first header </th>
<th>second header </th>
</tr>
</thead>
<body>
";
$d = [];
$i = ;
foreach($data as $val){
$output .="
<tr>
<td>first header data=".$val[columnName]."</td>
<td>second header data=".$val[columnName]."</td>
</tr>";
$d[i]['fieldName'] = $val['columnName'];
}
$output .=" </tbody>
</table>";
echo json_encode($output);
}else{ //no data returned
//error handling here
}

Using JQuery Append From AJAX

I want to create a dropdown list that populated by another dropdown list. I'm using AJAX and PHP.
I have created my AJAX file like this:
<?php
if(isset($_POST['selname']))
{
include('config.php');
$clientId = $_POST['selname'];
$query = "SELECT tv.*, v.* FROM t_vorder tv LEFT JOIN m_vehicle v ON tv.tv_vehicleid = v.v_id WHERE tv_orderid = '$clientId'";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$namek = "";
$namek .= $row['v_id'];
if($row['v_jenis'] != "" || !empty($row['v_jenis']))
{
$namek .= ' - '.$row['v_jenis'];
}
if($row['v_platno'] != "" || !empty($row['v_platno']))
{
$namek .= ' - '.$row['v_platno'];
}
if($row['v_merk'] != "" || !empty($row['v_merk']))
{
$namek .= ' - '.$row['v_merk'];
}
$xx .= "<option value='$row[v_id]'>$namek</option>";
}
return $xx;
exit;
}
?>
After that, I called this AJAX file to my main program, here's my JQuery code:
function getVehicle()
{
var selname = $("select[name=noorder]").val();
$('#combobox2').html('');
$.ajax({ url: "getVehicle.php",
data: {"selname":selname},
type: 'post',
dataType: "json",
success: function(output) {
console.log(output);
$('#combobox2').append(output);
}
});
}
And last is my HTML code:
<select name="noorder" id="combobox" class="form-control">
//get my vehicle from database
<?php
$querycon = mysqli_query($conn, "SELECT * FROM m_order WHERE o_status='1' ORDER BY o_id");
while($rowcon = mysqli_fetch_array($querycon, MYSQLI_ASSOC))
{
$invoice = sprintf("%s%"."04d", $rowcon['o_code'], $rowcon['o_id']);
?>
<option value="<?php echo $rowcon['o_id']; ?>"><?php echo $invoice; ?></option>
<?php
}
?>
</select>
<select name="kendaraan" class="form-control" id="combobox2" onclick="getVechile();">
</select>
My Ajax works fine, my console log return that the file finished load. But my dropdown list not appended by Jquery. Anyone know where's my mistakes?
You did't request for json obj/data into ajax success callback, then no need for dataType: "json", inside ajax properties. Remove that and change return $xx; into echo $xx;
AJAX request gets data from PHP file only when its printed out on the page.
Returning and data from PHP (AJAX backend) to jQuery/Javascript does not mean anything.
Change
return $xx;
to
echo $xx;
You use the dataType: "json" in your ajax call, so it get response in JSON. First remove dataType: "json" line from ajax call. Then replace return $xx; with echo $xx; in your php script.
Hope this solution may works for you, Thanks!

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 ;

PHP and AJAX search results into a table

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

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