Search code examples
ajaxlift

How to make an AJAX call with Confirm in lift?


I'm new to lift, and want to implement following in my project:

There is a "delete" link in the page, when user clicks it, there will be a confirmation with text "are you sure to delete?". If user clicks on "yes", it will make an AJAX call to delete something on the server side, then show a notice "Operation complete", and after 3 seconds, the page will be reloaded.

How to implement this in lift? I have searched a lot, but not found an correct example.

I can only do this for now:

SHtml.a( ()=>Confirm("are you sure to delete", ???), "delete" )

Solution

  • The easiest way is to use the SHtml.ajaxInvoke in conjunction with JsCmds.Confirm. It will create a server side function and return a tuple with the functionId and JsCmd. So, something like this should do what you are looking to do:

    SHtml.a( () => {
      JsCmds.Confirm("Are you sure you want to delete?", {
        SHtml.ajaxInvoke(() => {
          //Logic here to delete
    
          S.notice("Operation complete")
          JsCmds.After(3 seconds, JsCmds.Reload) //or whatever javascript response you want, e.g. JsCmds.Noop 
        })._2
      })
    }, "delete")
    

    In the above - clicking on the link will trigger the confirmation. If you select OK, then it will issue an ajax call to your function and display a notice. You can use that in any of the SHtml items that require a JsCmd.

    If you want to have the page redirect after a timeout, you can just write a client-side javascript function to do what you need and use JsCmds.Run to call it.