Fill table with fetched data after onselect using jquery+ajax - php

I'm trying fill the table with fetched data from database by the id of selected option. Table content must change when user selects other option. Chosen plugin is working fine and select options is filled with correct values, how to give var selektas from test.php to loader.php in query where kliento_id = $idofclient?
Somehow make selektas == $idofclient so that i could use this variable in query in loader.php
My test.php:
<script type="text/javascript">
$(document).ready(function () {
$('.chosen-select').chosen();
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#.pavadinimai").on("change",function(){
var selektas = $(this).val().split('|');
$.ajax({
type: "POST",
url: "loader.php",
data: {selektas[o]},
success: function(result){
$("#show").html(result);
$('#show').dataTable().fnDestroy();
$('#show').dataTable();
}
});
});
});
</script>
<select class="chosen-select" name="pavname" id="pavadinimai">
<option selected="selected" value = "">---Pasirinkti---</option>
<?php
echo "Pasirinkite klienta";
$sql = "SELECT id, kliento_pav FROM klientai";
$stmt = mysqli_query($link, $sql);
while ($row = mysqli_fetch_assoc($stmt)) {
echo "<option value='" . $row['id'] .'|'. $row['kliento_pav'] . "'>" . $row['kliento_pav'] . "</option>";
}
list($idofclient,$pavofclient) = explode ('|',$_POST['pavname']);
?>
</select>
<div id="show">
</div>
And this is my code in loader.php
<?php
require_once "config.php";
if(isset($_POST["pavadinimas"])){
$sql_query="SELECT uzsakymai.id, kliento_id, uzsakymai.kiekis,prekes.pavadinimas,uzsakymai.aprasymas FROM uzsakymai INNER JOIN prekes ON uzsakymai.prekes_id = prekes.id INNER JOIN klientai on uzsakymai.kliento_id = klientai.id WHERE kliento_id = $idofclient"
$resultset = mysqli_query($link, $sql_query) or die("database error:". mysqli_error($link));
while( $result = mysqli_fetch_assoc($resultset) ) {
?>
<br>
<table id="data_table" class="table table-striped">
<thead>
<tr>
<th>Prekės pavadinimas</th>
<th>Kiekis</th>
<th>Aprašymas</th>
</tr>
</thead>
<tbody>
<tr id="<?php echo $result ['id']; ?>">
<td><?php echo $result ['pavadinimas']; ?></td>
<td><?php echo $result ['kiekis']; ?></td>
<td><?php echo $result ['aprasymas']; ?></td>
</tr>
</tbody>
</table>
<?php } ?>
<?php
echo $result
}
?>
I'm using ...jquery/3.1.1/jquery.min.js

Try this
Initially you initialized the table so first clear that table
$('#myTable').dataTable().fnDestroy();
Then initialize again after ajax success
$('#myTable').dataTable();
Like this.....
$(document).ready(function(){
$("#.pavadinimai").on("change",function(){
$.ajax({
type: "POST",
url: "loader.php",
data: {$idofclient},
success: function(result){
$("#show").html(result);
$('#show').dataTable().fnDestroy();
$('#show').dataTable();
}
});
});
});

$(document).ready(function() {
$("#pavadinimai").on("change", function() {
var pavadinimai = $("#pavadinimai").val();
$.ajax({
type: "POST",
url: "loader.php",
data: {
pavadinimai: pavadinimai
},
success: function(result) {
$("#show").html(result);
$('#show').dataTable().fnDestroy();
$('#show').dataTable();
}
});
});
});

Related

Php ajax update button not working in jquery [duplicate]

list.php: A simple ajax code that I want to display only records of the Mysql table:
<html>
<head>
<script src="jquery-1.9.1.min.js">
</script>
<script>
$(document).ready(function() {
var response = '';
$.ajax({
type: "GET",
url: "Records.php",
async: false,
success: function(text) {
response = text;
}
});
alert(response);
});
</script>
</head>
<body>
<div id="div1">
<h2>Let jQuery AJAX Change This Text</h2>
</div>
<button>Get Records</button>
</body>
</html>
Records.php is the file to fetch records from Mysql.
In the Database are only two fields: 'Name', 'Address'.
<?php
//database name = "simple_ajax"
//table name = "users"
$con = mysql_connect("localhost","root","");
$dbs = mysql_select_db("simple_ajax",$con);
$result= mysql_query("select * from users");
$array = mysql_fetch_row($result);
?>
<tr>
<td>Name: </td>
<td>Address: </td>
</tr>
<?php
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>$row[1]</td>";
echo "<td>$row[2]</td>";
echo "</tr>";
}
?>
This code is not working.
For retrieving data using Ajax + jQuery, you should write the following code:
<html>
<script type="text/javascript" src="jquery-1.3.2.js"> </script>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "display.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<body>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Display All Data" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
</body>
</html>
For mysqli connection, write this:
<?php
$con=mysqli_connect("localhost","root","");
For displaying the data from database, you should write this :
<?php
include("connection.php");
mysqli_select_db("samples",$con);
$result=mysqli_query("select * from student",$con);
echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";
while($data = mysqli_fetch_row($result))
{
echo "<tr>";
echo "<td align=center>$data[0]</td>";
echo "<td align=center>$data[1]</td>";
echo "<td align=center>$data[2]</td>";
echo "<td align=center>$data[3]</td>";
echo "<td align=center>$data[4]</td>";
echo "</tr>";
}
echo "</table>";
?>
You can't return ajax return value. You stored global variable store your return values after return.
Or Change ur code like this one.
AjaxGet = function (url) {
var result = $.ajax({
type: "POST",
url: url,
param: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
// nothing needed here
}
}) .responseText ;
return result;
}
Please make sure your $row[1] , $row[2] contains correct value, we do assume here that 1 = Name , and 2 here is your Address field ?
Assuming you have correctly fetched your records from your Records.php, You can do something like this:
$(document).ready(function()
{
$('#getRecords').click(function()
{
var response = '';
$.ajax({ type: 'POST',
url: "Records.php",
async: false,
success : function(text){
$('#table1').html(text);
}
});
});
}
In your HTML
<table id="table1">
//Let jQuery AJAX Change This Text
</table>
<button id='getRecords'>Get Records</button>
A little note:
Try learing PDO http://php.net/manual/en/class.pdo.php since mysql_* functions are no longer encouraged..
$(document).ready(function(){
var response = '';
$.ajax({ type: "GET",
url: "Records.php",
async: false,
success : function(text)
{
response = text;
}
});
alert(response);
});
needs to be:
$(document).ready(function(){
$.ajax({ type: "GET",
url: "Records.php",
async: false,
success : function(text)
{
alert(text);
}
});
});
This answer was for #
Neha Gandhi but I modified it for people who use pdo and mysqli sing mysql functions are not supported. Here is the new answer
<html>
<!--Save this as index.php-->
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "display.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<body>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Display All Data" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
</body>
</html>
<?php
// save this as display.php
// show errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
//errors ends here
// call the page for connecting to the db
require_once('dbconnector.php');
?>
<?php
$get_member =" SELECT
empid, lastName, firstName, email, usercode, companyid, userid, jobTitle, cell, employeetype, address ,initials FROM employees";
$user_coder1 = $con->prepare($get_member);
$user_coder1 ->execute();
echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";
while($row =$user_coder1->fetch(PDO::FETCH_ASSOC)){
$firstName = $row['firstName'];
$empid = $row['empid'];
$lastName = $row['lastName'];
$cell = $row['cell'];
echo "<tr>";
echo "<td align=center>$firstName</td>";
echo "<td align=center>$empid</td>";
echo "<td align=center>$lastName </td>";
echo "<td align=center>$cell</td>";
echo "<td align=center>$cell</td>";
echo "</tr>";
}
echo "</table>";
?>
<?php
// save this as dbconnector.php
function connected_Db(){
$dsn = 'mysql:host=localhost;dbname=mydb;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
#echo "Yes we are connected";
return new PDO($dsn,'username','password', $opt);
}
$con = connected_Db();
if($con){
//echo "me is connected ";
}
else {
//echo "Connection faid ";
exit();
}
?>

Delete Records From Database Using jQuery

I want to add a delete button to this table, to delete the query from Database. I have the Ajax and PHP codes here :
<?php
require_once 'dbconfig.php';
$stmt = $pdo->prepare("SELECT * FROM test");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['server']; ?></td>
<td><?php echo $row['reference']; ?></td>
<td align="center"><a id="<?php echo $row['id']; ?>" class="delete-link" href="#" title="Delete">
<img src="images/delete.png" width="20px" />
</a></td>
</tr>
<?php
}
?>
the ajax :
$(document).ready(function(){
/* Data Delete Starts Here */
$(".delete-link").click(function()
{
var id = $(this).attr("id");
var del_id = id;
var parent = $(this).parent("td").parent("tr");
if(confirm('Sure to Delete ID no = ' +del_id))
{
$.post('delete.php', {'del_id':del_id}, function(data)
{
parent.fadeOut('slow');
});
}
return false;
});
/* Data Delete Ends Here */
});
delete.php :
<?php
include_once 'dbconfig.php';
if($_POST['del_id'])
{
$id = $_POST['del_id'];
$stmt=$db_con->prepare("DELETE FROM test WHERE id=:id");
$stmt->bindParam(':id', $id);
$stmt->execute();
}
?>
The row selected doesn't seem to get DELETED in the DB ... i have no error too.
You had pass data incorrectly . Please try this
$(document).ready(function()
{
$('table#delTable td a.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "view.php",
data: {id:id},
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
}
});
}
});
});

table row delete in database without reloading the page

I want to delete row in database without reloading the page. I have written following codes. It does delete row in page but not in database. which means connection not going to ajax. pls help.
<?php
$advances_result= mysqli_query($conn, "SELECT * FROM advances") or die("error");
?>
<table border>
<caption>ADVANCES</caption>
<tr>
<th>Date</th>
<th>EmpName</th>
<th>EmpCode</th>
<th>Amount</th>
<th>Comment</th>
<th>Action</th>
</tr>
<?php
while($row = mysqli_fetch_array($advances_result)){
?>
<tr>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['empname'];?></td>
<td><?php echo $row['empcode'];?></td>
<td style='text-align:right'><?php echo $row['amount'];?></td>
<td><?php echo $row['comment'];?></td>
<td><button class="delete" id="<?php echo $row['id']; ?>" > Delete</button></td>
</tr>
<?php
}
?>
</table>
'jquery part'
<script>
$(document).ready(function(){
$(".delete").click(function() {
if (confirm("Do you want to delete this row?"))
{
var row = $(this).parents('tr');
var id = row.attr("id");
var data = 'id=' + id ;
$.post({
type: "post",
url: "deleteadvances.php",
data: data,
cache: false,
success: function(){
row.slideUp('slow', function() {$(row).remove();});
}
});
}
return false;
});
});
</script>
'deleteadvances.php' page:
<?php
include("connection.php");
$id = $_POST['id'];
mysqli_query($conn,"INSERT INTO advancehistory SELECT * FROM advances WHERE ID='".$id."'");
mysqli_query($conn,"DELETE FROM advances WHERE ID='".$id."'");
?>
You need to test the output of mysqli_query in deleteadvances.php, if all good, it shows JSON Ok message that is easy parsable with $.post on the jQuery side.
e.g: {"deleted":"id"} on success or {"error":404} on error not found.
I think the id that you're passing from javascript to ajax is incorrect.
var data = 'id=' + id;
is appending the id with string 'id=' and now it finally becomes a string. When it is being passed to ajax, there is just a value and not a [key, value] pair. So, when you are accessing it in php you will get wrong id or Null value.
Try:
$.post({
type: "post",
url: "deleteadvances.php",
datatype : 'json',
data: {
id : id
},
cache: false,
contentType : 'application/x-www-form-urlencoded; charset=utf-8'
});
Change 'deleteadvances.php' page:
<?php
include ('connection.php');
$id=$_POST['id'];
$delete = "DELETE FROM table_name WHERE id=$id";
$result = mysqli_query($db,$delete) or die("Bad SQL: $delete");
?>

jQuery php to delete rows dynamically in table from mysql

I am have a page where i have the table row id defined by 'lesson_id' and i have a delete function for jquery that deletes that row without having to change page.
It is almost all working but when it posts the information to delete_row.php it is not deleting the record.
but delete_row.php is working because i've manually done delete_row.php?id=4 and it deleted that record succesfully.
Any pointers and explanations would be great as i'm still learning.
lessons.php
<table id="lessons" class="table-hover">
<thead>
<tr>
<th>Lesson ID</th>
<th>Lesson Name</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
while($row=mysqli_fetch_array($result)){
echo '<tr id="'. $row['lesson_id'].'">';
echo '<td>'. $row['lesson_id'] .'</td>';
echo '<td>'. $row['name'] .'</td>';
echo '<td><a class="delete">Delete</a></td>';
echo '</tr>';
}
?>
</tbody>
<div id="error"></div>
<script>
$(document).ready(function()
{
$('table#lessons td a.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
//$('#error').html(data);
$.ajax(
{
type: "POST",
url: "delete_row.php",
data: data,
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
}
});
}
});
});
</script>
delete_row.php
<?php
include ('../../../config.php');
$con = mysqli_connect ($dbhost,$dbuser,$dbpass,$dbname);
if (!$con){
die('could not connect: '. mysqli_error($con));
}
$error = "";
$success = "";
if($_GET['id'])
{
$id = $_GET['id'];
mysqli_query($con,"DELETE FROM module_lessons WHERE lesson_id='$id'");
}
?>
as its obvious ... this has no sql injection protection on it.
Change $_GET['id']; to $_POST['id'];
Here, you're doing a POST request:
type: "POST",
url: "delete_row.php",
... but in your PHP script you're checking for GET.
Also, as marc b noted, you're currently vulnerable to SQL injection. Look into using mysqli_real_escape_string, or bind_param.

Using Jquery Ajax to retrieve data from Mysql

list.php: A simple ajax code that I want to display only records of the Mysql table:
<html>
<head>
<script src="jquery-1.9.1.min.js">
</script>
<script>
$(document).ready(function() {
var response = '';
$.ajax({
type: "GET",
url: "Records.php",
async: false,
success: function(text) {
response = text;
}
});
alert(response);
});
</script>
</head>
<body>
<div id="div1">
<h2>Let jQuery AJAX Change This Text</h2>
</div>
<button>Get Records</button>
</body>
</html>
Records.php is the file to fetch records from Mysql.
In the Database are only two fields: 'Name', 'Address'.
<?php
//database name = "simple_ajax"
//table name = "users"
$con = mysql_connect("localhost","root","");
$dbs = mysql_select_db("simple_ajax",$con);
$result= mysql_query("select * from users");
$array = mysql_fetch_row($result);
?>
<tr>
<td>Name: </td>
<td>Address: </td>
</tr>
<?php
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>$row[1]</td>";
echo "<td>$row[2]</td>";
echo "</tr>";
}
?>
This code is not working.
For retrieving data using Ajax + jQuery, you should write the following code:
<html>
<script type="text/javascript" src="jquery-1.3.2.js"> </script>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "display.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<body>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Display All Data" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
</body>
</html>
For mysqli connection, write this:
<?php
$con=mysqli_connect("localhost","root","");
For displaying the data from database, you should write this :
<?php
include("connection.php");
mysqli_select_db("samples",$con);
$result=mysqli_query("select * from student",$con);
echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";
while($data = mysqli_fetch_row($result))
{
echo "<tr>";
echo "<td align=center>$data[0]</td>";
echo "<td align=center>$data[1]</td>";
echo "<td align=center>$data[2]</td>";
echo "<td align=center>$data[3]</td>";
echo "<td align=center>$data[4]</td>";
echo "</tr>";
}
echo "</table>";
?>
You can't return ajax return value. You stored global variable store your return values after return.
Or Change ur code like this one.
AjaxGet = function (url) {
var result = $.ajax({
type: "POST",
url: url,
param: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
// nothing needed here
}
}) .responseText ;
return result;
}
Please make sure your $row[1] , $row[2] contains correct value, we do assume here that 1 = Name , and 2 here is your Address field ?
Assuming you have correctly fetched your records from your Records.php, You can do something like this:
$(document).ready(function()
{
$('#getRecords').click(function()
{
var response = '';
$.ajax({ type: 'POST',
url: "Records.php",
async: false,
success : function(text){
$('#table1').html(text);
}
});
});
}
In your HTML
<table id="table1">
//Let jQuery AJAX Change This Text
</table>
<button id='getRecords'>Get Records</button>
A little note:
Try learing PDO http://php.net/manual/en/class.pdo.php since mysql_* functions are no longer encouraged..
$(document).ready(function(){
var response = '';
$.ajax({ type: "GET",
url: "Records.php",
async: false,
success : function(text)
{
response = text;
}
});
alert(response);
});
needs to be:
$(document).ready(function(){
$.ajax({ type: "GET",
url: "Records.php",
async: false,
success : function(text)
{
alert(text);
}
});
});
This answer was for #
Neha Gandhi but I modified it for people who use pdo and mysqli sing mysql functions are not supported. Here is the new answer
<html>
<!--Save this as index.php-->
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "display.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<body>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Display All Data" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
</body>
</html>
<?php
// save this as display.php
// show errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
//errors ends here
// call the page for connecting to the db
require_once('dbconnector.php');
?>
<?php
$get_member =" SELECT
empid, lastName, firstName, email, usercode, companyid, userid, jobTitle, cell, employeetype, address ,initials FROM employees";
$user_coder1 = $con->prepare($get_member);
$user_coder1 ->execute();
echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";
while($row =$user_coder1->fetch(PDO::FETCH_ASSOC)){
$firstName = $row['firstName'];
$empid = $row['empid'];
$lastName = $row['lastName'];
$cell = $row['cell'];
echo "<tr>";
echo "<td align=center>$firstName</td>";
echo "<td align=center>$empid</td>";
echo "<td align=center>$lastName </td>";
echo "<td align=center>$cell</td>";
echo "<td align=center>$cell</td>";
echo "</tr>";
}
echo "</table>";
?>
<?php
// save this as dbconnector.php
function connected_Db(){
$dsn = 'mysql:host=localhost;dbname=mydb;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
#echo "Yes we are connected";
return new PDO($dsn,'username','password', $opt);
}
$con = connected_Db();
if($con){
//echo "me is connected ";
}
else {
//echo "Connection faid ";
exit();
}
?>

Categories