Search code examples
phpformsrefreshdetectionsubscribe

Make an error to pop-up without refresh


I have this php code, which basically checks if the e-mail is correct and if it is, it saves the e-mail in a *.txt file (I'm using it for a subscribe form), if it's not it pop-ups an error div, but it pops it up with refreshing the whole web page, and when it's in the bottom you have to scroll to actually see the error.

<?php
if ( isset($_POST['submit']) ) {
    if( isset($_POST['inputEmail']) ) {
        $email = trim($_POST['inputEmail']);
        if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            echo "<div class='wrong'>This e-mail is invalid.</div>";
        }
        else {
            $data = $email . "\n";
            $ret = file_put_contents('emailAddresses.txt', $data, FILE_APPEND | LOCK_EX);
            if ( $ret !== FALSE ) {
                header('Location: thanks.html');
                exit;
            }
        }
    }
}
?>

Solution

  • What you want to do is send your request with AJAX using javascript or jQuery.

    With JavaScript:

    <script type="text/javascript">
    function loadXMLDoc() {
        var xmlhttp;
    
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 ) {
               if(xmlhttp.status == 200){
                   //Request worked, Do something
                   document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
               }
               else if(xmlhttp.status == 400) {
                  alert('There was an error 400')
               }
               else {
                   alert('something else other than 200 was returned')
               }
            }
        }
    
        xmlhttp.open("GET", "ajax_info.txt", true);
        xmlhttp.send();
    }
    </script>
    

    With jQuery:

    $.ajax({
        url: "test.php",
        context: document.body,
        success: function(){
          $(this).addClass("done");
        }
    });