I want to know how to write a pice of PHP code into JavaScript/Ajax.
This is my PHP code:
if ($folder = opendir('data/Tasklist/')) {
while (false !== ($file = readdir($folder))) {
if ($file != '.' && $file != ".."){
$data=file_get_contents("data/Tasklist/".$file);
$poc=explode(";",$data);
echo '<li class="taskli">
<button id="'. $file . '" class="Del"> Delete </button>
'. $poc[0] . " " . $poc[1] . '<div class="hidinfo">' . $poc[2] . '</div></li>';
}
}
closedir($handle);
}
And i want to write : id="'. $file . '" inside this code:
$.post( "data/remove.php",{HERE})
1 Answer 1
Since you're storing the $file variable in the <button> id, you can grab it from there:
$('.Del').click(function(){
var file = $(this).attr('id');
$.post( "data/remove.php",{id:file});
return false;
});
answered May 18, 2014 at 21:12
GluePear
7,78321 gold badges73 silver badges127 bronze badges
Sign up to request clarification or add additional context in comments.
14 Comments
zan
$(document).ready(function(){ $(".Del").click(function(event){ var file = $('.Del').attr('id'); $.post( "data/remove.php",{id:file}) .done(function(id){ }); console.log("delete clicked"); event.preventDefault(); return false; }); });halfer
That looks about right, try it? Keep an eye on your JS console to check for errors, of course.
GluePear
Thanks for the suggestion @halfer, I've added the click handler.
halfer
@zan, the one error you have is fixed in GluePear's answer - use
$(this) to capture the element that raised the event.zan
In the console i get no error,i dont know if works or not tho.I must write the code in remove.php also to delete the files i send there.
|
default
idvalues - files can have all sorts of characters that I expect element ids cannot.