Form submit with AJAX passing form data to PHP without page refresh

后端 未结 10 1454
盖世英雄少女心
盖世英雄少女心 2020-11-22 06:07

Can anyone tell me why this bit of code isn\'t working?


  
    

        
10条回答
  •  盖世英雄少女心
    2020-11-22 06:31

    JS Code

        $("#submit").click(function() { 
        //get input field values
        var name            = $('#name').val(); 
        var email           = $('#email').val();
        var message         = $('#comment').val();
        var flag = true;
        /********validate all our form fields***********/
        /* Name field validation  */
        if(name==""){ 
            $('#name').css('border-color','red'); 
            flag = false;
        }
        /* email field validation  */
        if(email==""){ 
            $('#email').css('border-color','red'); 
            flag = false;
        } 
        /* message field validation */
        if(message=="") {  
           $('#comment').css('border-color','red'); 
            flag = false;
        }
        /********Validation end here ****/
        /* If all are ok then we send ajax request to email_send.php *******/
        if(flag) 
        {
            $.ajax({
                type: 'post',
                url: "email_send.php", 
                dataType: 'json',
                data: 'username='+name+'&useremail='+email+'&message='+message,
                beforeSend: function() {
                    $('#submit').attr('disabled', true);
                    $('#submit').after(' ');
                },
                complete: function() {
                    $('#submit').attr('disabled', false);
                    $('.wait').remove();
                },  
                success: function(data)
                {
                    if(data.type == 'error')
                    {
                        output = '
    '+data.text+'
    '; }else{ output = '
    '+data.text+'
    '; $('input[type=text]').val(''); $('#contactform textarea').val(''); } $("#result").hide().html(output).slideDown(); } }); } }); //reset previously set border colors and hide all message on .keyup() $("#contactform input, #contactform textarea").keyup(function() { $("#contactform input, #contactform textarea").css('border-color',''); $("#result").slideUp(); });

    HTML Form


    PHP Code

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    //check if its an ajax request, exit if not
    if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    
        //exit script outputting json data
        $output = json_encode(
                array(
                    'type' => 'error',
                    'text' => 'Request must come from Ajax'
        ));
    
        die($output);
    }
    
    //check $_POST vars are set, exit if any missing
    if (!isset($_POST["username"]) || !isset($_POST["useremail"]) || !isset($_POST["message"])) {
        $output = json_encode(array('type' => 'error', 'text' => 'Input fields are empty!'));
        die($output);
    }
    
    //Sanitize input data using PHP filter_var().
    $username = filter_var(trim($_POST["username"]), FILTER_SANITIZE_STRING);
    $useremail = filter_var(trim($_POST["useremail"]), FILTER_SANITIZE_EMAIL);
    $message = filter_var(trim($_POST["message"]), FILTER_SANITIZE_STRING);
    
    //additional php validation
    if (strlen($username) < 4) { // If length is less than 4 it will throw an HTTP error.
        $output = json_encode(array('type' => 'error', 'text' => 'Name is too short!'));
        die($output);
    }
    if (!filter_var($useremail, FILTER_VALIDATE_EMAIL)) { //email validation
        $output = json_encode(array('type' => 'error', 'text' => 'Please enter a valid email!'));
        die($output);
    }
    if (strlen($message) < 5) { //check emtpy message
        $output = json_encode(array('type' => 'error', 'text' => 'Too short message!'));
        die($output);
    }
    
    $to = "info@wearecoders.net"; //Replace with recipient email address
    //proceed with PHP email.
    $headers = 'From: ' . $useremail . '' . "\r\n" .
            'Reply-To: ' . $useremail . '' . "\r\n" .
            'X-Mailer: PHP/' . phpversion();
    
    $sentMail = @mail($to, $subject, $message . '  -' . $username, $headers);
    //$sentMail = true;
    if (!$sentMail) {
        $output = json_encode(array('type' => 'error', 'text' => 'Could not send mail! Please contact administrator.'));
        die($output);
    } else {
        $output = json_encode(array('type' => 'message', 'text' => 'Hi ' . $username . ' Thank you for your email'));
        die($output);
    }
    

    This page has a simpler example http://wearecoders.net/submit-form-without-page-refresh-with-php-and-ajax/

提交回复
热议问题