PROBLEM SOLVED.. I update my code accordingly.. Thanks all
Intro: My code display array of message traces (each message display in grey-panel). User can delete unwanted message by click on delete button, the message will be deleted in both DB and disappear from screen.
Seems my delete function is not working.. Appreciate for advice.. I don't know AJAX.. this is my first try. Thanks in advance.
The following are my code:
ajax code:
$(document).ready(function(){
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
var $btn = $(this),
$li = $btn.closest('li');
var traceId = $li.data('trace-id');
jQuery.ajax({
type: 'post',
url: 'traceDelete',
dataType: 'text',
data: { 'traceId': traceId },
success: function (res) {
if (res === '1') {
$btn.fadeOut();
}
},
error: function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
part of view code:
<ul id="responds">
<?php foreach ($line as $dataName => $contents){ ?>
<li data-trace-id="<?php echo $contents->trace_id; ?>">
<div class="grey-panel" style="text-align:right">
<div class="del_wrapper" id="<?php echo $contents->trace_id; ?>">
<a href="#" class="del_button" id="<?php echo $contents->trace_id; ?>" data-hover="tooltip" title="Delete this message <?php echo $contents->trace_id; ?>" >
<i class="fa fa-times"></i>
</a>
</div>
<div class="col-sm-12 col-xs-12">
<?php print $contents->trace_hdr.'<br />';
print $contents->trace_src.'<br />';
print $contents->trace_dest.'<br />';
// some other things ?>
</div>
</div>
</li>
<?php } ?>
</ul>
controller code:
public function traceDelete($traceID) {
if ($traceId = $this->input->post('traceId')) {
return $this->model_general->deleteTrace($traceId);
}
return false;
}
model code:
public function deleteTrace($id) {
$this->db->where('trace_id', $id);
$this->db->delete('trace_tbl');
return $this->db->affected_rows() > 1 ? true:false;
}
First, you are using the id attributes wrong. They are meant to be unique as in appear on one element and not multiple as you have done. (As well, id attributes cannot start with a digit.) There's really no need to put it on multiple containing elements as you can easily traverse to the parents or children with jQuery's .find(), .parent(), .closest(), and other traversing methods. However, this should not be the cause of your problem.
Now, what I do think is the cause of your problem is that you are passing the 2nd character of your id attribute into your AJAX request.
$(document).ready(function(){
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
// assign the ID e.g. "abc" to clickedID
var clickedID = this.id;
// problem: assign the second character of your ID i.e. "b" into DbNumberID
var DbNumberID = clickedID[1];
// assign the same value to myData (which is redundant)
var myData = DbNumberID;
$(this).hide();
jQuery.ajax({
type: "POST",
url: 'traceDelete',
dataType:"text",
// sending "myData=b"
data: { myData: myData },
success:function(traceDelete){
alert("Deleted");
$(DbNumberID).fadeOut();
},
error:function(xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
I am not too familiar with CodeIgniter anymore, but you need to get value from the $_REQUEST or $_POST array or use their built-in function.
$myData = $this->input->post('myData'); // because you are sending myData
EDIT
This is untested but here's how I would do it.
HTML
First, let's use HTML5 data attribute call it data-trace-id. This will be used instead of your numerous improper usages of id attributes.
<ul id="responds">
<?php foreach ($line as $dataName => $contents) : ?>
<li data-trace-id="<?php echo $contents->trace_id ?>">
<div class="grey-panel" style="text-align: right">
<div class="del_wrapper">
<a href="#" class="del_button" data-hover="tooltip" title="Delete this message <?php echo $contents->trace_id ?>">
<i class="fa fa-times"></i>
</a>
</div>
<div class="col-sm-12 col-xs-12">
<?php echo $contents->trace_hdr ?><br />
<?php echo $contents->trace_src ?><br />
<?php echo $contents->trace_dest ?><br />
<!-- etc -->
</div>
</div>
</li>
<?php endforeach ?>
</ul>
JavaScript
Next, let's simplify your JavaScript. I'll use the dreaded alert() for debugging purposes -- but it's usually better to use console.log().
$(function() {
$("#responds").on("click", ".del_button", function (e) {
e.preventDefault();
// keyword 'this' refers to the button that you clicked;
// $(this) make a jQuery object out of the button;
// always good idea to cache elements that you will re-using;
var $li = $(this).closest('li');
// get the associated trace ID from the list-item element;
var traceId = $li.data('trace-id');
alert('trace ID ' + traceId);
// assuming you only want to hide the message only if it has been been successfully deleted from the DB?
// if that is the case, then you have to wait for the AJAX response to tell you whether it was
jQuery.ajax({
type: 'post',
url: 'traceDelete',
dataType: 'text',
// notice how I am using 'traceId'? on the server-side, the data will accessible by using $_POST['traceId'] or $this->input->post('traceId')
data: { 'traceId': traceId },
// look at the response sent to you;
// if I am not mistaken (boolean) true and false get sent back as (strings) 1 or 0, respectively;
// so if the response is 1, then it was successfully deleted
success: function (res) {
alert('AJAX response ' + res);
if (res === '1') {
alert('hiding button');
// hide the message
$li.fadeOut();
}
},
error: function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
});
PHP
Lastly, we take the value from the $_POST array. Check whether there is a value: if so, delete the item; otherwise ignore it.
public function traceDelete()
{
if ($traceId = $this->input->post('traceId')) {
echo $this->model_general->deleteTrace($traceId) ? '1' : '0';
}
echo '0';
}
remove var DbNumberID = clickedID[1]; var myData = DbNumberID;, as its not needed. Directly assign data: { myData: clickedID },. Also get value of myData in controller via POST.
public function traceDelete() {
$traceID = $this->input->post('myData');
if($traceID)
return $this->model_general->deleteTrace($traceID);
return false;
}
Related
I try to display the departments in my website as tabs, when click one tab it will display the data related to this department according to department_id.
I try this code Execute php function only when clicked (wordpress) but I need the tabs number to be dynamic.
<div class="tabs">
<ul>
<?php
$arr1=array(2,3,5,10,22,25,27,28,29,30);
$arr2=array("dep1","dep2","dep3","dep4",
"dep5","dep6","dep7","dep8","dep9","dep10");
for($i=0;$i<10;$i++){?>
<li><a href="#tab" id="<?php echo $arr1[$i]; ?>"><?php echo
$arr2[$i];?>
</a></li>
<?php } ?>
</ul>
</div>
<div id="tab" class="section">
</div>
functions.php:
<?php
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id=$_GET[id];
/** Here I print data according to $dept_id **/
die();
}
?>
script.js:
jQuery(document).ready(function() {
jQuery('.tabs a').click(function(e) {
e.preventDefault();
var tab_id = jQuery(this).attr('id');
console.log(tab_id);
jQuery.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'tabsfunction', id: tab_id}),
success: function(data){
jQuery('#tab').html(data);
},
error: function(data)
{
alert("Error!");
return false;
} });}); });
it dose not work, it displays data only for one tab.
console.log(tab_id) ----> it display the id for the first tab clicked
and did not change when click another tab.
You need to echo the output from the tabsfunction and also add the die() at end of the function like below :
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id=$_GET[id];
/** Here display data according to $dept_id **/
echo 'output';
die();
}
Hope it helps.
can you please correct your tab list code.
<div class="tabs">
<ul>
<?php
$arr1 = array(2,3,5,10,22,25,27,28,29,30);
$arr2 = array("dep1","dep2","dep3","dep4","dep5","dep6","dep7","dep8","dep9","dep10");
for($i=0;$i<10;$i++)
{
?>
<li><?php echo $arr2[$i];?></li>
<?php
}
?>
</ul>
</div>
<?php for($i=0;$i<10;$i++)
{
?>
<div id="tab<?php echo $arr1[$i]; ?>" class="section">
</div>
<?php
}
?>
Also return proper response on ajax request.
<?php
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id = $_GET[id];
echo $dept_id; // this just dispay requsted id as tab content here you can add your logic for dynamic content based on id
die();
}
?>
And your script js look like this
jQuery(document).ready(function() {
jQuery('.tabs a').click(function(e) {
e.preventDefault();
var tab_id = jQuery(this).attr('id');
console.log(tab_id);
jQuery.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'tabsfunction', id: tab_id}),
success: function(data){
jQuery('#tab'+tab_id).html(data);
},
error: function(data)
{
alert("Error!");
return false;
} });}); });
I'm using laravel5.5 Ajax paging. I am the HTML part assembled in the controller. When I clicked on page second, I jumped to this method. How to make the compiled HTML code continue to display on the page?
After clicking on the second page, a string of JSON data is returned. This is a problem. How can we make the data on the second page continue to display in the original page?
PHP
//Screen video, playback volume and key points.
public function accept(Request $ request){
$id=$_GET['id'];
$summer=$_GET['key'];
$name=DB::table('vd_category')->where('address',$summer)->value('name');
if($id=='1'){
$video=DB::table('vd_video_'.$summer)->orderBy('state','desc')->paginate(25);
}else if($id=='2'){
$video=DB::table('vd_video_'.$summer)->orderBy('thumbs','desc')-
>paginate(25);
}
$data='';
foreach($video as $list){
$data.='<div class="col-md-1-5 col-sm-4 col-xs-6" style="padding:0
5px;"><div class="movie-item">';
$data.="<a style='position:relative;display:block;' title='$list-
>video_name' target='_blank' href='details?id=$list->id&key =$summer'>";
$data.="<img alt='$list->video_name' title='$list->video_name'
src=\"uploads/$list->image_address\" height=\"230px\" width='100%'>";
$data.="<button class='bdtag'></button>";
$data.="</a>";
$data.="<div class=\"meta\"><div
style=\"width:100%;overflow:hidden;height:20px;\">";
$data.="<a href='/details?id='$list->id'&key='$summer'
target='_blank' title='$list->video_name' class=\"movie-name\">$list-
>video_name</a>";
$data.="<span class=\"otherinfo\"> 5.0分</span></div><div
class=\"otherinfo\">类型:$name</div></div></div></div>";
}
$datav['1']=$data;
$datav['2']="<div>"."{$video->appends(['id' =>
$id,'key'=>$summer,'name'=>'page'])->links()}"."</div>";
return json_encode($datav);
}
HTML
<div id="data">
#foreach($video as $list)
<div class="col-md-1-5 col-sm-4 col-xs-6" style="padding:0 5px;">
<div class="movie-item">
<a style="position:relative;display:block;" title="{{$list-
>video_name}}" target="_blank" href="/details?id={{$list->id}}&key=
{{$status}}">
<img alt="{{$list->video_name}}" title="{{$list-
>video_name}}" src="{{asset('uploads')}}/{{$list->image_address}}"
height="230"
width="100%">
<button class="bdtag"></button>
</a>
<div class="meta">
<div style="width:100%;overflow:hidden;height:20px;"><a
href="/details?id={{$list->id}}&key={{$status}}" target="_blank" title="
{{$list-
>video_name}}" class="movie-name">{{$list->video_name}}</a><span
class="otherinfo"> 5.0分</span></div>
<div class="otherinfo">类型:{{$namme}}</div>
</div>
</div>
</div>
#endforeach
</div>
</div>
</div>
<div id="datav" style="background:#FFF;padding-left:15px;">
{{$video->appends(['id' => $page,'name'=>'page'])->links()}}
</div>
JavaScript
<select name="" required id="where_id" style="float: right;padding-
left:10px;border-left:8px;width: 90px;height: 30px;">
<option value="">Click screening</option>
<option value="1">Sort by play volume</option>
<option value="2">Ranking by points</option>
</select>
<input type="hidden" id="summer" value="{{$status}}">
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#where_id").change(function () {
var id=$("#where_id").val();
var summer=$("#summer").val();
$.ajax({
type:"get",
url:"accept",
dataType:'json',
data:{id:id,key:summer},
success:function (event){
$("#data").html(event[1]);
$("#datav").html(event[2]);
}
});
});
</script>
It has been solved.js has been modified.
That is, the parameters carried by the URL through the Ajax request to the
back-end again, and then the back-end returned JSON data inserted into the
specified location again, probably this is the solution, my English is not
very good, please forgive me.
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#where_id").change(function () {
fun();
});
function fun() {
var id=$("#where_id").val();
var summer=$("#summer").val();
$.ajax({
type:"get",
url:"accept",
dataType:'json',
data:{id:id,key:summer},
success:function (event){
$("#data").html(event[1]);
$("#datav").html(event[2]);
pagedata();
}
});
}
function pagedata(){
$(".page-item a").click(function (){
var href=this.href;
this.href="javascript:void(0);";
var id=getQueryVariable('page',href);
var key=getQueryVariable('key',href);
var page=getQueryVariable('page',href);
$.ajax({
type: "get",
url: "accept",
dataType: 'json',
data: {id: id, key: key,page:page},
success:function (event){
$("#data").html(event[1]);
$("#datav").html(event[2]);
pagedata();
}
})
})
}
// Intercept the parameter values carried by URL, such as page parameters
//and some custom parameters.
function getQueryVariable(name,url) {
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
var data=url.slice(url.indexOf('?'));
var r =data.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
}
return null;
}
</script>
I am trying to change the value of a span after using jQuery.ajax.
JavaScript
$(document).on('click', '.kssico', function(event) {
var for_uid = $(this).parents("li").attr('data'),
for_name = $(this).parents("li").attr('unme'),
dataString = "for_uid=" + for_uid + "&for_name=" + for_name;
$.ajax({
type: "POST",
url: "include/ajax.php",
data: dataString,
success: function (html) {
if(html=="300") {
$('#myModal .modal-body p').html("Error Please Try Again.");
$('#myModal').modal('show');
}
else {
$(this).parents("li span.mi-val").html(html);
$('#myModal .modal-body p').html("The Requested Action Has Been Notified To Your Friend.");
$('#myModal').modal('show');
}
}
});
});
HTML
<li class="mispan main-span" >
<div class="thumbnail">
<h3 class="miheader">Dewashree Singh</h3>
<a >
<div class="miprofile-pic-cnt" ></div>
</a>
<div class="caption">
<p>
<a href="#" class="btn kssico miclickks">
<img src="/lisps.png"><span class="mi-val">0</span>
</a>
<a href="#" class="btn bdico miclickbd">
<img src="/besd.png"><span class="mi-val">1</span>
</a>
</p>
</div>
</div>
</li>
When I click on a.miclickks it should complete the Ajax call and return a value too be placed inside the span on the button anchor. However, nothing is being changed!
jsFiddle
I don't know what your whole code looks like, but you should be able to modify this to do what you are trying to:
$('#id').on('click', function() {
var that = this;
$.ajax({
url: 'wherever.php',
success: function(html) {
$(that).find("li span.mi-val").html(html);
}
});
It looks like you have two problems. The first is that as #Barmar posted above, mi-val is a child of micclickks, not a parent. The second is that your ajax complete function is asynchronous, so $(this) isn't what you expect it will be. Both of these are solvable though.
Your code is a bit messy and your html is missing the proper attributes, but this is I think roughly what you want:
$('.kssico').on('click', function(event) {
var for_uid = $(this).parents("li").attr('data'); //the li element in your html doesn't have a data attribute
var for_name = $(this).parents("li").attr('unme'); //the li element in your html doesn't have a 'unme' attribute
var dataString = "for_uid=" + for_uid + "&for_name=" + for_name;
$.ajax({
type: "POST",
context: this,
url: "include/ajax.php",
data: dataString,
success: function (html) {
if(html=="300")
{
$('#myModal .modal-body p').html("Error Please Try Again.");
$('#myModal').modal('show');
}
else
{
$(this).parents("li span.mi-val").html(html);
$('#myModal .modal-body p').html("The Requested Action Has Been Notified To Your Friend.");
$('#myModal').modal('show');
}
}
});
});
Hello at the moment i'm trying to use jQuery in order to get ids of multiple fields with ajax and send the data to remove it via php.
So far i was able to delete the item but i can't remove other ids so for and example:
i have a for loop what will get the information off the database as:
for($i=0; $i < $data; $i++) {
echo "
<div class='list-item' data-action='delete' id='".$Data[$i]['ID']."'>
<a class='title link' href='".$Data[$i]['URL']."' target='_blank'>".$Data[$i]['name']."</a>
<span class='checkbox' id='".$Data[$i]['ID']."' value='".$Data[$i]['ID']."'></span>
<div class='thumb'>
<img src='".$Data[$i]['thumb']."' alt='' width='110' height='99'>
<span class='attr'>".$Data[$i]['width'].'x'.$Data[$i]['height']."</span>
<span class='size'>".$Data[$i]['size']."</span>
</div>
<div class='date'>".$Data[$i]['Date']."</div>
</div>
";
}
notice how you see the $Data[$i]['ID'] with that it'll print out :
<div class="list-item" data-action="delete" id="89">
<a class="title link" href="http://URL" target="_blank">NAME</a>
<span class="checkbox" id="89" value="89"></span>
<div class="thumb">
<img src="thumb.png" alt="" width="110" height="99">
<span class="attr">100x100</span>
<span class="size">85.2 KB</span></div>
<div class="date">2012-06-11 01:25:20</div>
</div>
<div class="list-item" data-action="delete" id="90">
<a class="title link" href="http://URL" target="_blank">NAME</a>
<span class="checkbox" id="90" value="90"></span>
<div class="thumb">
<img src="thumb.png" alt="" width="110" height="99">
<span class="attr">100x100</span>
<span class="size">85.2 KB</span></div>
<div class="date">2012-06-11 01:25:20</div>
</div>
so with that i'm using jQuery to add a class to both class="checkbox" and class="list-item" with selected so that when the event of click or .on('click' function, it will do a confirm window saying "Are you sure you want to remove?" if ok then grab the id of the elements for each and post the data with ajax to have the item removed instantly!
The thing is i need it to work upon multiple ids and have it not add the class of selected to all of class="checkbox" and class="list-item" need it to be specific as in, i choose the items of the ids with 84,94,99,& 100 if i do that everything that is selected should have that class of selected not every id
here is my attempt trying to get this to work
<script>
$(function (){
$('.list-item').on('click', function(e) {
$(this).addClass("selected");
if(window.confirm('Are you sure you want to remove?')) {
id = $(this).attr("id");
//alert(id);
$.ajax({
type: 'post',
url: 'something.php?action=delete&id='+id,
dataType: 'json',
data: {
}, success: function(data) {
if(data.error === true)
{
$.errRorBar({ bdS: "error", html: data.message , delay: 5000 });
}
else
{
$.errRorBar({ bdS: "success", html: data.message , delay: 5000});
}
}, error: function(XMLHttpRequest, textStatus, errorThrown) {
$.errRorBar({ bdS: "error", html: "Opps! Something went wrong!" , delay: 5000 });
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
// console.log(XMLHttpRequest.responseText);
}
});
return false;
}
});
});
</script>
So how can i do this and how can i make the refresh to update the list making it hide or remove it or something?
At the moment, it will remove the item from the database but only one time for the one item i selected even if i have multiple items chosen,i'll get a return of "fail to remove"
Anyone here can help me out?
i think i'm missing something but hopefully this was a good explanation of my situation
Thanks
After looking into your code i have found few glitches:
Element div of class list-items and span of class checkbox having same ids which is against the dom specification. (use prefix before ids like div-89, span-89 etc.).
You are using the request type post but posting the data in url which is get method.
You are sending request on click event of checkbox so it fires everytime when you select it so you cannot delete multiple items using this approach.
Solution:
create a seperate button of delete and send request on click of that button.
Your code would be:
$('.list-item').click(function() {
$(this).addClass('selected');
});
$(.delete).click(function() {
var delIds = new Array();
$('.selected').each(function() {
delIds.push($(this).attr('id'));
});
$.ajax({
url: 'something.php?action=delete&id='+delIds.join(),
dataType: 'json',
success: function(data) {
if(data.error === true)
{
$.errRorBar({ bdS: "error", html: data.message , delay: 5000 });
}
else
{
$.errRorBar({ bdS: "success", html: data.message , delay: 5000});
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$.errRorBar({ bdS: "error", html: "Opps! Something went wrong!" , delay: 5000 });
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
// console.log(XMLHttpRequest.responseText);
}
});
});
Hope this helps you
I'm trying to delete a li item using jquery, but its not working. Here's my code:
the html file:
<li>
<img class="avatar" src="images/$picture" width="48" height="48" alt="avatar" />
<div class="tweetTxt">
<strong>$username</strong> $auto
<div class="date">$rel</div>
$reply_info
<div class="date"></div>
<a class ="delbutton" href="#" id = $id> Delete </a>
</div>
<div class="clear"></div>
</li>
The jquery file:
$(function () {
$(".delbutton").click(function () {
var del_id = element.attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function () {}
});
$(this).parents(".record").animate({
backgroundColor: "#fbc7c7"
}, "fast")
.animate({
opacity: "hide"
}, "slow");
}
return false;
});
});
the delete.php file:
<?php
include("includes/connect.php");
if($_POST['id'])
{
$id=$_POST['id'];
$sql = "delete from {$prefix}notes where id='$id'";
mysql_query( $sql);
}
?>
There is no element in your HTML with a class of record. I would try something like this:
<li class="record">
<!-- a bunch of other stuff -->
<a class="delbutton" href="#">Delete</a>
</li>
then in the JS:
$(function ()
{
$(".delbutton").click(function ()
{
if (confirm("..."))
{
$.ajax({ /* ... */});
$(this).closest(".record").fadeOut();
}
return false;
});
});
If your div look like this:
<ul>
<li>One | <a href='#' class='delete'>Delete</a></li>
<li>Two | <a href='#' class='delete'>Delete</a></li>
<li>Three | <a href='#' class='delete'>Delete</a></li>
<li>Four | <a href='#' class='delete'>Delete</a></li>
</ul>
jQuery:
jQuery(document).ready(function(){
jQuery('.delete').live('click', function(event) {
$(this).parent().fadeOut()
});
});
Check: http://jsfiddle.net/9ekyP/
EDIT:
You can remove your li after getting response in success function something like this:
jQuery(document).ready(function(){
jQuery('.delbutton').live('click', function(event) {
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
$(this).parent().parent().fadeOut();
}
});
});
});
There are several issues with your code...
element.attr("id") references undeclared element but this should probably be $(this).attr("id")
The <li> block has no class ".record" either
EDIT: You only fade your <li> but do not actually remove it from the DOM (don't know if this was deliberate though)
The <a>'s ID is not quoted (and not escaped either... as are the other strings you insert in PHP (EDIT) and the ID you use in your delete script - this is very dangerous as it allows cross-site scripting / XSS and SQL injection as TokIk already pointed out)
PHP:
echo '<li class="record">
<img class="avatar" src="images/'.htmlentities($picture).'" width="48" height="48" alt="avatar" />
<div class="tweetTxt">
<strong>'.htmlentities($username).'</strong> '.htmlentities($auto).'
<div class="date">'.htmlentities($rel).'</div>'.htmlentities($reply_info).'<div class="date"></div> <a class="delbutton" href="#" id="'.htmlentities($id).'"> Delete </a>
</div>
<div class="clear"></div>
</li>';
JavaScript:
$(document).ready(function() {
$(".delbutton").click(function(){
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
alert('success');
},
error: function(){
alert('error');
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
EDIT: Delete script (note the additional error check that $_POST['id'] exists and the pseudo-function for quoting the ID):
<?php
include("includes/connect.php");
if( isset($_POST['id']) ) {
$id = quote($_POST['id']);
$sql = "delete from {$prefix}notes where id='$id'";
mysql_query( $sql);
}
?>
I am assuming that '.records' is the container.
You can pass through your ID value to make <li> unique, result being:
<li id='record_12'>
//CONTENT
</li>
<li id='record_13'>
//CONTENT
</li>
And change your SUCCESS script to the following:
$(".delbutton").click(function(){
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
//Getting the unique LI and fading it out
$('#record_' + del_id).fadeOut();
}
});
Your code works fine well.I was trying to code a form that has multiple textbox, then after each textbox threre will be link called add which POST call the other php called addnew.php.
In addnew.php data will we added to database(postgres). But I am geting problem while getting the post variable itself.
this is my code for form (I will chage for multiple textbox once it works fine)
script:
<script type='text/javascript'>
$(window).load(function() {
jQuery(document).ready(function() {
jQuery('.add').live('click', function(event) {
var da = $('form#myform').serialize();
alert(da);
$.ajax({
type: "POST",
url: "addnew.php",
data:da,
success: function(data) {
if (data === "ok") {
$(this).parent().fadeOut();
$('#results').html(data);
}
else {
alert(data);
}
}
});
});
});
});
Form
<form name='myform' id='myform'>
<input name='da' type='text' id='da' value='none'>
<a href='#' class='add'>Add</a>
</form>
addnew.php code here
<? php
if( isset($_POST['da']) )
{
echo (da);
}
?>