how can i use confirm() then refresh the page?

Viewed 245

I made a print page to print tables from there. But when you delete something you will also need the refresh to page to apply the site. Here is my code

<a target="_blank" onclick=" asd()" href="<?= url('/delete?id=' . $row['product_id']) ?>" class="btn success">Delete</a>`

and my delete code is here

function asd() {
  var a = confirm('Are you sure you want to delete this product');
  if (a == 1) {
    setTimeout(function() {
      location.refresh();
    }, 1000);
    return 1;

  } else {
    return 0;
  }
}

When i delete something page doesnt refresh after i click ok.

2 Answers

Was not able to find a location.refresh() method

Try location.reload() instead

In general when some piece of code isn't working, try to isolate specifically what isn't working, a good way to do that in the future is to use console.log instead and see if you got a result. If you did, then try the other function. If it didn't work, then it's the problem

I highly dislike the use of PHP for stuff like this, but if you want to use it, here is something I would change.

You fire an onclick and a href simultaneously, but actually you want to do it one after the other, because if you don't, you are going to run into a race condition.

Also, as someone else already pointed out, there is no refresh method. Use reload.

Here is a solution to that problem:

<a target="_blank" onclick=" asd()" hclass="btn success">Delete</a>

<script>
  const url = <?=json_encode(url('/delete?id=' . $row['product_id']))?>;

  function asd() {
    var a = confirm('Are you sure you want to delete this product');
    if (a == 1) {
      // Make ajax request in js to make it async and do the refresh AFTER it has succeeded
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          // refresh on success
          location.refresh();
        }
      };
      xhttp.open("GET", url, true);
      xhttp.send();
      return 1;
    } else {
      return 0;
    }
  }
</script>

If you want to improve your project further and not only bugfix it, here are a few tips:

  • Make the function names meaningful
  • Use PHP for the backend, if you like, but avoid mixing it with the template code (HTML, JS, CSS)
  • Refactor your backend to use the correct REST HTTP functions (DELETE, PUT, PATCH, ...)
  • Install a library for the ajax instead of using the standard JS XMLHttpRequest. Try Axios or jQuery.
Related