简体   繁体   中英

Removing item from session array Jquery Ajax

I have a table containing a row for each element in an array. I am trying to remove the element when the delete image is clicked (the image's id is deleteRowButton ). At the moment nothing happens when you click the image, however if I remove the var index line, the table row will fade out as expected (but of course the array element is not removed.

$(document).on('click', '#deleteRowButton', function() {
    var index = $(this).closest('tr').attr(id); 
   //Set index to the id of table row (number corresponding to their position in the array)
    remove_index(index); 
    $(this).closest("tr").fadeOut('slow');
    return false;
});

function remove_index(value) {
    $.post("./remove_array_item.php", {index:value});
}       

Here is my code in remove_array_item.php to remove the array element:

<?php  
include("./config/init.php"); //Contains session_start() etc. 

$index = $_POST['index']; //index variable passed in
$ca = $_SESSION["objColl"]; //get array from session variable
$ca->delLineItem($index); //delete item of array at index
$_SESSION["objColl"] = $ca; //store array as session variable 
?>

So what I am wondering is:

  1. Why does the jquery function stop firing if I include:

var index = $(this).closest('tr').attr(id);

ie if I comment it out, the function will make the table row fade out.

  1. What is wrong with my function in remove_array_item.php because even when I remove the var index and just pass a value for the index like so

remove_index(1);

It still does not remove the item from the array and so when I refresh the page, the item is back in the table.

Change var index = $(this).closest('tr').attr(id); to var index = $(this).closest('tr').attr('id'); You forgot the quotes around id .

I think you made a mistake by binding on click event to an Id, where as you will have multiple rows. You need to share the HTML to clarify this issue.

A wild guess. Change the #deleteRowButton (id) to .deleteRowButton (class).

Also note that attr() function only accept string as parameter.

$(this).closest('tr').attr("id");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM