简体   繁体   中英

Ajax doesn't send data to PHP file

I wrote this script which doesn't send the data from the AJAX to the PHP file. I debugged it with logging the data that's in the form before it ran through the AJAX function. It gave me this data:

Form: name=jim&email=info%40test.com

However, I get an empty alert and I receive an empty e-mail.

HTML

<form name="form" id="form" class="form" method="post">
    <input type="text" class="text border" name="name" id="name" placeholder="Name" />
    <input type="text" class="text" name="email" id="email" placeholder="E-mail" />
    <input type="submit" class="button" value="Submit" />
</form>

JS

jQuery(function(){
        jQuery('#form').submit(function(event){
            event.preventDefault();
            jQuery.ajax({
                type: "POST",
                url: "includes/post.php",
                data: jQuery('#form').serialize(),

                success: function(data){
                    jQuery("#form").addClass("inactive");
                    jQuery("#message").addClass("active");
                    alert(data);
                }                   
                });
            });
    });

PHP

<?php

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $name   =   mysql_real_escape_string($_POST["name"]);
        $email  =   mysql_real_escape_string($_POST["email"]);

        $to = "test@hidden.com";

        $message = '

        <html>
        <body>
        <p>
        <strong>Name: </strong> '.$name.' <br/>
        <strong>E-mail: </strong> '.$email.' <br/>
        </p>
        </body>
        </html>

        ';

        $subject = 'New entry: '.$name.', '.$email;
        $headers .= "From: ".$name." ".$$email."\r\n";
        $headers .= "X-Mailer: PHP's mail() Function\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";;

        mail($to, $subject, $message, $headers);

    }

?>

Try the below code,

Update your PHP with the below,

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = htmlspecialchars($_POST["name"]);
    $email = htmlspecialchars($_POST["email"]);
    echo $name;// this will see in your response
    $to = "test@gmail.com";
    $message = '

        <html>
        <body>
        <p>
        <strong>Name: </strong> ' . $name . ' <br/>
        <strong>E-mail: </strong> ' . $email . ' <br/>
        </p>
        </body>
        </html>

        ';
    $subject = 'New entry: ' . $name . ', ' . $email;
    $headers = "From: " . $name . " " . $email . "\r\n";
    $headers.= "X-Mailer: PHP's mail() Function\n";
    $headers.= "MIME-Version: 1.0\r\n";
    $headers.= "Content-Type: text/html; charset=ISO-8859-1\r\n";;
    mail($to, $subject, $message, $headers);
}

Nothing is being returned from your php, and you need some form of server side validation, here is a complete code you can use:

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

$admin_email = 'your@yourdomain.com'; // Your Email
$message_min_length = 5; // Min Message Length


class Contact_Form{
function __construct($details, $email_admin, $message_min_length){

    $this->name = stripslashes($details['name']);
    $this->email = trim($details['email']);
    $this->subject = 'Contact from Your Website'; // Subject 
    $this->message = stripslashes($details['message']);

    $this->email_admin = $email_admin;
    $this->message_min_length = $message_min_length;

    $this->response_status = 1;
    $this->response_html = '';
}


private function validateEmail(){
    $regex = '/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i';

    if($this->email == '') { 
        return false;
    } else {
        $string = preg_replace($regex, '', $this->email);
    }

    return empty($string) ? true : false;
}


private function validateFields(){
    // Check name
    if(!$this->name)
    {
        $this->response_html .= '<p>Please enter your name</p>';
        $this->response_status = 0;
    }

    // Check email
    if(!$this->email)
    {
        $this->response_html .= '<p>Please enter an e-mail address</p>';
        $this->response_status = 0;
    }

    // Check valid email
    if($this->email && !$this->validateEmail())
    {
        $this->response_html .= '<p>Please enter a valid e-mail address</p>';
        $this->response_status = 0;
    }

    // Check message length
    if(!$this->message || strlen($this->message) < $this->message_min_length)
    {
        $this->response_html .= '<p>Please enter your message. It should have at least '.$this->message_min_length.' characters</p>';
        $this->response_status = 0;
    }
}


private function sendEmail(){
    $mail = mail($this->email_admin, $this->subject, $this->message,
         "From: ".$this->name." <".$this->email.">\r\n"
        ."Reply-To: ".$this->email."\r\n"
    ."X-Mailer: PHP/" . phpversion());

    if($mail)
    {
        $this->response_status = 1;
        $this->response_html = '<p>Thank You!</p>';
    }
}


function sendRequest(){
    $this->validateFields();
    if($this->response_status)
    {
        $this->sendEmail();
    }

    $response = array();
    $response['status'] = $this->response_status;   
    $response['html'] = $this->response_html;

    echo json_encode($response);
}
}


$contact_form = new Contact_Form($_POST, $admin_email, $message_min_length);
$contact_form->sendRequest();

You should write echo statement after mail() function. The string written in echo statement will display in alert.

for example : echo "Mail sent successfully";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM