Using Jquery Ajax to retrieve data from Mysql - php

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

Related

Data will not refresh after AJAX call

I have a HTML table with three columns
ID, BuildingLocation, Status
and a Active Link in each row. When I Click on Active Link, Status value changed from 0 to 1 into the database but updated value data from the database is not displayed into the HTML table. It will display when I press the F5 key.
Building.php
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function Active(ID)
{
$.ajax(
{
type: "POST",
url: "buildingactive.php",
data: {ID:ID},
dataType: "JSON",
success: function(data)
{
$("#Response").html(data);
},
error: function(err)
{
//console.log("Fail"+err.call);
$("#Response").html(err);
}
});
}
</script>
</head>
<body>
<table>
<tr>
<th>ID</th>
<th>Location</th>
<th>Status</th>
<th>Action</th>
</tr>
<?php
$sq="Select * from buildingmaster";
$Table=mysqli_query($CN,$sq);
while ($Row=mysqli_fetch_array($Table))
{
$ID=$Row['ID'];
echo("<tr>");
echo("<td>".$Row["ID"]."</td>");
echo("<td>".$Row["BuildingLocation"]."</td>");
echo("<td>".$Row["Status"]."</td>");
echo("<td>");
echo("<a href='#' onclick='Active($ID)'>Change</a>");
echo("</td>");
echo("</tr>");
}
?>
</table>
<?php
echo("<div>");
echo("<p id='Response'></p>");
echo("</div>");
?>
</body>
</html>
buildingactive.php
This is my PHP file which is used to update the status column of the buildingmaster table.
<?php
$ID=$_POST['ID'];
$UpdateQuery="Update buildingmaster set Status=1 where ID=$ID";
require_once "connection.php";
$R=mysqli_query($CN,$UpdateQuery);
if($R==1)
{
$res="Building Active Successfully:";
echo json_encode($res);
}
else
{
$error="Server Error... Try Again...";
echo json_encode($error);
}
?>
You have to pass status value along with success message like,
$res={status:'1', msg: 'Building Active Successfully:'};
And you have to decode the data in Ajax success
var myObj = $.parseJSON(data);
Modified Code,
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function Active(ID)
{
$.ajax(
{
type: "POST",
url: "buildingactive.php",
data: {ID:ID},
dataType: "JSON",
success: function(data)
{
$("#Response").html(data.msg);
$(".row"+ID).text(data.staus);
$("#Response").addClass("alert alert-success");
$("#Response").fadeOut(3000);
},
error: function(err)
{
//console.log("Fail"+err.call);
$("#Response").html(err);
$("#Response").addClass("alert alert-danger");
$("#Response").fadeOut(3000);
}
});
}
</script>
</head>
<body>
<table>
<tr>
<th>ID</th>
<th>Location</th>
<th>Status</th>
<th>Action</th>
</tr>
<?php
$sq="Select * from buildingmaster";
$Table=mysqli_query($CN,$sq);
while ($Row=mysqli_fetch_array($Table))
{
$ID=$Row['ID'];
echo("<tr>");
echo("<td class='row".$ID."'>".$Row["ID"]."</td>");
echo("<td>".$Row["BuildingLocation"]."</td>");
echo("<td>".$Row["StatusName"]."</td>");
echo("<td>");
echo("<a href='#' onclick='Active($ID)'>Change</i></a>");
echo("</td>");
echo("</tr>");
}
?>
</table>
<?php
echo("<div>");
echo("<p id='Response'></p>");
echo("</div>");
?>
</body>
</html>
<?php
$ID=$_POST['ID'];
$UpdateQuery="Update buildingmaster set Status=1 where ID=$ID";
require_once "connection.php";
$R=mysqli_query($CN,$UpdateQuery);
if($R==1)
{
$res={status:'1', msg: 'Building Active Successfully:'};
echo json_encode($res);
}
else
{
$error="Server Error... Try Again...";
echo json_encode($error);
}
?>
Add to success: function(data){}
either window.location.reload(); or you can
assign
window.location = window.location

Fill table with fetched data after onselect using jquery+ajax

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

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

jQuery code does not work after resetting a div's content twice

There is a div element :
...
<div id="liste_secteurs"></div>
...
<script type="text/javascript">
$(document).ready(function() {
rechercheSecteursEtProduits(0); // setting the div's content
$('#btnSupprimer').click(function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
var msg = "Do you want to remove these records ?";
if (confirm(msg)) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
}
}
});
});
function rechercheSecteursEtProduits(pn){
var user = "<?php echo $_SESSION[CODE_USER]; ?>";
var html = $.ajax({
data: "id_user="+user,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
async: false
}).responseText;
$('#liste_secteurs').html(html); // this is the div element
}
</script>
Code of ListerProduitsUserParSecteursAjax.php :
<?php
... // getting database data
?>
<p>Total : <?php echo $nr; ?></p>
<div><img src="<?php echo HTTP_ICON.'plus.png'; ?>" /></div>
<?php echo $paginationDisplay; ?>
<table id="table" class="data display " >
<thead style="background-color:#CCC">
<tr>
<th><?php echo _getText("service.produit.form.secteur_activite");?></th>
<th><?php echo _getText("service.produit.form.titre");?></th>
<th></th>
<th><?php if($data["secteur"]["cnt"] > 0){ ?><input type="checkbox" id="check_all"><?php }?></th>
</tr>
</thead>
<tbody style="background-color:#FFF">
<?php
if($data["secteur"]["cnt"] > 0){
for($i=0;$i<$data["secteur"]["cnt"];$i++){?>
<tr class="odd gradeX">
<td><?php echo $data["secteur"][$i]["secta_lib_fr"] ?></td>
<td><?php echo $data["secteur"][$i]["produit_lib"] ?></td>
<td align="center" style="vertical-align:middle"><img src="<?php echo HTTP_ICON.'edit.png'; ?>" alt="<?php echo _getText('main.btn.modifier'); ?>" style="height:10px;width:10px;" /></td>
<td align="center" style="vertical-align:middle"><input type="checkbox" id="prod_<?php echo $i; ?>" value="<?php echo $data['secteur'][$i]['id_user_produit']; ?>"><input type="hidden" id="secteur_<?php echo $i; ?>" value="<?php echo $data['secteur'][$i]['id_user_secteur']; ?>"></td>
</tr>
<?php } ?>
<?php
}
else{
?>
<tr class="odd gradeX">
<td colspan="4" align="center"><b><?php echo _getText('main.liste.no_data'); ?></b></td>
</tr>
<?php }?>
</tbody>
</table>
<?php if($data["secteur"]["cnt"] > 0){ ?>
<div align="right"><input name="btnSupprimer" id="btnSupprimer" type="button" value="<?php echo _getText("main.btn.delete"); ?>" class="btn btn-blue"/></div>
<?php } ?>
<?php echo $paginationDisplay; ?>
When the page loads for the first time then the delete button works fine : the selected rows are deleted , and the list reappears accordingly to new database data. But later when I want to delete other rows then the alert does not show when I check some checkboxes and clicking the delete button !
So what is wrong in my approach ?
From what I am reading you are having problems with the row that are added from the database.
What could be the problem is when you execute this peace of code:
$('#btnSupprimer').click(function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
When you call the $.click() function you add a event to all the existing DOM object that have a id of 'btnSupprimer', however this doesn't update if you add a new DOM object. So what you should do is call this function every time you add a new row. you would get something like this:
function rechercheSecteursEtProduits(pn){
var user = "<?php echo $_SESSION[CODE_USER]; ?>";
var html = $.ajax({
data: "id_user="+user,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
async: false
}).responseText;
$('#liste_secteurs').html(html);
$('#btnSupprimer').click(addClickHandler()); // this is the div element
}
function addClickHandler(){
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
var msg = "Do you want to remove these records ?";
if (confirm(msg)) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
}
}
}
I hope it helps
Try using on instead of click as below
$('#btnSupprimer').on("click","#liste_secteurs",function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
var msg = "Do you want to remove these records ?";
if (confirm(msg)) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
}
}
});
Use the dynamic jquery selector instead of the regular 'click' event
$('#liste_secteurs').on('click', '#btnSupprimer', function() {});
// $("container").on("event", "button", function() {});
As from Caveman's answer I made some updates :
function rechercheSecteursEtProduits(pn) {
var user = "<?php echo $_SESSION[CODE_USER]; ?>";
var html = $.ajax({
data: "id_usermer="+user,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
async: false
}).responseText;
$('#liste_secteurs').html(html);
$('#btnSupprimer').on('click',function(){
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
if (confirm("Do you want to remove these records ?")) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0);
}
}
});
}
And it works !

jquery table reload after ajax call

I am trying to reload a table instead of reloading the whole page
here is my code
<link href="assets/css/bootstrap.min.css" rel="stylesheet" >
<script src="assets/js/bootstrap.min.js"></script>
<input id="check" value="" placeholder="Enter your number here" />
<button type="button" id="go_check" class="btn btn-success" data-loading-text="Loading..." > <i class="icon-ok icon-white"></i> Check</button>
<span id="button"></span>
<br/>
<div id="response">
</div>
<script>
jQuery(document).ready(function() {
jQuery('#go_check').click(function() {
jQuery('#go_check').button('loading');
jQuery.ajax({
type: "POST",
url: "ajax.php",
data: ({
method: "check",
number: jQuery('#check').val()
}),
dataType: "json",
success: function(data) {
jQuery('#button').html(data.btn);
jQuery('#go_check').button('reset');
jQuery('#response').html(data.html);
},
failure: function(errMsg) {
jQuery('#go_check').button('reset');
alert(errMsg);
}
});
});
});
function delete_item($id) {
jQuery.ajax({
type: "POST",
url: "ajax.php",
data: ({
method: "delete",
number: $id
}),
dataType: "json",
success: function(data) {
jQuery('#button').html('');
window.location.reload(); // would like to replace this line with the table refresh
},
failure: function(errMsg) {
jQuery('#go_check').button('reset');
alert(errMsg);
}
});
}
</script>
<link href="assets/css/jquery.dataTables.css" rel="stylesheet" media="screen">
<link href="assets/css/jquery.dataTables_themeroller.css" rel="stylesheet" media="screen">
<script src="assets/js/jquery.dataTables.min.js"></script>
<table class="table" id="tad">
<thead>
<th>
Order Id
</th>
<th>
Ticket Name
</th>
<th>
Ticket Number
</th>
<th>
Product
</th>
<th>
Model
</th>
<th>
Option Name
</th>
<th>
Option
</th>
<th>
Customer
</th>
<th>
Email
</th>
<th>
Telephone
</th>
<th>
Date
</th>
</thead>
<tbody>
<?php
include "config.php";
$con = mysql_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
mysql_select_db(DB_DATABASE, $con);
$result = mysql_query("select * from order_serial ", $con);
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['order_id'];
echo "</td>";
echo "<td>" . $row['serial_name'];
echo "</td>";
echo "<td>" . $row['product_serial'];
echo "</td>";
echo "<td>" . $row['name'];
echo "</td>";
echo "<td>" . $row['model'];
echo "</td>";
echo "<td>" . $row['option_name'];
echo "</td>";
echo "<td>" . $row['option_value'];
echo "</td>";
echo "<td>" . $row['firstname'] . " " . $row['lastname'];
echo "</td>";
echo "<td>" . $row['email'];
echo "</td>";
echo "<td>" . $row['telephone'];
echo "</td>";
echo "<td>" . $row['date'];
echo "</td>";
echo "</tr>";
}
?>
</tbody>
</table>
<script>
jQuery(document).ready(function() {
$('#tad').dataTable({
"sDom": 'R<"H"lfr>t<"F"ip>',
"bJQueryUI": true,
"sPaginationType": "full_numbers"
});
});
</script>
</tbody>
</table>
I have searched for the answer and cant seem to find one it seems a bit silly to reload the whole page instead of just the table ?
Here we can separate the table loading as a separate method and call it on both the go_check button click and after successful deletion of the item.
jQuery(document).ready(function() {
function loadTable(){
jQuery('#go_check').button('loading');
jQuery.ajax({
type: "POST",
url: "ajax.php",
data: ({
method: "check",
number: jQuery('#check').val()
}),
dataType: "json",
success: function(data) {
jQuery('#button').html(data.btn);
jQuery('#go_check').button('reset');
jQuery('#response').html(data.html);
},
failure: function(errMsg) {
jQuery('#go_check').button('reset');
alert(errMsg);
}
});
}
jQuery('#go_check').click(loadTable);
});
function delete_item($id) {
jQuery.ajax({
type: "POST",
url: "ajax.php",
data: ({
method: "delete",
number: $id
}),
dataType: "json",
success: function(data) {
jQuery('#button').html('');
loadTable();
},
failure: function(errMsg) {
jQuery('#go_check').button('reset');
alert(errMsg);
}
});
}
Use the sAjaxSource of datatables rather than seperate ajax call to ajax.php
"sAjaxSource": "http://www.sprymedia.co.uk/dataTables/json.php"

Categories