Jquery ajax json post to php variable - php

I am looping through a mysql table and printing an HTML "Play" link for each row.
I'm trying to avoid refreshing the page on every click of the 'Play' link so I'm placing javascript in the link's 'href':
<a href='javascript:void(0)' onclick='playMV(\"".$rows["v_type"]."\",\"".$rows["v_id"]."\");'>Play</a>
The playMV() function will send necessary info to the server via jquery ajax post to get back out needed values. The php script on the server will use the values posted as values in a mysql query.
// javascript:
<script type="text/javascript">
function playMV(p1, p2) {
$.post("?opt=music", {
var1: p1,
var2: p2
}, function (data) {
//$('#result').html(p2);
});
}
</script>
// PHP:
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$q = mysql_query("SELECT * FROM table WHERE v_lang='".$var1."' AND v_id='".$var2."'");
My question is: I don't know how to call both 'p1' and 'p2' values and assigned into php variable. the commented line $('#result').html(p2) was only output the values in a div block with id='result' but don't really can get it pass to php. I've been read through some answer regarding on json stuffs but end up can't even get what I want.
Please help as I've been stuck quite long in this part.
Thanks very much!!!
// whole code
<script type="text/javascript">
function playMV(p1, p2) {
$.post("<?php echo curPageURL() ?>", {
var1: p1,
var2: p2
}, function (data) {
//$('#result').html(p2);
//$('#result').html(data);
});
}
</script>
<?php
mysql_set_charset("utf8");
$var1 = $_POST['var1'];
$mvid = $_POST['var2'];
echo $var1.$var2;
//echo var_dump($_POST);
$count = 1;
if((strpos(curPageURL(),'mv')==false) || (strpos(curPageURL(),'type')==false)){
$type = ucwords("C");
$mvid = 1;
}
$mtv_data = array();
$mtvlist = mysql_query("SELECT * FROM ".$tb01." WHERE mtv_type='".$type."' ORDER BY mtv_order ASC LIMIT 0, 10") or die(mysql_error());
while($rows = mysql_fetch_array($mtvlist)){
$mtv_data[] = $rows;
}
$q = mysql_query("SELECT * FROM ".$tb01." WHERE mtv_id='".$mvid."'") or die(mysql_error());
$r = mysql_fetch_array($q);
?>
<span id="result"></span>
<div align="center" class="content-layer1" style="height:600px;padding-bottom:20px;">
<div class="content-layer2">
<div style="width:900px;text-align:left;padding:18px 18px 8px 18px;">
<h1>MUSIC ZONE</h1>
</div>
<div style="width:900px;text-align:left;padding:10px;">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="55%">
<div id='mediaspace' align='center'>
<img src="images/ajax-loader.gif">
</div>
<div><?php echo $r["mtv_title"] ?><br /><?php echo $r["mtv_artist"] ?> </div>
</td>
<td width="45%" valign="top">
<div style="border:0px #000 solid;">
<table width='100%' border='1' cellspacing='2' cellpadding='2'>
<?php
foreach($mtv_data as $rows){
echo "<tr>
<td>".$count."</td>
<td><div>".$rows["mtv_title"]."</div><div>".$rows["mtv_artist"]."</div></td>
<td><a href='javascript:void(0)' onclick='playMV(\"".$rows["mtv_type"]."\",\"".$rows["mtv_id"]."\");' id='playmv'>Play</a>
</td>
</tr>";
$count += 1;
}
?>
</table>
</div>
</td>
</tr>
</table>
</div>
</div>
</div>

use json_decode()
$object = json_decode(json_string)

Related

Multiple Images Uploaded Remove Selected Image on Multiple Images in PHP MySqli

Hello Every One i have small problem i will upload multiple images single input file and database store with comma i will stored but i have problem is remove the uploaded images selected and remove the image when we click the image above delete icon that only image deleted
My Code for Retrieve the Multiple images
<div class="panel-body">
<div class="table-responsive">
<table id="dataTableExample1" class="table table-striped table-bordered">
<thead>
<tr>
<th>S.No</th>
<th>Gallery Images</th>
<th>Gallery Name</th>
<th>Operation</th>
</tr>
</thead>
<tbody>
<?php
extract($_REQUEST);
$sql="SELECT * FROM `smw_gallery`";
$result = $conn->query($sql);
$count=$result->num_rows;
if ($count > 0) {
$i=1;
while ($row = $result->fetch_object()) {
$primages = $row->smw_gallery_images;
$imgp = explode(",", $primages);
$realPath = '../assets/images/gallery/';
?>
<tr>
<td style="width:10%"><?=$i;?></td>
<td style="width:50%">
<?php foreach($imgp as $img)
{
echo '<a class="example-image-link" href="#" data-lightbox="example-set" data-title="Click the right half of the image to move forward."><img class="example-image" src="'.$realPath.'/'.$img.'" alt="" height="80" width="80" style="margin: 10px;"/></a>';
} ?>
</td>
<td style="width:10%">
<?php
$limit = 30;
$td_title1 = $row->smw_gallery_name;
if (strlen($td_title1) > $limit)
$td_title1 = substr($td_title1, 0, strrpos(substr($td_title1, 0, $limit), ' '))."...";
echo $td_title1;
?></td>
<td style="width:20%">
<center>
<i class="fa fa-pencil-square-o btn btn-warning" aria-hidden="true"></i>
</center>
</td>
</tr>
<?php $i++; } } ?>
</tbody>
</table>
</div>
</div>
the above code Output look like this
each image i will place delete button and hole gallery delete button
how to made to single image delete button and remove that image only remain will be as it is display
You can do it with small help of jquery, ajax and mysql.
On click delete icon you have to make one ajax request with image name and id parameters. Update image name in database using below query. On success ajax response you can remove that image block using jquery.
Html code for image. Just a sample line.
DeleteIcon
Jquery Code
$(document).on('click', '.delete-image', function(){
var $this = $(this);
var imagname = $(this).data('name');
$.post("delete_image.php",
name: imagname,
id: 1
},
function(data, status){
$this.closest(tr).remove(); //Write your remove code for single image
});
})
I have write code is look like this :
<img class="btn-delete" id="photo-<?=$photo_index_key;?>" data-id="<?=$photo_index_key;?>" data-name="<?=$photo_name;?>" style="margin: 3px 1px 74px -17px; cursor: pointer;" src="../assets/images/closes.png";>
each one of indexkey value can taken in jquery var $imageId = $(this).attr('id');
<script>
$(document).on('click', '.btn-delete', function(){
var imageId = $(this).attr('data-id');
var imageName = $(this).attr('data-name');
var dataString = {id:imageId, name: imageName}
$.ajax({
type: "POST",
url: "remove.php",
data: dataString,
cache: false,
success: function(html){
$('#photo'+imageId).remove(); // you can write your logic
}
});
});
</script>
remove.php
//get ajax data:
$id = $POST['id'];
$name = $POST['name'];
UPDATE smw_gallery
SET `smw_gallery_images` = REPLACE(`smw_gallery_images`, $name,'')
WHERE `id` = $id;
What if you do it in appearance.
That is, you can define the array by indexes
<div class="panel-body">
<div class="table-responsive">
<table id="dataTableExample1" class="table table-striped table-bordered">
<thead>
<tr>
<th>S.No</th>
<th>Gallery Images</th>
<th>Gallery Name</th>
<th>Operation</th>
</tr>
</thead>
<tbody>
<?php
extract($_REQUEST);
$sql = "SELECT * FROM `smw_gallery`";
$result = $conn->query($sql);
$count = $result->num_rows;
if ($count > 0) {
$i = 1;
while ($row = $result->fetch_object()) {
$primages = $row->smw_gallery_images;
$imgp = explode(",", $primages);
$realPath = '../assets/images/gallery/';
?>
<tr>
<td style="width:10%"><?= $i; ?></td>
<td style="width:50%">
<?php foreach ($imgp as $photo_index_key => $img) {
echo '<a class="example-image-link" href="#" data-lightbox="example-set" data-title="Click the right half of the image to move forward.">
<img class="example-image" src="' . $realPath . '/' . $img . '" alt="" height="80" width="80" style="margin: 10px;"/>
</a>';
echo "<a href='".$realPath . "/remove.php?smw_gallery_id=" . $row->id . "&photo_index_key=" . $photo_index_key . "'></a>";
} ?>
</td>
<td style="width:10%">
<?php
$limit = 30;
$td_title1 = $row->smw_gallery_name;
if (strlen($td_title1) > $limit)
$td_title1 = substr($td_title1, 0, strrpos(substr($td_title1, 0, $limit), ' ')) . "...";
echo $td_title1;
?></td>
<td style="width:20%">
<div style="text-align: center;">
<a href="gallery-edit.php?edit=<?= $row->smw_gallery_id; ?>" title="Edit"><i
class="fa fa-pencil-square-o btn btn-warning" aria-hidden="true"></i></a>
</div>
</td>
</tr>
<?php $i++;
}
} ?>
</tbody>
</table>
</div>
I don't know English. This was done via google translate
remove.php
<?php
if (!empty($_GET['smw_gallery_id'] && !empty($_GET['photo_index_key']))) {
$sql = sprintf("SELECT `smw_gallery_images` FROM `smw_gallery` WHERE `id` = %d", $_GET['smw_gallery_id']);
$result = $conn->query($sql);
$result->fetch_assoc();
if (!is_null($result) && is_array($result)) {
while ($row = $result->fetch_assoc()) {
$smw_gallery_images = explode(",", $row['smw_gallery_images']);
$new_smw_gallery_images = array_splice($smw_gallery_images, $_GET['photo_index_key'], 1);
$new_smw_gallery_images = implode(',', $new_smw_gallery_images);
$updateSql = sprintf("UPDATE smw_gallery SET `smw_gallery_images` = %s WHERE `id` = %d", $new_smw_gallery_images, $_GET['smw_gallery_id']);
$conn->query($updateSql);
}
}
}

My php while loop is not parsing the whole table

I have two tables in my webpage, each being populated with a php while loop.
My first table gets all its data outputted but my second while loop only outputs as many fields as the first one.
My second while loop is not nested within the other one, they are both independent from each other.
When i check the console I see that my second while loops seems to have outputted my data but when I click on my button to display the entire column, only 3 values appear instead of all of them
This is what is shown when I click on TEAM TASK
https://imgur.com/4FCu1dX
This is what is shown when I click on MY TASK
https://imgur.com/q1F6sgx
I also noticed that whether I click on MYTASK or TEAM TASK their are two rows from MYTASK that are always shown.
I Initially had both while loops within the same table but then moved them to each fill there own table but this issue still occurs.
<table border='0' style="float:left; width:20%; height: 500px; border-radius: 5px; display: block;" bgcolor="#2B4353">
<thead>
<tr>
<td bgcolor="#2B4353" border="0" valign="top" align="right">
<div class="messages-header-my" onclick="myTasks()"><p id="myTasks">MY TASKS</p></div></td>
</tr>
</thead>
<tbody>
<?php
while($row8 = mysqli_fetch_array($TableMY)){ $task1234=$row8[1];
?>
<tr id="my" style="display: block;" onclick="myTaskView('<?php echo $task1234?>')"><td bgcolor="#2B4353" border="0" valign="top" colspan="3"><p
<?php if ($row8[0]=='HIGH')
{$statuscss= 'taskHigh';}
elseif ($row8[0]== 'MEDIUM')
{$statuscss= 'taskMedium ';}
else{ $statuscss= 'taskLow';}
echo 'class="',$statuscss,'"';?> style="margin-left: 30px;">OD_<?php echo $task1234?></p></td></tr>
<?php }?>
</tbody>
</table>
<table border='0' style="float:left; width:20%; height: 500px; border-radius: 5px; display: block;" bgcolor="#2B4353">
<thead>
<tr>
<td bgcolor="#2B4353" border="0" valign="top" align="right">
<div class="messages-header-team" onclick="teamTasks()"><p id="teamTasks">TEAM TASKS</p></div></td>
</tr>
</thead>
<tbody>
<?php
while($row8 = mysqli_fetch_array($TableTeam)){ $task1234=$row8[1];
?>
<tr id="team" style="display:none;" onclick="myTaskView('<?php echo $task1234?>')"><td bgcolor="#2B4353" border="0" valign="top" colspan="3"><p
<?php if ($row8[0]=='HIGH')
{$statuscss= 'taskHigh';}
elseif ($row8[0]== 'MEDIUM')
{$statuscss= 'taskMedium ';}
else{ $statuscss= 'taskLow';}
echo 'class="',$statuscss,'"';?> style="margin-left: 30px;">OD_<?php echo $task1234?></p></td></tr>
<?php }?>
</tbody>
</table>
My php
require('server.php');
session_start();
$email=$_SESSION['email'];
$sqli="Select URLDomain from Admin.Users where Email = ?";
$stmt =mysqli_prepare($link,$sqli);
mysqli_stmt_bind_param($stmt,"s",$email );
mysqli_stmt_execute($stmt);
$useremail=mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_array($useremail);
$DBdomain=$row[0];
mysqli_select_db($link,"Universe");
$stmt = mysqli_prepare($link,"Select Priority,TaskNumber from Task where urlDomain=?");
mysqli_stmt_bind_param($stmt,"s",$DBdomain );
mysqli_stmt_execute($stmt);
$TableTeam=mysqli_stmt_get_result($stmt);
mysqli_stmt_close($stmt);
mysqli_select_db($link,"Universe");
$stmt = mysqli_prepare($link,"Select Priority,TaskNumber from Task where TaskOwner=?");
mysqli_stmt_bind_param($stmt,"s",$email );
mysqli_stmt_execute($stmt);
$TableMY=mysqli_stmt_get_result($stmt);
mysqli_stmt_close($stmt);
Here is my Javascript
<script>
function messagesTab() {
document.getElementById("task-message").style.display = "block";
}
</script>
<script>
function myTasks() {
document.getElementById("myTasks").style.color = "#1FAC96";
document.getElementById("teamTasks").style.color = "#FFFFFF";
document.getElementById("team").style.display = "none";
document.getElementById("my").style.display = "block";
document.getElementById("messageDisplay").style.display = "block";
document.getElementById("myTaskView").style.display = "none";
}
</script>
<script>
function teamTasks() {
document.getElementById("teamTasks").style.color = "#1FAC96";
document.getElementById("teamTasks").style.underline = "#1FAC96";
document.getElementById("myTasks").style.color = "#FFFFFF";
document.getElementById("team").style.display = "block";
document.getElementById("my").style.display = "none";
document.getElementById("myTaskView").style.display = "none";
document.getElementById("messageDisplay").style.display = "block";
}
</script>
<script>
function myTaskView(Task_Number) {
$.ajax({
url:'messages_select.php',
type:'POST',
data:{Task_Number:Task_Number},
success:function(data){
$('#myTaskView').html(data);
document.getElementById("myTaskView").style.display = 'block';
document.getElementById("messageDisplay").style.display = 'none';
}
});
}
</script>
<script>
var main = function() {
$('form').submit(function(event) {
var $input = $(event.target).find('input');
var comment = $input.val();
if (comment != "") {
var user = '<i class="fas fa-user-circle"></i>';
var userInfo = $(user).text(' '+'nataliekoly#mail.usf.edu'+' | '+'01/31/19'+' | '+'3:45 PM')
var comment = $('<li>').text(comment);
comment.prependTo('#comments');
userInfo.prependTo('#comments');
$input.val("");
}
return false;
});
}
$(document).ready(main);
</script>
IDs need to be unique, you can't have id="my" and id="team" on each row of the table. Use classes instead:
<tr class="my" style="display: block;" onclick="myTaskView('<?php echo $task1234?>')"><td bgcolor="#2B4353" border="0" valign="top" colspan="3"><p
and
<tr class="team" style="display:none;" onclick="myTaskView('<?php echo $task1234?>')"><td bgcolor="#2B4353" border="0" valign="top" colspan="3"><p
Then you need to loop over them:
document.querySelectorAll(".my").forEach(el => el.style.display = "block");

How do I get items by category wise

Basically, I have a list of categories that I am iterating form mysqli
<div style="width:20%; float:left;">
<h3>Categories</h3>
<?php while($categories = $resultproductcategories->fetch_assoc()){?>
<div class="rows">
<input type="button" name="<?php echo $categories['id'] ?>" value="<?php echo $categories['category?>" />;
</div>
<?php }?>
</div>
Now what I want that if I press any category it should fetch data accordingly there is my code for fetching
$stmtproducts = $mysqli->prepare("SELECT * FROM store_products sp INNER JOIN store_product_categories spc ON sp.product_category=spc.id WHERE sp.store_id=? AND sp.category=? LIMIT $count, 10");
$stmtproducts->bind_param("ii",$_SESSION['storeid'],$_POST['']);
$stmtproducts->execute();
$resultproducts = $stmtproducts->get_result();
$num=$resultproducts->num_rows;
echo $num;
$stmtproducts->close();
I am confused that if there was a specific name of input then I would have gotten it by isset($_POST['name']) but there is no specific name... I cannot think of how to send category to mysql.
<div id="divTransactional" style="width:70%;padding-left:5%; float:left;">
<?php if($num>0) {?>
<table class="table table-responsive table-hover" id="tableProducts">
<h3>Products</h3>
<tbody>
<?php for($i=0;$i<$num;$i++) { $products = $resultproducts->fetch_assoc();//while($products = $resultproducts->fetch_assoc()) {?>
<tr>
<td>Code: <?php echo $products['product_code'];?></td><td>Added On: <?php echo $products['product_date'];?></td>
</tr>
<tr>
<td>Name: <?php echo $products['product_name'];?></td>
</tr>
<tr>
<td>Category: <?php echo $products['category'];?></td>
</tr>
<tr>
<td>Description: <?php echo $products['product_desc'];?></td>
</tr>
<tr>
<td>Price: <?php echo $products['product_price'];?></td><td>Discount: <?php echo $products['product_discount'];?></td>
</tr>
<tr style="width:100px; height:100px;">
<td><img src="../../uploads/store/products/<?php echo $products['product_image1'];?>" style="width:100px; height:100px;"/></td>
<td><img src="../../uploads/store/products/<?php echo $products['product_image2'];?>" style="width:100px; height:100px;"/></td>
<td><img src="../../uploads/store/products/<?php echo $products['product_image3'];?>" style="width:100px; height:100px;"/></td>
<td><img src="../../uploads/store/products/<?php echo $products['product_image4'];?>" style="width:100px; height:100px;"/></td>
</tr>
<?php }?>
</tbody>
<?php if($num >= 10) { ?>
Next
<?php } ?>
<?php $prev = $count - 10;
if ($prev >= 0){?>
Previous
<?php }?>
</table>
<?php if($num >= 10) { ?>
Next
<?php } ?>
<?php $prev = $count - 10;
if ($prev >= 0){?>
Previous
<?php }?>
<?php } ?>
</div>
I would suggest using Ajax to call the server with an Id in parameters.
You need to add a class to your buttons and you do need to link a JS file and JQuery. here's an example.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="path/to/your/file.js"></script>
<div style="width:20%; float:left;">
<h3>Categories</h3>
<?php while($categories = $resultproductcategories->fetch_assoc()){?>
<div class="rows">
<input type="button" name="<?php echo $categories['id'] ?>" value="<?php echo $categories['category']?>" class="btnCategory"/>;
</div>
<?php }?>
And then, using ajax you can call your php file that returns the value you need to fetch from your database.
$(document).ready(function() {
$('.btnCategory').on('click', function(){
var id = $this.attr('name');
$.ajax({
url: 'path/to/your/file.php',
method: "GET",
data: {category_id: id},
success: function(data) {
//This is the data fetch from the server
console.log(data);
},
error: function(err) {
console.error('An error occurred : ' + err);
}
});
});
});
And then, when your PHP file receive the parameter $_GET['category_id'] you call your database.
<?php
if(isset($_GET['category_id'])){
//An id was post in the url.
$stmtproducts = $mysqli->prepare("SELECT * FROM store_products sp INNER JOIN store_product_categories spc ON sp.product_category=spc.id WHERE sp.store_id=? AND sp.category=? LIMIT $count, 10");
$stmtproducts->bind_param("ii",$_SESSION['storeid'],$_POST['']);
$stmtproducts->execute();
$resultproducts = $stmtproducts->get_result();
$num=$resultproducts->num_rows;
$stmtproducts->close();
$result = array('row_count' => $num, 'result' => $resultproducts);
echo json_encode($result);
}
And then you return a json array of your result. That's what I would do.
Hope it helps !
Nic
You asked for a demo, here it is .
<?php
if(isset($_GET['category_id'])){
//An id was post in the url.
$stmtproducts = $mysqli->prepare("SELECT * FROM store_products sp INNER JOIN store_product_categories spc ON sp.product_category=spc.id WHERE sp.store_id=? AND sp.category=? LIMIT $count, 10");
$stmtproducts->bind_param("ii",$_SESSION['storeid'],$_POST['']);
$stmtproducts->execute();
$resultproducts = $stmtproducts->get_result();
$num=$resultproducts->num_rows;
$stmtproducts->close();
$result = array('row_count' => $num, 'result' => $resultproducts);
echo json_encode($result);
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div style="width:20%; float:left;">
<h3>Categories</h3>
<?php while($categories = $resultproductcategories->fetch_assoc()){?>
<div class="rows">
<input type="button" name="<?php echo $categories['id'] ?>" value="<?php echo $categories['category']?>" class="btnCategory"/>;
</div>
<?php }?>
</div>
<script>
$(document).ready(function() {
$('.btnCategory').on('click', function(){
var id = $this.attr('name');
$.ajax({
method: "GET",
data: {category_id: id},
success: function(data) {
//This is the data fetch from the server
console.log(data);
},
error: function(err) {
console.error('An error occurred : ' + err);
}
});
});
});
</script>

jquery not working on using pagination

Am just trying to show all the list in the pagination. am using datatable plugin's pagination on my file, pagination is working fine, in the list i have an image that have a function delete on click. in my pagination 1'st five records is shown . and the other five records shown on click next, delete function working properly on 1'st five record when i click on next than delete function stop it's working .
my code:-
<script>
var conf = jQuery.noConflict();
conf(document).ready(function(){
conf(".delete").on( "click", function() {
alert('adfasdfasd');
//alert(conf(this).attr("id"));
custid = conf(this).attr("id");
var r=confirm("Are you sure");
if (r==true)
{
var url = "<?php echo Mage::getBaseUrl();?>turnkey/index/deleteuser/";
conf.ajax({
type:"POST",
url:url,
data: { 'custid':custid},
success: function(msz){
alert(msz);
if(msz=="deleted") {
conf("#hidepro"+custid).hide("slow");
}
else {
//conf("#hidepro"+proid).hide();
alert("product cant be deleted");
}
//console.log("chal hun");
}
});
}
else
{
return false ;
}
});
});
</script>
and the pagination code is :-
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#example').dataTable();
} );
</script>
<div id="container">
<div id="demo">
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example" width="100%">
<thead>
<tr>
<th>Factory</th>
<th></th>
<th>Contact</th>
<th>URL</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
<?php
foreach( $custemail as $custemail1 ) {
$customer = Mage::getModel("customer/customer");
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($custemail1); //load customer by email id ?>
<tr class="odd gradeX" style=" border-bottom: 1px solid #FF0000;" id = "hidepro<?php echo $customer['entity_id'] ?>">
<td class="bodyText style4" ><a style=" color: #CC3300;float: left;margin-top: 42px !important;text-decoration: underline;" href="<?php echo Mage::getBaseUrl();?>turnkey/index/listuser?id=<?php echo $customer->getEntity_id();?>"><?php echo $customer->getFactory();?></a> </td>
<td class="bodyText style4">
<a href="<?php echo Mage::getBaseUrl();?>turnkey/index/listuser?id=<?php echo $customer->getEntity_id();?>">
<img style=" width:100px;height:100px;margin-bottom:5px ;" src = "http://lab.ghrix.com/turn-key-mart/media/<?php echo $customer->getUserImage();?>"></a>
</td>
<td class="bodyText style4" style="padding-top: 10px;">
<?php echo $customer->getFirstname();?><?php //echo $customer->getUser_address();?><br><?php echo $customer->getmobile();?><br><?php echo $customer->getEmail();?></td>
<td class="bodyText style4" style="float: left;margin-top: 42px !important;" >
<a target="_blank" style="color:#005580;" href="<?php echo $customer->getWebsite();?>"><?php echo $customer->getWebsite();?></a></td>
<td class="bodyText style4"><div style= "cursor:pointer;" class = "delete" id = "<?php echo $customer['entity_id'] ?>"><img width="60px" src="<?php echo $this->getSkinUrl('images/trash.jpg'); ?>"</div></td>
</tr>
<?php }?>
</tbody>
</table>
</div>
</div>
please suggest where mistake is happen.
Without a live example, I can't be sure, but try this:
replace
conf(".delete").on("click", function() ...
with:
conf(document).on("click", ".delete", function() ...
The reason is that conf(".delete") only attaches to elements available at the time the function is run. It might be that your dataTable plugin runs first, removes the extra elements, then the delete binder is run and only works on the first 5. The second method binds to the document, and checks each click to see if it matches the .delete selector. This used to be known as jQuery.live()

ajax html response can't take effect on link with javascript

I made a form for showing users informations about some presentations. I used ajax cause it should be loaded into a div container and not reloading each time while changing the year.
This is my JavaScript:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: 'include/scripts/select_event.php',
type: 'POST',
data: data,
dataType: 'html',
success: function (select) {
$("#coffee_talk").html(select);
$("#coffee_talk").fadeIn();
}
});
return false;
});
This is my select_event.php:
if ('POST' == $_SERVER['REQUEST_METHOD']) {
/*******************************/
/** Erzaehlcafe auswählen
/*******************************/
if (isset($_POST['coffee_talk_year_submit'])) {
$getID = array();
$getDate = array();
$getTheme = array();
$getContributer = array();
$getBegin = array();
$getPlace = array();
$getEntrance = array();
$getFlyer = array();
$sql = "SELECT
ID,
Date,
Theme,
Contributer,
Begin,
Place,
Entrance,
Flyer
FROM
Coffee_talk
WHERE
YEAR(Date) = '".mysqli_real_escape_string($db, $_POST['year_coffee_talk'])."'
ORDER BY
Date ASC
";
if (!$result = $db->query($sql)) {
return $db->error;
}
while ($row = $result->fetch_assoc()) {
$getID[$i] = $row['ID'];
$getDate[$i] = $row['Date'];
$getTheme[$i] = $row['Theme'];
$getContributer[$i] = $row['Contributer'];
$getBegin[$i] = $row['Begin'];
$getPlace[$i] = $row['Place'];
$getEntrance[$i] = $row['Entrance'];
$getFlyer[$i] = $row['Flyer'];
$i++;
}
$result->close();
/****************************/
/** Output der Tabelle
/****************************/
if ($getID[0] == '') {
echo 'Kein Eintrag vorhanden';
} else {
//Kopf
echo '<table id="table">
<thead>
<tr id="table_head">
<th>Nr.</th>
<th>Datum</th>
<th>Thema</th>
<th>Referent</th>
<th>Begin</th>
<th>Ort</th>
<th>Eintritt</th>
<th>Flyer</th>
<th>Bearbeiten</th>
</tr>
</thead>
<tbody>';
//Mittelteil
$j = 0;
for($i = 0; $i < count($getID); $i++) {
$j = $i + 1;
echo '<tr>
<td class="center">'.$j.'</td>
<td class="center">'.$getDate[$i].'</td>
<td class="center">'.$getTheme[$i].'</td>
<td class="center">'.$getContributer[$i].'</td>
<td class="center">'.$getBegin[$i].'</td>
<td class="center">'.$getPlace[$i].'</td>
<td class="center">'.$getEntrance[$i].'</td>';
if ($getFlyer[$i] == '') {
//Kein Bild vorhanden
echo '<td class="center">Kein Bild vorhanden</td>';
} else echo '<td class="center">'.$getFlyer[$i].'</td>';
echo '<td class="center">
<table id="icons">
<tr>
<td>
<a href="#" data-event-id="'.$getID[$i].'" data-table="Coffee_talk" class="edit_event">
<img src="images/edit.png" />
</a>
</td>
<td>
<a href="#" data-event-id="'.$getID[$i].'" data-table="Coffee_talk" class="delete_event">
<img src="images/delete.png" />
</a>
</td>
</tr>
</table>
</td>
</tr>';
}
//Ende
echo '</tbody>
</table>';
}
}
}
As you can see my outpt is a table. I am using links to make an edit and delete function:
<a href="#" data-event-id="'.$getID[$i].'" data-table="Coffee_talk" class="edit_event">
<img src="images/edit.png" />
</a>
and
<a href="#" data-event-id="'.$getID[$i].'" data-table="Coffee_talk" class="delete_event">
<img src="images/delete.png" />
</a>
This is my html with the placeholder div:
<div>
<p class="bold underline headline">Bereits eingetragen:</p>
<form id="coffee_talk_year" action="include/scripts/select_event.php" method="post" accept-charset="utf-8">
<select name="year_coffee_talk" id="year_coffee_talk">
<option value="none" class="bold italic">Jahr</option>
<?php
for($i=2008; $i<=$year; $i++){
if ($i == $year) {
echo "<option value=\"".$i."\" selected=\"$i\">".$i."</option>\n";
} else echo "<option value=\"".$i."\">".$i."</option>\n";
}
?>
</select>
<button id="select_coffee_talk_year">anzeigen</button>
<input type="hidden" name="coffee_talk_year_submit" value="true" />​​​​​​​​​​​​​​​​​
</form>
<br />
<div id="coffee_talk"></div>
<br />
<button id="add_coffee_talk">hinzufügen</button>
</div>
Now I want to use this JavaScript to do a delete and edit function:
$(".delete_event").click(function() {
alert('hallo');
currentUserID = $(this).data("event-id");
currentTable = $(this).data("table");
$( "#dialog_delete_event" ).dialog( "open" );
});
$( '#dialog_delete_event' ).dialog({
autoOpen: false,
resizable: false,
height: 170,
modal: true,
buttons: {
'Ja': function() {
document.location = "index.php?section=event_delete&id=" + currentUserID +"&table=" + currentTable;
$( this ).dialog( 'close' );
},
'Nein': function() {
$( this ).dialog( 'close' );
}
}
});
My problem is that the click_function (defined in the links) is not working. I Found out that the ajax form response is not written into the html code. Bet that this is the problem. What can I do to give the links a working click function?
im not sure due to your code's size but this:
$(".delete_event").click(function() {
should be
$(".delete_event").live("click",function() {
because you dynamically create html; the "live" works with that.
Like #Albit, not really sure what your question is, assuming the ajax is working correctly, and the results are visible on the screen, instead of using:
$(".delete_event").click(function() {
try
$(".delete_event").live("click", function() {
This means that elements that satisfy the selector after page load will still trigger an event.
i don't know if i undestood your problem correctly but just use the onclick event in the html tag of the anchor and you will be ok . if this is not the correct answer plese ignore me

Categories