'Execute only one time and then wait set period of time before executing again

I am trying to make a pop up execute only 1 time for a user every 30 days. Currently the pop up is being executed in an infinite loop. Every time I trigger it executes. Over and over and over again. It should only happen 1 time and then set a cookie of some sort or a check and 30 days later if the user comes back it will execute again. I have tried setting cookie in PHP. Using the one. jQuery method. Setting cookie in jQuery. Using a flag variable. All these things and it still just executes alwayse. I need solution in PHP or jQuery preferably.

<script>
$( document ).ready(function() {

var SetWait;
var filledPhone;
//setTimeout(function(){}, 1500);//close timeout
SetWait = 1;

setTimeout(function(){SetWait=0;}, 1200);

$("body").mouseleave(function() {
    if(SetWait==0){
        if(!filledPhone){
    $("#myModalpopup").fadeIn();
    $(".modal-backdrop").fadeIn();
    $(".modal-content").fadeIn();
    
        }//close filled email check
    }
});//close function

$(".close").click(function() {
    SetWait = 1;
    $("#myModalpopup").fadeOut();
    $(".modal-backdrop").fadeOut();
    $(".modal-content").fadeOut();
    setTimeout(function(){SetWait=0;}, 2500);
});//close function

    
$("#twillioPopup").click(function() {
    var the_number = $("#custPhone").val(); //email user enters


    if(!the_number){
        alert('Please enter phone number.');    
    }else{
        $("#myModalpopup").fadeOut();
        $(".modal-backdrop").fadeOut();
        $(".modal-content").fadeOut();
        filledPhone = the_number;   
        /////////  DO AJAX TO SAVE EMAIL AND CART ID ETC /////////
            $.ajax({
                type: 'POST',
                url:  'ajax/twillioPopup.php',
                data: {the_number:the_number},
                success: function( response ){
                    $('#success_message').html(response);
                }
            }); //close ajax    
        /////////  DO AJAX TO SAVE EMAIL AND CART ID ETC /////////
    }//close if else
});//close click    
    

});//close ready
</script>


Solution 1:[1]

Try to create a php COOKIE that expires after 30 days. If the cookie is not set, then run the code and set it, else do nothing. Something like this?

<?php

if(isset($_COOKIE['yourCookieName'])){
   //Do nothing
} else {
   $cookie_name = "yourCookieName";
   $cookie_value = "set";
   setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
   ?>
    //Break out of php and run your javascript here
   <?php 
}
?>

This should detect if the cookie is set, and if its not, then run the javascript once and then set the cookie (if they revisit in the next 30 days whilst the cookie is still active, the javascript will be ignored)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1