2

I have a form with URL:

localhost:83/mysite/item/UpdateItems/225

I have a temporary table in which I have loaded data and display in my form from temporary table.

When I refresh the page I don't want to fire an ajax call and truncate the table. But if I click on another link from menu then I do want to fire the ajax call and truncate tables.

Is it possible?

I have used beforeunload for truncate table when click on another menu:

 $(window).on('beforeunload', function(){
     //My ajax code for truncate table
});

But this works on page refresh also, which I don't want. So I tried with matching string in URL:

$(window).on('beforeunload', function(e){
    if (document.URL.indexOf("UpdateItems") > -1) {

        console.log("page refresh");

     }else{
         console.log("not refreshed");  
      }
});

But this always go in first page refresh condition even if I have clicked on another menu.

rjmunro
  • 27,203
  • 20
  • 110
  • 132
Dhara
  • 1,431
  • 4
  • 29
  • 47

2 Answers2

0

Try this , it will definitely work,

    <SCRIPT language="javascript">

    window.onbeforeunload=before;

    function before(evt)
    {
       if(window.location.toString().indexOf("UpdateItems") > -1) { 

        console.log("page refresh");

       }
       else{
         console.log('Not');
       }
    }
    </script>
Dimag Kharab
  • 4,439
  • 1
  • 24
  • 45
  • This is not working. it always go in `if (document.URL.indexOf("UpdateItems") > -1) ` even if i click on another menu. – Dhara Aug 19 '15 at 11:54
  • It doesn't work :(. I want alert on close of that page, but not in page refresh. – Dhara Aug 27 '15 at 12:03
0

If (and this is a pretty big if) the refresh is done by clicking a link on the page (and not say from a script or by the user clicking the browsers refresh button) this approach might work:

Set a flag to false whenever someone click a link that should not lead to the table being truncated, and only run the code if the flag is true:

// As default the flag is true.
flagTruncate = true;

// When someone clicks a link with UpdateItems in the URL, the flag is  set to false.
$("a[href*='UpdateItems']").click(function () {
    flagTruncate = false;
});

//Only truncate the table when the user is leaving if the flag is still true.
$(window).on('beforeunload', function() {
    if(flagTruncate) {
        //Truncate the table.
    }
});
Anders
  • 8,307
  • 9
  • 56
  • 88
  • Thats also not working. i tried it. i want to truncate table any redirection to another page. only on refresh i don't want it. so that i match `UpdateItems`. – Dhara Aug 27 '15 at 12:10
  • 1
    As I stated in my answer, it will only work under certain conditions. Within those conditions it works; outside of them it does not work. I do not know how to do a full solution to the problem without any conditions. – Anders Aug 27 '15 at 12:14