I've been trying this code but i don't know what's wrong with it, i want my database to be update once a link is click before it goes to another page
<script type="text/javascript">
function performAjaxSubmission(){
$.ajax({
url: 'notif_update.php',
method: 'POST',
data: {
action: 'save',
field: $("#getNotifId").val()
},
dataType:'json',
success: function(data) {
alert(data.success);
}
});
return false;
}
jQuery(document).ready(function() {
$("#notif").click(performAjaxSubmission);
});
</script>
and my notif_update.php is this:
<?php
//UpdateData.php
require_once("connection/dbConn.php");
if (isset($_POST['action'])) {
$value = $_POST['getNotifId'];
mysqli_query($conn, "update notif set notif_status='read' WHERE id=".$value."'");
mysqli_close($conn);
$message ="Updated Sucessfuly!";
}
echo json_encode(array('success'=>$message));
?>
my html code is like this:
echo "<a href='".$row['notif_link']."' target='content' id='notif'>";
echo "<div id='notif_block'>";
echo "<img src='".$imgSrc."' width='50px' height='50px' style='padding-right: 5px; float: left;'>";
echo $row['notif_name'];
echo "<br>";
echo "<span style='color: #999999; font-size: 16px;'>".$subTitle."</span>";
echo "<span style='font-style: italic; color:#999999; font-size: 16px;'> ";
echo date("m-d-Y", $timestamp);
echo "<input id='getNotifId' type='text' value='".$row['notif_id']."'>";
echo "</span></div></a>";
this html code is a generated notification base on what the database given, i want that when a user click the notification, the status of 'unread' in the database will go 'read' so that it won't be displayed anymore
Your PHP script is expecting a parameter called getNotifId and you're sending 'field'. Change the name being sent via ajax like this:
...
data: {
action: 'save',
getNotifId: $("#getNotifId").val()
},
...
Javascript
jQuery(document).ready(function() {
$("#notif").click(function(ev){
ev.preventDefault();
$.ajax({
url: 'notif_update.php',
method: 'POST',
data: {
action: 'save',
field: $("#getNotifId").val()
},
dataType:'json',
success: function(data) {
alert(data.success);
}
});
});
});
and your php would be to catch ajax parameter:
if (isset($_POST['action'])) {
$value = $_POST['field'];
mysqli_query($conn, "update notif set notif_status='read' WHERE id=".$value."'");
mysqli_close($conn);
$message ="Updated Sucessfuly!";
}
echo json_encode(array('success'=>$message));
Related
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();
}
?>
<?php
while ($row = mysqli_fetch_array($query,MYSQLI_BOTH))
{
$id= $_POST['tran_no'];;
?>
<tbody>
<tr id=<?php echo $row['trans_no']?>>
<td><?php echo $row['trans_no']?></td>
<td><?php echo $row['obj_code']?></td>
<td><?php echo $row['div_no']?></td>
<td><?php echo $row['check_no']?></td>
<td><?php echo $row['payee']?></td>
<td><?php echo $row['payment']?></td>
<td><?php echo $row['add']?></td>
<td><?php echo $row['amount']?></td>
<td><?php echo $row['amountw']?></td>
<td>
<img src="image/remove.png">
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<script src="jquery.js"></script>
<script type="text/javascript">
$(function() {
$(".delete").click(function(){
var element = $(this);
var del_id = element.attr("trans_no");
var info = 'trans_no=' + del_id;
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
}
});
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
My problem is the ajax code doesnt seem to delete the row i dont know if the ajax code is executed or not. help would be much need, and please give me an insight as to what is the problem with my code or if i have to add something. heres the delete.php
<?php
$con = mysqli_connect("localhost","root"," ","dole") or die("Could not connect database");
if($_POST['trans_no'])
{
$id=$_POST['trans_no'];
$delete = "DELETE FROM table_no WHERE trans_no = '$id'";
$res=mysqli_query($con,$delete);
}
?>
OPTION 1:
You are assigning id from database to id attribute and in AJAX, reading trans_no.
trans_no attribute is not set for the delete link.
That is why you are not getting it.
Change your HTML to
<img src="image/remove.png">
To make it HTML5 Compliant:
<img src="image/remove.png">
And change JS:
var del_id = element.attr("data-id");
OPTION 2
Just change the line:
var del_id = element.attr("trans_no");
To
var del_id = element.attr("id");
And use your existing code.
It will work.
Try the below code,
$(".delete").click(function(){
var element = $(this);
var del_id = this.id;// use this.id as your database id related to element id
var info = {trans_no : del_id};
if(confirm("Are you sure you want to delete this?")){
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(data){
if(data=='success'){
// hide only in case of successful deltion
element.parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
} else {
alert('Error while deleting');
}
}
});
}
return false;
});
And in PHP return success or error like,
<?php
$con = mysqli_connect("localhost","root"," ","dole") or die("Could not connect database");
$status='error';
if(isset($_POST['trans_no']) && $_POST['trans_no']){
$id=$_POST['trans_no'];
$delete = "DELETE FROM table_no WHERE trans_no = '$id'";
$res=mysqli_query($con,$delete);
if($res){// only success in case of deleted.
$status='success';
}
}
echo $status;
?>
Try this:
$(function() {
$(".delete").click(function(){
var element = $(this);
var transNoVar = element.attr('id');
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: {
trans_no: transNoVar
},
success: function(data){
// delete.php return 1 on success 0 otherwise, check it here
if(data=='1') {
// on success hide the tr
// add class="show" to the tr
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
} else {
alert('Error deleting your record');
}
}
});
}
return false;
});
});
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 !
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();
}
?>
I have been developing a simple page, and there is the problem - my page contains a table with 2 columns; if user moves his cursor to the second column it transforms in editable field and user can edit it and do some actions. Also the page contains links for pagination; if user clicks by link, for example, "2", then table change its content dynamically using Ajax/Jquery. So, my code works good for initial screen, but if I change a page then I can't edit any field in the second column, i.e. code for editing doesn't work now. So, please, tell me, how can I fix it? JS code:
<script type="text/javascript" charset="utf-8">
function hide_info_block(block_id) {
$('#info_block').hide();
}
$(function()
{
var old_value='No translate';
var item_id='';
var item;
$('.field').hover(
function()
{
old_value=$(this).text();
item_id=$(this).attr('id');
item=$(this).parent('td');
new_value=(old_value=='Not translated') ? '' : old_value;
$(this).empty();
var field="<div id='save_button' class='btn btn-primary' style='float: right' href='#'>Save</div><form>"+
"<div style='overflow: hidden; padding-right: .5em;'>"+
"<input id='new_value' type='textarea' name='term' style='width: 100%;' value='"+new_value+"'/></div></form>";
$(this).html(field);
},
function()
{
$(this).empty();
$(this).html(old_value);
});
$('#save_button').live('click', function() {
if ($.trim($('#new_value').val()).length==0)
{
alert ('The string is empty');
return;
}
var loader="<td><img id='small_loader' style='position:absolute' src='/small_loader.gif' /></td>";
item.after(loader);
var old_val=old_value;
var new_val=$.trim($('#new_value').val());
$.post("http://"+document.location.host+"/index.php/welcome/update_record", { old_value: old_val,
value: new_val, id: item_id} ,
function(data) {
var message="Message";
var json = jQuery.parseJSON(data);
var item_id=json.id.replace(/([!"#$%&'()*+,./:;<=>?#\[\\\]^`{|}~])/g, "\\$1");
if (json.result=='LOGIN') {
message="You need to enter before making any actions";
$('#'+item_id).html(json.old_value);
}
else {
if (json.result=='OK') {
$('#'+item_id).css('color', '#000000');
message="Your correction has been added successfully";
$("#"+item_id).html(json.language_value);
}
else {
message="Your correction has been updated successfully";
$('#'+item_id).html(json.language_value);
}
}
$('#small_loader').remove();
alert(message);
});
});
$('.page_button').live('click',function() {
$('#ajaxBusy').show();
$('.selected_page_button').attr('class','page_button');
$(this).attr('class','selected_page_button');
$.post("http://"+document.location.host+"/index.php/welcome/update_records_set/"+this.id,
function(data)
{
if (data != "")
{
$(".records_content:last").empty();
$(".records_content").html(data);
}
$('#ajaxBusy').hide();
});
});
});
</script>
Table code:
<div class="records_content">
<table>
<tbody>
<?php
$i=0;
foreach ($records as $record) {
//echo "<tr class = 'output' style='border-bottom: 1px dotted silver;'>";
echo "<tr class = 'output' style='border-bottom: 1px dotted silver;'>";
echo "<td width='400'>" . strip_tags($record['translate']['language_value']) . "</td>";
if ($record['translate']['coalesce(loc.language_value)'])
{
echo "<td width='200' height='30'><div class='field' id='".$record['translate']['label_value']."/".$record['language_id']."'>".
strip_tags($record['translate']['coalesce(loc.language_value)'])."</div>";
if (count($record['alternatives']))
{
echo "<br/><b>Alternatives:</b>";
echo "<ul>";
foreach ($record['alternatives'] as $alternative)
{
echo "<li>".strip_tags($alternative['coalesce(loc.language_value)'])."</li>";
}
echo "</ul>";
}
}
else
{
echo "<td width='200'>"."<div class='field' style='font-style: italic; color: #FF0000' id='".$record['translate']['label_value']."/".$record['language_id']."'>Not translated</div>";
if (count($record['alternatives']))
{
echo "<br/><b>Alternatives:</b>";
echo "<ul>";
foreach ($record['alternatives'] as $alternative)
{
echo "<li>".strip_tags($alternative['coalesce(loc.language_value)'])."</li>";
}
echo "</ul>";
}
}
echo "</td>";
$i++;
}
?>
</tbody>
</table>
</div>
UPDATE 2:
$('body').on({
mouseenter: function(event)
{
old_value=$(this).text();
item_id=$(this).attr('id');
item=$(this).parent('td');
new_value=(old_value=='Not translated') ? '' : old_value;
$(this).empty();
var field="<div id='save_button' class='btn btn-primary' style='float: right' href='#'>Save</div><form>"+
"<div style='overflow: hidden; padding-right: .5em;'>"+
"<input id='new_value' type='textarea' name='term' style='width: 100%;' value='"+new_value+"'/></div></form>";
$(this).html(field);
},
mouseleave: function(event)
{
$(this).empty();
$(this).html(old_value);
}}, '.field');
You're adding a hover handler to your .field only once. When you change your .field by loading it through AJAX, it becomes a different element without any event handlers.
attach the hover event handler after loading the new .field.
OR
use delegated event handlers.
$('body').on({
mouseenter: function() {
//code when mouse enters .field
},
mouseleave: function() {
//code when mouse leaves .field
}
}, '.field');
Try running it in Google Chrome and press F12 so you have the JavaScript debugger available. Use the [Console] tab so see whether any errors are occurring. Its surprising what you can learn from this and what JavaScript is doing behind the scenes!