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

后端 未结 10 1472
盖世英雄少女心
盖世英雄少女心 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('<span class="wait">&nbsp;<img src="image/loading.gif" alt="" /></span>');
                },
                complete: function() {
                    $('#submit').attr('disabled', false);
                    $('.wait').remove();
                },  
                success: function(data)
                {
                    if(data.type == 'error')
                    {
                        output = '<div class="error">'+data.text+'</div>';
                    }else{
                        output = '<div class="success">'+data.text+'</div>';
                        $('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

    <div  class="cover">
    <div id="result"></div>
    <div id="contactform">
        <p class="contact"><label for="name">Name</label></p>
        <input id="name" name="name" placeholder="Yourname" type="text">
    
        <p class="contact"><label for="email">Email</label></p>
        <input id="email" name="email" placeholder="admin@admin.com" type="text">
    
        <p class="contact"><label for="comment">Your Message</label></p>
        <textarea name="comment" id="comment" tabindex="4"></textarea> <br>
        <input name="submit" id="submit" tabindex="5" value="Send Mail" type="submit" style="width:200px;">
    </div>
    

    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/

    0 讨论(0)
  • 2020-11-22 06:33
    $(document).ready(function(){
    $('#userForm').on('submit', function(e){
            e.preventDefault();
    //I had an issue that the forms were submitted in geometrical progression after the next submit. 
    // This solved the problem.
            e.stopImmediatePropagation();
        // show that something is loading
        $('#response').html("<b>Loading data...</b>");
    
        // Call ajax for pass data to other place
        $.ajax({
        type: 'POST',
        url: 'somephpfile.php',
        data: $(this).serialize() // getting filed value in serialize form
        })
        .done(function(data){ // if getting done then call.
    
        // show the response
        $('#response').html(data);
    
        })
        .fail(function() { // if fail then getting message
    
        // just in case posting your form failed
        alert( "Posting failed." );
    
        });
    
        // to prevent refreshing the whole page page
        return false;
    
        });
    
    0 讨论(0)
  • 2020-11-22 06:38

    Here is a nice plugin for jQuery that submits forms via ajax:

    http://malsup.com/jquery/form/

    its as simple as:

    <script src="http://malsup.github.com/jquery.form.js"></script> 
    <script> 
        $(document).ready(function() { 
            $('#myForm').ajaxForm(function() { 
               alert('form was submitted');
            }); 
        }); 
    </script> 
    

    It uses the forms action for the post location. Not that you can't achieve this with your own code but this plugin has worked very nicely for me!

    0 讨论(0)
  • 2020-11-22 06:38

    type="button"

    should be

    type="submit"
    
    0 讨论(0)
提交回复
热议问题