-1

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})      
3
  • Do you mean that when users click on one of the 'Delete' buttons, it should make an AJAX call to the server relating to that file? Commented May 18, 2014 at 21:14
  • yes @halfer and i want it sent to a new file called remove.php and then delete it from there Commented May 18, 2014 at 21:22
  • OK, good - @GluePear is on the right lines. Also, it's worth checking that filenames do not create invalid id values - files can have all sorts of characters that I expect element ids cannot. Commented May 18, 2014 at 21:27

1 Answer 1

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;
});
Sign up to request clarification or add additional context in comments.

14 Comments

$(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; }); });
That looks about right, try it? Keep an eye on your JS console to check for errors, of course.
Thanks for the suggestion @halfer, I've added the click handler.
@zan, the one error you have is fixed in GluePear's answer - use $(this) to capture the element that raised the event.
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.