0

I'm writing a jquery code and calling a JavaScript function through it on a jsp page.

This is the jquery function

$(function () {

    $('#defaultCountdown').countdown({until: $.countdown('//SomeTime'),onExpiry: liftOff});

});

liftOff is a javascript method which is called after the specified time expires.

This is the JavaScript function

<script>
function liftOff() {

    alert("Before Delete");
    &lt;% DAO_Object.deleteRecord(ID);%&gt;
    alert("After Delete");

}

</script>

Now here the problem is, the line <% DAO_Object.deleteRecord(ID);%> is getting executed before the function call and the record from database is getting deleted. The alert statements are executing correctly AFTER the function call.

Am i calling the deleteRecord method incorrectly?

Sahan Serasinghe
  • 1,591
  • 20
  • 33
  • You're conflating client side code and server side code. See https://stackoverflow.com/a/23740549/1366624 – lxe Jul 20 '17 at 23:29
  • @lxe OP is trying to run JSP code dependent on browser events. It's more akin to this post: https://stackoverflow.com/questions/1280767/how-do-i-run-php-code-when-a-user-clicks-on-a-link – Ezra Chu Jul 20 '17 at 23:32

1 Answers1

3

You are mixing your server-side JSP logic with your client-side JavaScript logic.

Everything between <% %> runs on your servlet when it's processing the request, so the record is already deleted by the time you get the response in the browser. If you look at the HTML/JS you are receiving in the browser using Chrome DevTools or similar tool, you will see that there is nothing between those alert(...) calls.

Your solution here is to setup a route that handles the deleteRecord() on the server-side, and call it via AJAX in your liftOff() method. So liftOff() would look something like this:

// assuming `id` is a string here
function liftOff(id) {

  alert("Before Delete");

  // You'll have to setup this endpoint to run 
  // your `DAO_Object.deleteRecord(ID);` code 
  // in your JSP code.

  $.get("/delete/my/record/" + id, {
    error: function(e){
      // some kind of error occurred in making the request
    },
    success: function(resp){
      // `resp` is the response from the server
      alert("After Delete");
    }
  });
}
Ezra Chu
  • 832
  • 4
  • 13