0

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 = "[email protected]";

        $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);

    }

?>
1
  • Also, if I alert the data from jQuery('#form').serialize() before the jQuery.ajax function it returns the datastring correctly. Commented Sep 27, 2015 at 15:13

3 Answers 3

1

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 = "[email protected]";
    $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);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks dude, it works now :) You made my day, I should buy you beer :D
Ah, one more problem. I tried the script on my host and it worked perfectly (I also received the e-mail correctly). However, if I migrate it to the clients' host it gives this error: XMLHttpRequest cannot load http://www.thehost.com/beta/includes/post. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://thehost.com' is therefore not allowed access. The response had HTTP status code 404.
@IroNLioNZioN does the php file is in the same location as html file?
It is in the same root folder yes
It is saying about the cross domain action..if it is in the same location this won't be an issue..Can i have a live version of this?
0

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 = '[email protected]'; // 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();

Comments

0

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

for example : echo "Mail sent successfully";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.