Run php script with AJAX and POST

Viewed 4670

I'm quite new to AJAX. I did some of them with javascript that returns HTML, but I'm struggling with something that I think should be really simple.

I have a header with an inline element:

<header>
  <span class="right_alignment">
    <a id="delete_work" href="">
      <input id ="work_id" type="hidden" value="<?php echo $work_id ?>"/>
      <i class="fa fa-plus" aria-hidden="true">
      </i>
    </a>
  </span>
</header>

I want to send $work_id to a PHP script that executes a MySQL query that deletes this record in the database. It has to be a POST request, and as it is an inline element I can't use a form. So AJAX is the way. This is my try:

$( document ).ready(function() {
  $("#delete_work").click(function () {
    $.ajax({
      url: 'scripts/script-delete-work.php',
      type: 'POST',
      data: $('#work_id').val(),
    });
  });
});

For now script-delete-work.php don't worry me, so is as simple as:

$edition_id = $_POST['work_id'];
echo $work_id;

But this setup doesn't work. I know that it is the simplest form of an AJAX, but I can't figure how to send the data or what is failing. Any help?

Thanks!

EDIT -- Ok, I solved the data thing. What I have now is:

HTML

<span class="span_edit_right">
  <a id="delete_work" href="">
    <input id="work_id" type="hidden" value="<?php echo $work_id; ?>"/>
        <i class="fa fa-trash-o" aria-hidden="true">
        </i>
  </a>
</span>

Script:

$( document ).ready(function() {
  $("#delete_work").click(function () {
    var val = $('#work_id').val();
    $.ajax({
      url: 'scripts/script-delete-work.php',
      type: 'POST',
      data: { "work_id" : val },
      success: function ()
      {
        alert("works!");
      }
    });
  });
});

PHP

<?php echo $_POST['work_id'];

When I click on #delete_work it returns the alert "works", and reload the page, but doesn't show the page with <?php echo $_POST['work_id'];.

5 Answers
Related