issue with ajax populating database and displaying results in an html table - php

I have orders table in my database that has id,name and status columns.Then i have html table representing my orders table and inside i have
buttons that i want to update the status column using ajax to make it asynchronous displaying the changes in the html table rigth away.How can i
achieve this?I have tried running ajax functions onclick of a button passing order id as an argument and then using get method to fetch the result but
something is wrong with the document.getElementsByClassName method it is not populating my status field in the html table nor the database is being changed.
orders.php
$query=mysqli_query($conn,"SELECT*FROM orders");
echo "<table border='1'>";
echo "<th>Id</th><th>Name</th><th>Status</th><th>Considering</th><th>Accepted</th>";
while($row=mysqli_fetch_array($query)){
$id=$row['id'];
$name=$row['name'];
$status=$row['status'];
echo "<tr>
<td>$id</td><td>$name</td><td><div class='status'>$status</div></td><td><buttton onclick=\"considering('$id')\">Considering</button></td>
<td><buttton onclick=\"accepted('$id')\">Accepted</button></td>
</tr>";
}
admin.php
<?php
include "include/connect.php";
?>
<!DOCTYPE html>
<html>
<head>
<script>
function considering(one){
var a=new XMLHttpRequest();
a.open("GET","considering_parser.php?one="+one,true);
a.onreadystatechange=function(){
if(a.readyState==4 && a.status==200){
var returndata=a.responseText;
var x=document.getElementsByClassName("status");
for(var i=0;i<x.length;i++){
x[i].innerHTML=returndata;
}
}
}
a.send(null);
}
function accepted(two){
var b=new XMLHttpRequest();
b.open("GET","accepted_parser.php?two="+two,true);
b.onreadystatechange=function(){
if(b.readyState==4 && b.status==200){
var returndata=b.responseText;
var x=document.getElementsByClassName("status");
for(var i=0;i<x.length;i++){
x[i].innerHTML=returndata;
}
}
}
b.send(null);
}
</script>
</head>
<body>
<div id="content">
<?php
include "orders.php";
?>
</div>
</body>
</html>
considering_parser.php
<?php
include "include/connect.php";
$id=$_GET['one'];
$query=mysqli_query($conn,"UPDATE orders SET status=1 WHERE id='$id'");
$query=mysqli_query($conn,"SELECT * FROM orders WHERE id='$id'");
while($row=mysqli_fetch_array($query)){
$one=$row['status'];
echo $one;
}
?>
accepted_parser.php
<?php
include "include/connect.php";
$id=$_GET['two'];
$query=mysqli_query($conn,"UPDATE orders SET status=2 WHERE id='$id'");
$query=mysqli_query($conn,"SELECT * FROM orders WHERE id='$id'");
while($row=mysqli_fetch_array($query)){
$two=$row['status'];
echo $two;
}
?>
Help would be appreciated

Ok i solved it thanks to Fred-ii's suggestion to use multi_query()
orders.php
$query=mysqli_query($conn,"SELECT*FROM orders");
echo "<table border='1'>";
echo "<th>Id</th><th>Name</th><th>Status</th><th>Considering</th><th>Accepted</th>";
while($row=mysqli_fetch_array($query)){
$id=$row['id'];
$name=$row['name'];
$status=$row['status'];
echo "<tr>
<td>$id</td><td>$name</td><td><div class='status$id'>$status</div></td><td><buttton onclick=\"considering('$id')\">Considering</button></td>
<td><buttton onclick=\"accepted('$id')\">Accepted</button></td>
</tr>";
}
admin.php
<html>
<head>
<script>
function considering(one){
var a=new XMLHttpRequest();
a.open("GET","considering_parser.php?one="+one,true);
a.onreadystatechange=function(){
if(a.readyState==4 && a.status==200){
var returndata=a.responseText;
var x=document.getElementsByClassName("status"+one);
for(var i=0;i<x.length;i++){
x[i].innerHTML=returndata;
}
}
}
a.send(null);
}
function accepted(two){
var b=new XMLHttpRequest();
b.open("GET","accepted_parser.php?two="+two,true);
b.onreadystatechange=function(){
if(b.readyState==4 && b.status==200){
var returndata=b.responseText;
var x=document.getElementsByClassName("status"+two);
for(var i=0;i<x.length;i++){
x[i].innerHTML=returndata;
}
}
}
b.send(null);
}
</script>
</head>
<body>
<div id="content">
<?php
include "orders.php";
?>
</div>
</body>
</html>
considering_parser.php
<?php
include "include/connect.php";
$id=$_GET['jedan'];
$query="UPDATE orders SET status=1 WHERE id='$id';
SELECT * FROM orders WHERE id='$id';";
if (mysqli_multi_query($conn,$query))
{
do
{
// Store first result set
if ($result=mysqli_store_result($conn))
{
while ($row=mysqli_fetch_array($result))
{
$one=$row['status'];
echo $one;
}
}
}
while (mysqli_more_results($conn) && mysqli_next_result($conn));
}
mysqli_close($conn);
?>
Similar code for the accepted_parser.php.Thank you Fred-ii

Related

Write a Jquery inside the <?php?> tag

I want to write Jquery code inside PHP tag. I wanted to do this so that I can perform AJAX after that.
I have tried to echo it, but it doesn't work.
<?php
require("conn.php");
$rs = mysql_query("select * from food order by LENGTH(price), price");
if($rs!=false && mysql_num_rows($rs)>0){
$counter ++;
while($row = mysql_fetch_array($rs)){
echo '
<script src="jquery.js">
<script>
$(document).ready(function(){
$("#'.$row["code"].'").click(function(){
echo "clicked";
});
});
</script>
';
}
mysql_free_result($rs);
}else{
echo mysql_error();
}
mysql_close();
?>
Here's a small rearrangement of your code.
<?php
require("conn.php");
$rs = mysql_query("select * from food order by LENGTH(price), price");
if($rs!=false && mysql_num_rows($rs)>0){
$counter ++;
while($row = mysql_fetch_array($rs)){
echo '<a class="row_food">'. $row["code"] .'</a>';
}
mysql_free_result($rs);
}else{
echo mysql_error();
}
mysql_close();
?>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$('.row_food').click(function(){
alert("clicked");
return false;
});
});
</script>
You don't have to echo the javascript code every time in the loop! You only need to echo the content from your db inside the loop.
In the javascript/jquery, you could bind the click event to the element and do whatever you needed.
Hope it helps.
Just put </script> after jquery.js.

edit table with php and jquery

I'm trying to modify the contents of a cell in a table with php and ajax.
the problem that the content has been changed in the page but it is not registered in the database.
this is the page index.php:
<?php
include 'connexion.php';
$sql = 'SELECT * FROM liste_user_tbl';
$result = mysql_query($sql) or die(__LINE__.mysql_error().$sql);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>Modification "inline" de données</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script>
$(function(){
var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
var field_userid = $(this).attr("id") ;
var value = $(this).text() ;
$.post('test1.php' , field_userid + "=" + value, function(data){
if(data != '')
{
message_status.show();
message_status.text(data);
setTimeout(function(){message_status.hide()},3000);
}
});
});
</script>
</head>
<body>
<h1>Utilisateurs</h1>
<table id="table-utilisateurs">
<tr>
<th>Nom</th>
<th>Prénom</th>
</tr>
<?php
while($user = mysql_fetch_assoc($result))
{
?>
<tr>
<td id="<?php echo $user['id']; ?>" contenteditable="true">
<?php echo $user['nom']; ?>
</td>
<td id="<?php echo $user['id']; ?>" contenteditable="true">
<?php echo $user['prenom']; ?>
</td>
</tr>
<?php
}
?>
</table>
</body>
</html>
<?php
mysql_close();
?>
this is test1.php:
<?php
if(!empty($_POST))
{
include "connexion.php";
foreach($_POST as $field_name => $val)
{
//clean post values
$field_userid = strip_tags(trim($field_name));
$val = strip_tags(trim(mysql_real_escape_string($val)));
//from the fieldname:user_id we need to get user_id
$split_data = explode(':', $field_userid);
$user_id = $split_data[1];
$field_name = $split_data[0];
if(!empty($user_id) && !empty($field_name) && !empty($val))
{
//update the values
mysql_query("UPDATE liste_user_tbl SET $field_name = '$val' WHERE id = $user_id") or mysql_error();
echo "Updated";
} else {
echo "Invalid Requests";
}
}
} else {
echo "Invalid Requests";
}
?>
this is my table :
First of all, $field_name is not defined in your code, that's why the query will produce an error if you enable debugging
Second of all, your code is very vulnerable to SQL injections. Your are using user's posted data as it is, without any filtering, and this can lead to loosing your entire database data.
Third of all, you are still using procedural php and "old schoool" database connection. Instead, you can use PDO and POO
use
print_r($_POST);
to receive post data and display
check if the post data has a problem

Post data in a specific div on other page

I want to know if I can post a data in a form to a specific div on other page. Let say example,
form.php
I have this code in jQuery:
$("#hod").change(function(){
var hod = $('#hod').val();
$.post('calc.php #content',
{
hod : hod
}, function(data){
$('#designation').html(data)
});
});
calc.php
<?php
if(isset($_POST['budget'])){
$budget=$_POST['budget'];
$paid=$_POST['paid'];
$ammount=$_POST['ammount'];
$gst=$_POST['gst'];
}
$total=$budget+$paid+$ammount+$gst;
echo $total;
?>
<div id="content">
<?php
if(isset($_POST['hod'])){
$hod=$_POST['hod'];
}
require '../db_connection/connection-intra.php';
$sql="SELECT s.nama,s.staff_id,gp.jawatan,j.nama_jabatan from staff s INNER JOIN gred_pekerja gp ON s.gred_id=gp.gred_id INNER JOIN jabatan j ON j.j_id=s.j_id WHERE s.staff_id='$hod'";
$result=mysqli_query($conn, $sql);
if(!$result) {
die(mysqli_error($conn));
}
if(mysqli_num_rows($result) > 0){
while($row=mysqli_fetch_assoc($result)){
$jawatan=$row['jawatan'];
$jabatan=$row['nama_jabatan'];
}
}
mysqli_free_result($result);
mysqli_close($conn);
echo $jawatan." ".$jabatan;
?>
</div>
If I send the post value to page calc.php, it will also take the value outside of the <div id="content"></div>. Is there a way to only send the content on the <div>

Running Ajax From HTML list Issues

I am trying to run Ajax on a web application which is suppose to list associated data with HTML List from MySQL database using jQuery and PHP.I have two tables in MySQL database called Item and Items as below:
and I have to PHP file called index.php and result.php as:
================================================================== index.php
<html>
<head></head>
<body>
<?php
$mysqli = new mysqli('localhost', 'root', '', 'testdb');
if ($mysqli->connect_errno)
{
die('Unable to connect!');
}
else{
$query = 'SELECT * FROM items';
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
?>
<p>
Select a language
<ul id="item">
<?php
while($row = $result->fetch_assoc()){
?>
<li><div id="selectLanguage"><?php echo $row['item']; ?></div></li>
<?php
}
?>
</ul>
</p>
<p id="result"></p>
<?php
}
else
{
echo 'No records found!';
}
$result->close();
}
else
{
echo 'Error in query: $query. '.$mysqli->error;
}
}
$mysqli->close();
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#selectLanguage').click(function()
{
alert("hello");
if($(this).val() == '') return;
$.get(
'results.php',
{ id : $(this).val() },
function(data)
{
$('#result').html(data);
}
);
});
});
</script>
</body>
</html>
and the result.php is
====================================================================== result.php
<?php
$mysqli = new mysqli('localhost', 'root', '', 'testdb');
$resultStr = '';
$query = 'SELECT type FROM item where name='.$_GET['item'];
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
$resultStr.='<ul>';
while($row = $result->fetch_assoc())
{
$resultStr.= '<li><strong>'.$row['id'].'</strong> - '.$row['type'];
'</li>';
}
$resultStr.= '</ul>';
}
else
{
$resultStr = 'Nothing found';
}
}
echo $resultStr;
?>
now the first part(index.php) is rendering the list base on the items table but I can't click at the second or third item besides none of them not returning any values to the page.
Can you please let me know what I am doing wrong here?
You're creating the selectLanguage div id multiple times. You should use a class instead of an id. Also. the val() is null. You should use html() instead.
looks like in result.php you're populating the list by parameter 'item'
when in your jquery ajax function you're passing the parameter as 'id'
change one of those and you should be good.
Change Your index.php file as :
<html>
<head></head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<?php
$mysqli = new mysqli('localhost', 'root', '', 'testdb');
if ($mysqli->connect_errno)
{
die('Unable to connect!');
}
else{
$query = 'SELECT * FROM items';
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
?>
<p>
Select a language
<ul id="item">
<?php
while($row = $result->fetch_assoc()){
?>
<li><div id="selectLanguage<?php echo $row['id']; ?>"><?php echo $row['item']; ?></div></li>
<script type="text/javascript">
$(document).ready(function()
{
$('#selectLanguage<?php echo $row['id']; ?>').click(function()
{
//alert("hello");
$.ajax({
type : 'POST',
url : 'result.php',
data: {
id : <?php echo $row['id']; ?>
},
success : function(data){
$('#result').html(data);
}
});
});
});
</script>
<?php
}
?>
</ul>
</p>
<p id="result"></p>
<?php
}
else
{
echo 'No records found!';
}
$result->close();
}
else
{
echo 'Error in query: $query. '.$mysqli->error;
}
}
$mysqli->close();
?>
</body>
</html>

jQuery page refresh not reading or executing php

sorry if the title is a little.. vague i couldnt pin it down.
So i am developing a friend request system which works i guess similar in concept to facebook. So you get a request and it lists them without a page reload.
However i get the div 'refreshing' or so i think i cant test the php which is where i have a problem, i will post the relevent code and files below.
It may look a little long winded but it shouldnt be too bad in reality. My php code should keep executing the query which is looking at the database in the updateFriendBox.php however it doesnt seem to be doing this. My code may be messy as well so I apologise.
myaccount.php
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
function refreshDiv()
{
$.get('updateFriendBox.php', function(data){$('#refresh').html(data);});
}
$(function()
{
refreshDiv();
setInterval(refreshDiv, 5000);
});
function box(x){
if($('#'+x).is(":hidden")){
$('#'+x).slideDown(200);
} else {
$('#'+x).hide();
}
}
</script>
<?php
$addBox = '<div style="display:inline; padding:5px;">
Show/Hide Friend Requests
</div>';
// a bit further down in the code where its all called:
<? echo $addBox; ?></span>
<div class="friendSlide" id="fRequ" style="height:240px; overflow:auto;">Your friend requests: <br />
<div id="refresh"> <?php // this is where the refresh call is ?>
</div>
</center>
</div>
</div>
</div>
updateFriendBox.php:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
function acceptFriendRequest(x) {
var url = "friendParse.php";
$.post(url,{ request: "acceptFriend", reqID: x}, function(data){
$("#req"+x).html(data).show().fadeOut(5000);
});
}
function denyFriendRequest(x) {
var url = "friendParse.php";
$.post(url,{ request: "denyFriend", reqID: x}, function(data){
$("#req"+x).html(data).show().fadeOut(5000);
});
}
</script>
</head>
<body>
<?php
include 'dbc.php';
$sql = "SELECT * FROM friendRecu WHERE mem2='" . $_SESSION['user_id'] . "' ORDER BY id ASC LIMIT 10";
$query = mysql_query($sql)or die(mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows < 1) {
echo "No friend requests";
} else {
while($row = mysql_fetch_array($query)){
$requestID = $row['id'];
$req = $row['mem1'];
$sqlName = mysql_query("SELECT full_name FROM users WHERE id='$req'");
while($row = mysql_fetch_array($sqlName)){
$requesterName = $row['full_name'];
}
echo '<hr /><table width="100%", cellpadding="5"><tr><td width="17%" align="left"><div style="overflow:hidden; height:50px; color:white;"></div></td> <td width="83%">' . $requesterName . ' added you as a friend
<span id="req' . $requestID . '">
Accept
||
Deny
</span></td></tr>
</table>';
}
}
?>
I think you are having a problem because your updateFriendBox.php is returning too much. Remove all that inline JS code, place it in an include file, and include it from myaccount.php. You also shouldn't have <head> and <body> sections in your updateFriendBox.php file.
The ajax call here doesn't create a whole new page, you're getting additional HTML to add to the original page.
So the only thing you should have there is your SQL query, the loop, and your HTML output for each data row.

Categories