ajax form submission with php

雨燕双飞 提交于 2019-12-02 18:08:17

问题


I am having trouble getting the email to send which I am sure it is because of the php but here is the js ajax also..it shows my error messages for form fields that are not filled out correctly and then it shows my processing bar once submitted but I get my error message after submission..any help would be appreciated.

html

<form method="post" action="feedback.php" id="contactform">
            <fieldset class="first">


            <div id="response"></div>  


            <div id="name_input">

            <input id="name" name="name" placeholder="Name" class="required" type="text" maxlength="128" />

            </div>



            <div id="email_input">

            <input id="email" name="name" placeholder="Email"  class="required" type="text"  maxlength="128" />

            </div>



            <div id="budget_input">
            <label for="budget">Budget</label>
            <select id="mydropdown">
            <option value="none" selected=“”> -- choose one --</option>
            <option value="firstchoice">$0 - $1,000</option>
            <option value="secondchoice">$1,000 - $2,000</option>
            <option value="thirdchoice">$3,000 +</option>
            </select>
            </div>



            <div id="button">

            <input type="submit" class="button" name="Submit" value="" />
            </div>


            </fieldset>


        </form>

Updated:

<?php 

$name = trim(stripslashes(htmlspecialchars($_POST['name'])));           
$email = trim(stripslashes(htmlspecialchars($_POST['email'])));
$mydropdown = trim(stripslashes(htmlspecialchars($_POST['mydropdown'])));  
$recipient = "blake.harrison1@cox.net";  
$humancheck = $_POST['humancheck'];
$honeypot = $_POST['honeypot'];



    if ($honeypot == 'http://' && empty($humancheck)) { 

    //Validate data and return success or error message
    $error_message = '';    
    $reg_exp = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,4}$/";

    if (!preg_match($reg_exp, $email)) {

                $error_message .= "<p>A valid email address is required.</p>";             
    }
    if (empty($name)) {

                $error_message .= "<p>Please provide your name.</p>";              
    }

    if (empty($mydropdown)) {

                $error_message .= "<p>Please select an item from the list.</p>";
    }               

    if (!empty($error_message)) {
                $return['error'] = true;
                $return['msg'] = "<h3>Oops! The request was successful but your form is not filled out correctly.</h3>".$error_message;                 
                echo json_encode($return);
                exit();
        } else {

        //send to  an email


        $emailSubject = 'Top Contact Form';
        $webMaster = 'blake.harrison1@cox.net';

 $body="
 <br><hr><br>
 <strong>Name:</stong> $name <br>
 <br>
 <strong>Email:</stong> $email <br>
 <br>
 <strong>Budget:</strong> $mydropdown <br>
 <br>
 ";      

        $headers = "From: $email\r\n";
        $headers .= "Content-type: text/html\r\n";


        //send email and return to user
        if(mail($webMaster, $emailSubject, $body, $headers)) {

            $return['error'] = false;
            $return['msg'] = "<p>Message sent successfully. Thank you for your interest " .$name .".</p>"; 
            echo json_encode($return);
        }
    }   
 } else {

$return['error'] = true;
$return['msg'] = "<h3>Oops! There was a problem with your submission. Please try again.</h3>";  
echo json_encode($return);
 }

?> 



$(document).ready(function() {

$('form #response').hide();

$('#submit').click(function(e) {

    // prevent forms default action until
    // error check has been performed
    e.preventDefault();

    // grab form field values
    var valid = '';
    var required = ' is required.';
    var name = $('form #name').val();
    var email = $('form #email').val();
    var mydropdown = $('form #mydropdown').val();
    var honeypot = $('form #honeypot').val();
    var humancheck = $('form #humancheck').val();


    // perform error checking
    if (name == '' || name.length <= 2) {
        valid = '<p>Your name' + required +'</p>';  
    }

    if (!email.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
        valid += '<p>Your email' + required +'</p>';                                                  
    }

    if (mydropdown == '') {
        valid += '<p>An item from the list' + required +'</p>';

    }

    if (honeypot != 'http://') {
        valid += '<p>Spambots are not allowed.</p>';    
    }

    if (humancheck != '') {
        valid += '<p>A human user' + required + '</p>'; 
    }


    // let the user know if there are erros with the form
    if (valid != '') {

        $('form #response').removeClass().addClass('error')
            .html('<strong>Please correct the errors below.</strong>' +valid).fadeIn('fast');           
    }
    // let the user know something is happening behind the scenes
    // serialize the form data and send to our ajax function
    else {

        $('form #response').removeClass().addClass('processing').html('Processing...').fadeIn('slow');                                      

        var formData = $('form').serialize();
        submitForm(formData);           
    }           

});
});


function submitForm(formData) {

$.ajax({    
    type: 'POST',
    url: 'send.php',        
    data: formData,
    dataType: 'json',
    cache: false,
    timeout: 12000,
    success: function(data) {           

        $('form #response').removeClass().addClass((data.error === true) ? 'error' : 'success')
                    .html(data.msg).fadeIn('fast'); 

        if ($('form #response').hasClass('success')) {

            setTimeout("$('form #response').fadeOut('fast')", 12000);
        }

    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {

        $('form #response').removeClass().addClass('error')
                    .html('<p>There was an<strong> ' + errorThrown +
                          '</strong> error due to a<strong> ' + textStatus +
                          '</strong> condition.</p>').fadeIn('fast');           
    },              
    complete: function(XMLHttpRequest, status) {            

        $('form')[0].reset();
    }
}); 
};

回答1:


can you try $.post instead of $.ajax

$.post(url, {argument_name: value, ...} , function(data){

// callback function..

}, 'json'}



回答2:


do this with the php page...

  sleep(2);
  //Sanitize incoming data and store in variable
  $name = trim(stripslashes(htmlspecialchars($_POST['name'])));           
  $email = trim(stripslashes(htmlspecialchars($_POST['email'])));
  $message = trim(stripslashes(htmlspecialchars($_POST['message']))); 
  $recipient = "info@internetmarketingtrio.com";



//Validate data and return success or error message
$errors = array();   
$reg_exp = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,4}$/";

if (!preg_match($reg_exp, $email)) {

            $errors[] = "<p>A valid email address is required.</p>";             
}
if (empty($name) || $name == '') {

            $errors[] = "<p>Please provide your name.</p>";              
}           
if (empty($message) || $message == '') {

            $errors[] = "<p>A message is required.</p>";
}
if(empty($errors)) {
    $return['success'] = true;
    $return['message'] = "<p>Thanks for your feedback " .$name. ".</p>";
} else {
    $return['success'] = false;
    $return['message'] = "<h3>Oops! The request was successful but your form is not filled out correctly.</h3>";
    foreach($errors as $error) {
        $return['message'] .= $error ."<br />";
    }
}

And then in your call to get this page... the ajax call...

$.ajax({    
type: 'POST',
url: 'feedback.php',        
data: formData,
dataType: 'json',
cache: false,
success: function(data) { 
    if(data.success) {
        $("form#response").removeClass().addClass('success').html(data.message).fadeIn('fast');
        removeResponse(5000);
    } else {
        $("form#response").removeClass().addClass('error').html(data.message).fadeIn('fast'); 
    }
}        
}); 

function removeResponse(time) {
    setTimeout(function() {
        $("form#response").fadeOut('fast');
    }, time);
}

And that should do ya




回答3:


adding this to the bottom of my php ended up fixing my issue if anyone reads this

        $emailSubject = 'Contact Form';
        $webMaster = 'blake.harrison1@cox.net';

$body="
<br><hr><br>
<strong>Name:</stong> $name <br>
<br>
 <strong>Email:</stong> $email <br>
 <br>
 <strong>Message:</stong> $message 
";      

        $headers = "From: $email\r\n";
        $headers .= "Content-type: text/html\r\n";


        //send email and return to user
        if(mail($webMaster, $emailSubject, $body, $headers)) {

            $return['error'] = false;
            $return['msg'] = "<p>Message sent successfully. Thank you for your intrest " .$name .".</p>"; 
            echo json_encode($return);
        }
    }   
} else {

$return['error'] = true;
$return['msg'] = "<h3>Oops! There was a problem with your submission. Please try again.</h3>";  
echo json_encode($return);
 }

 ?> 


来源:https://stackoverflow.com/questions/13924309/ajax-form-submission-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!