Contact Form Confirmation Message Without Refresh

前端 未结 1 1064
生来不讨喜
生来不讨喜 2021-01-25 21:12

The contact form I\'m using redirects after message has been sent but i would like the user to get a \'Message Sent\' alert that would appear & disappears somewhere on the c

相关标签:
1条回答
  • 2021-01-25 21:48

    You can use the below link to prepare your form. Simple Ajax Form Using Javascript No jQuery

    Once its prepared, you can use the responseText to check if the success status is returned and then can display the message accordingly on the same page without refresh.

    Edit:

    In HTML

    <form id="contact-form-face" onSubmit="AJAXPost(this.id); return false;" class="clearfix" action="http://www.demo.com/php/contactengine.php">
    

    In php file

    if($success){
    echo 1;
    }else{
    echo 0;
    }
    

    This could be your javascript function to which to will pass your form-Id.

    function AJAXPost(formId) {
    var elem   = document.getElementById(formId).elements;
    var url    = document.getElementById(formId).action;        
    var params = "";
    var value;
    
    for (var i = 0; i < elem.length; i++) {
        if (elem[i].tagName == "SELECT") {
            value = elem[i].options[elem[i].selectedIndex].value;
        } else {
            value = elem[i].value;                
        }
        params += elem[i].name + "=" + encodeURIComponent(value) + "&";
    }
    
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else { 
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    xmlhttp.open("POST",php_post_url.php,false);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", params.length);
    xmlhttp.setRequestHeader("Connection", "close");
    xmlhttp.send(params);
    if(xmlhttp.responseText == 1){
    alert('Successfully Submitted');
    }else{
    alert('Something Went Wrong. Please try again.');
    }
    }
    
    0 讨论(0)
提交回复
热议问题