rjhewitt3
rjhewitt3

Reputation: 30

jQuery serialized data not successfully posting to PHP form handler

I’m trying to post some data via jQuery Ajax to a PHP form handler file. It was working earlier, but I wasn’t getting errors when I should have (ie it was always sending an email), so I modified the mess out of my stuff and now the PHP file is no longer receiving the serialized data. Would greatly appreciate some eyes on this. I have a feeling it’s a stupid syntax error, but I’m not seeing it.

JS (jQuery)

$form.submit(function(e) {
        e.preventDefault();

        var data = $(this).serialize(),
            url = $(this).attr('action');

        console.log(data);

        $(this).addClass('sending');

        $.ajax({
            url: url,
            type: 'GET',
            async: true,
            dataType: 'json',
            data: data,
            success: 
                function(response) {
                    console.log("Success: " + data);

                    if(!response.success) {
                        formError(response);
                    } else {
                        // on success
                        console.log(`✔ Form submission successful!`);
                        console.log(response);

                        // Add success message
                        $form.append(
                            '<div class="success-message"><h3>Your Message Was Sent</h3><p>' 
                            +
                            successMsg
                            + 
                            '</p></div>'
                        ).delay(10)
                        .queue(function(){
                            $(this).find('.success-message').addClass('visible');
                            $(this).dequeue();
                        });                    

                        $form
                            .delay(10)
                            .queue(function() {
                                $(this)
                                    .removeClass('sending')
                                    .addClass('sent')
                                    .dequeue();
                            });

                        $form[0].reset();
                    }
                },
            error: 
                function(xhr, status, error){
                    console.log("Fail: " + data);

                    formError(xhr, status, error);
                }
        });

        function formError(xhr, status, error) {
            //on failure
            console.log('✘ Form submission failed.');
            console.log(xhr);
            console.log(status);
            console.log(error);

            if (!$form.hasClass('error')) {
                $form
                    .addClass('error')
                    .delay(2000)
                    .queue(function() {
                        $(this)
                            .removeClass('error')
                            .removeClass('sending')
                            .dequeue();
                    });
            }
        };
    });

PHP Handler

<?php 
$errors = '';
$myemail = '#####';//<-----Put Your email address here.

$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$company = $_POST['company'];
$subject = $_POST['subject'];
$message = $_POST['message'];

$data = array($name, $email, $phone, $company, $subject, $message);

if(
    empty($name) ||
    empty($email) || 
    empty($phone) || 
    empty($company) || 
    empty($message)
) {
    $errors .= "\n You must fill out required fields.";
}

if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", 
$email))
{
    $errors .= "\n Invalid email address.";
}

if( empty($errors) ) {
    $to = $myemail; 
    $email_subject = "Contact Form: $name";
    $email_body =   "<html><body>".
                    "<p>Name: $name<br>".
                    "<p>Company: $company<br>".
                    "Email: $email<br>".
                    "Phone: $phone<br></p>".
                    "<p><b>Subject:</b></p>".
                    "<p>$subject</b></p>".
                    "<p><b>Message:</b></p>".
                    "<p>$message</p>".
                    "</body></html>";

    $headers = "From: $myemail\r\n"; 
    $headers .= "Reply-To: $email\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    mail($to,$email_subject,$email_body,$headers);

    echo json_encode(array("success" => true, "data" => $data));
} else {
    echo json_encode(array("success" => false,"error" => $errors, "data" => $data));
}
?>

The PHP handler is returning data so that I can see what's going on, and then I'm console logging it. Here's what I'm getting:

{success: false, error: "↵ You must fill out required fields.↵ Invalid email address.", data: Array(6)}
data: (6) [null, null, null, null, null, null]
error: "↵ You must fill out required fields.↵ Invalid email address."
success: false
__proto__: Object

In other words, the data isn't actually passing to the PHP file. I'm assuming I have some stupid syntax error, but I'm not seeing it. Help! 🙏🏼

Upvotes: 0

Views: 73

Answers (1)

Shim-Sao
Shim-Sao

Reputation: 2126

You send GET data in Ajax and you try to get POST in your PHP.

Change type to POST in your Ajax function.

$form.submit(function(e) {
        e.preventDefault();

        var data = $(this).serialize(),
            url = $(this).attr('action');

        console.log(data);

        $(this).addClass('sending');

        $.ajax({
            url: url,
            type: 'POST',
            async: true,
            dataType: 'json',
            data: data,
            success: 
                function(response) {
                    console.log("Success: " + data);

                    if(!response.success) {
                        formError(response);
                    } else {
                        // on success
                        console.log(`✔ Form submission successful!`);
                        console.log(response);

                        // Add success message
                        $form.append(
                            '<div class="success-message"><h3>Your Message Was Sent</h3><p>' 
                            +
                            successMsg
                            + 
                            '</p></div>'
                        ).delay(10)
                        .queue(function(){
                            $(this).find('.success-message').addClass('visible');
                            $(this).dequeue();
                        });                    

                        $form
                            .delay(10)
                            .queue(function() {
                                $(this)
                                    .removeClass('sending')
                                    .addClass('sent')
                                    .dequeue();
                            });

                        $form[0].reset();
                    }
                },
            error: 
                function(xhr, status, error){
                    console.log("Fail: " + data);

                    formError(xhr, status, error);
                }
        });

        function formError(xhr, status, error) {
            //on failure
            console.log('✘ Form submission failed.');
            console.log(xhr);
            console.log(status);
            console.log(error);

            if (!$form.hasClass('error')) {
                $form
                    .addClass('error')
                    .delay(2000)
                    .queue(function() {
                        $(this)
                            .removeClass('error')
                            .removeClass('sending')
                            .dequeue();
                    });
            }
        };
    });

Upvotes: 1

Related Questions