3

I have a html form that is supposed to submit data to a php file through jquery ajax. the code can be seen below.The problem I am having is that on clicking submit, the ajax seems not to be passing data to php as the console.log under the done() function returns a $data object showing that all fields are empty (i.e returning the error messages when the fields are empty). I am simply not getting where the problem is. When I submit the form without using ajax i.e disabling the entire $('form').submit (...) block, the success message returns true. the ajax blocks always returns false

<form id="sds_contact_form" class="sds_form" action="form_submit.php" method="post">
                    <!-- name -->
                    <div class="sds_input_group sds_half_field">
                        <label for="sds_sender_name">full name*</label>
                        <input id="sds_sender_name" name="sds_customer" type="text" placeholder="eg John smith" required />
                        <span id="sds_customername_error" class="sds_error_span"></span>
                    </div>
                    <!-- email address -->
                    <div class="sds_input_group sds_half_field">
                        <label for="sds_sender_email">email*</label>
                        <input id="sds_sender_email" name="sds_form_email" type="email" placeholder="eg [email protected]" required />
                        <span id="sds_email_error" class="sds_error_span"></span>
                    </div>
                    <!-- subject -->
                    <div class="sds_input_group">
                        <label for="sds_email_subject">subject*</label>
                        <input id="sds_email_subject" name="sds_form_subject" type="text" placeholder="e.g need an app designed" required />
                        <span id="sds_subject_error" class="sds_error_span"></span>
                    </div>
                    <!--enquiry -->
                    <div class="sds_input_group">
                        <label for="sds_sender_enquiry">enquiry*</label>
                        <span id="sds_enquiry_error" class="sds_error_span"></span>
                        <textarea id="sds_sender_enquiry" name="sds_form_enquiry" placeholder="enter details here" rows="15" required></textarea>
                    </div>
                    <!-- submit button -->
                    <button  name="sds_submit_enquiry" type="submit" class="sds_form_button sds_button">send</button>
                </form> 

This is the jquery code

//form data submission
$('form').submit(function(event){
    var form_data = {
        'customer_name' : $('#sds_sender_name').val(),
        'customer_email' : $('#sds_sender_email').val(),
        'email_subject': $('#sds_email_subject').val(),
        'enquiry': $('#sds_sender_enquiry').val()
    };
    console.log(form_data);

    $.ajax({
        url :'form_submit.php',
        type:'POST',
        data:form_data,
        dataType:'json',

    }).done(function(data){
        console.log(data);

    }).fail(function(xhr, ajaxOptions, thrownError){
        console.log("ERROR:" + xhr.responseText+" - "+thrownError);
    });
    event.preventDefault();


});

This is the PHP Code in form_submit.php

<?php

$data = array();
$errors = array();

//get form data
$customer_name = $_POST['sds_customer'];
$customer_email = $_POST['sds_form_email'];
$email_subject = $_POST['sds_form_subject'];
$enquiry = $_POST['sds_form_enquiry'];  

//validate name
if(empty($customer_name)){
    $errors['customer_name'] = 'name is required';
}

//validate email
if(empty($customer_email)){
    $errors['customer_email'] = 'email is required';
}else{
    if(!filter_var($customer_email,FILTER_VALIDATE_EMAIL)){
        $errors['customer_email'] = 'email provided is invalid';
    }
    $customer_email = filter_var($customer_email,FILTER_SANITIZE_EMAIL);
}

//validate form subject
if(empty($email_subject)){
    $errors['email_subject'] = 'subject is required';
}else{
    $email_subject = filter_var($email_subject,FILTER_SANITIZE_STRING);
}

//validate form comments
if(empty($enquiry)){
    $errors['enquiry'] = 'please enter your enquiry';
}else{
    $enquiry = filter_var($enquiry,FILTER_SANITIZE_STRING);
}



if(!empty($errors)){
    $data['success'] = false;
    $data['errors'] = $errors;
}else{
    $data['success'] = true;
    $data['message'] = "Your email has been sucessfully sent. Thank you for your enquiry. Exepect a response soon!";

    //further data processing here....


}
echo json_encode($data);

?>

2
  • In done section you should use JSON.parse(data); as you are passing json decode from php Commented Nov 9, 2016 at 10:15
  • 1
    @Jigar7521 No, he shouldn't. If the dataType of AJAX is defined as JSON, JSON.parse isn't necessary. Commented Nov 9, 2016 at 10:23

2 Answers 2

1

Your problem is about parameters names At jquery the parameter is defined as:

var form_data = {
    'customer_name' : $('#sds_sender_name').val(),
    'customer_email' : $('#sds_sender_email').val(),
    'email_subject': $('#sds_email_subject').val(),
    'enquiry': $('#sds_sender_enquiry').val()
};

At PHP, you are using a sds prefix (as write in the form):

//get form data
$customer_name = $_POST['sds_customer'];
$customer_email = $_POST['sds_form_email'];
$email_subject = $_POST['sds_form_subject'];
$enquiry = $_POST['sds_form_enquiry'];

Your parameters should match with AJAX, not with form (as below).

$customer_name = $_POST['customer_name'];
$customer_email = $_POST['customer_email'];
$email_subject = $_POST['email_subject'];
$enquiry = $_POST['enquiry'];

Or just use serialized on form:

$.ajax(
    data: $("#sds_contact_form").serialize(),
    /*** others parameters ***/
Sign up to request clarification or add additional context in comments.

3 Comments

Yeeeeessssss! Switched the code and its working now! The only concern I have is when someone has javascript turned off, it will not work. how can I code it to accommodate both situations in the php file?
To answer myself, the second solution (serializing the form) caters for both situations i.e. I don't have make the parameters match with AJAX.
If you serialize the form, it'll came with the parameters name from your HTML form. So, your PHP should match with form names (as you did before)
1
$("#sds_contact_form").serialize() // returns all the data in your form

$.ajax({
     type: "POST",
     url: 'form_submit.php',
     data: $("#sds_contact_form").serialize(),
     dataType:'json',
     success: function(data) {
          console.log(data);
     }
});

In you php file Unserialize your data

unserialize($data); 

1 Comment

Thanks. your answer complements @Gabriel Heming answer and helped me see how to cater for situations when both javascript is on and off

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.