0

I have a contact form which is passed to a PHP script through ajax. Once the form is processed, The ajax will perform some actions depending on the response received from json_encode() function in the PHP script. The problem is I get the following error message:

parsererror SyntaxError: Unexpected end of JSON input

readyState:4 responseText:"" status:200 statusText:"OK"

When the dataType is text in the ajax call and the PHP script simply echos a text message, then code works fine, but with json, I get the above error.

I have tried header("Content-Type: application/json")and JSON.parse() with no success. I have added charset="UTF-8" in the header and tried encode_utf8() function on the array passed to json_encode too, but nothing seems to work for me.

I am posting the code for the relevant files below. Any help to resolve this problem will be highly appreciated.

contact.php

<form action="" method="post" name="contactForm" id="contactForm">   

    <div class="form-row">         
        <div id="contactFormResponse"></div>

        <div class="form-col">  
            <label for="orderNumer">Order Number</label>
            <input type="text" name="orderNumber" id="orderNumber" value="<?php echo ($_POST['orderNumber']); ?>" />
        </div>

        <div class="form-col">
          <label for="comment">Comment *</label>
          <textarea name="message" id="comment" maxlength="2000" rows="5"><?php echo ($_POST['comment']); ?></textarea>
        </div>

        <div class="form-col">
            <label for="title">Title *</label>
            <select name="title" id="title">
                <option value="" <?php if ($_POST['title'] == "") {echo "selected='selected'";} ?>>Select a title...</option>
                <option value="ms" <?php if ($_POST['title'] =="ms") {echo "selected='selected'";} ?>>Ms</option>
                <option value="miss" <?php if ($_POST['title'] == "miss") {echo "selected='selected'";} ?>>Miss</option>
                <option value="mrs" <?php if ($_POST['title'] == "mrs") {echo "selected='selected'";} ?>>Mrs</option>
                <option value="mr" <?php if ($_POST['title'] == "mr") {echo "selected='selected'";} ?>>Mr</option>
                <option value="other" <?php if ($_POST['title'] == "other") {echo "selected='selected'";} ?>>Other</option>
            </select>
        </div>

        <div class="form-col">
            <label for="firstName">First Name *</label>
            <input type="text" name="firstName" id="firstName" value="<?php echo ($_POST['firstName']); ?>" />
        </div>

        <div class="form-col">
            <label for="surname">Surname *</label>
            <input type="text" name="surname" id="surname" value="<?php echo ($_POST['surname']); ?>" />
        </div>

        <div class="form-col">
            <label for="email">Email Address *</label>
            <input type="text" name="email" id="email" value="<?php echo ($_POST['email']); ?>" />
        </div>

        <div class="form-col">
            <input type="submit" name="submitContactForm" id="submitContactForm" value="Submit" class="btn" />
        </div>

    </div>
</form>

jsCode.js

// process contact form
$("#contactForm").submit(function(e) {

    e.preventDefault();

    // some jQuery validation goes here...

    $.ajax({
        type:"POST",
        url: "functions.php",
        dataType: "json",
        data: new FormData(this),
        //data: $('form').serialize(),
        processData: false,
        contentType: false,
        success:function(response) {
            if(response.status === "OK") {
                $("#contactFormResponse").html("<div class='alert alert-success' id='message'></div>");
                $("#message").html(response.message).fadeIn("100");
                $("#contactForm")[0].reset();
                $(window).scrollTop(0); 
            } else if (response.status === "error") {
                $("#contactFormResponse").html("<div class='alert alert-danger' id='message'></div>");
                $("#message").html(response.message).fadeIn("100");
                $(window).scrollTop(0);
            }  
       },
       error:function(jqXHR, textStatus, errorThrown) {
           console.log("JQuery failed: " + textStatus + " with error thrown: " + errorThrown);
           console.log(jqXHR);

         }
    });
});

functions.php

// send email
function sendMessage() {

    if (isset($_POST["submitContactForm"])) {
        if (!$_POST["comment"]) {
            $error .= "<br />Comment is required.";
        }

        if (!$_POST["firstName"]) {
            $error .= "<br />First name is required.";
        }

        // validation for other form fields goes here... 

        if ($error) {
            echo json_encode(array("status" => "error", "message" => "There were error(s)in your form: " . $error));

        } else {

            $to            = "[email protected]";
            $subject       = "Message from the website";
            $order_number  = $_POST["orderNumber"];
            $comment       = $_POST["comment"];
            $title         = $_POST["title"];
            $first_name    = $_POST["firstName"];
            $surname       = $_POST["surname"];
            $email_address = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
            $headers       = "From: " . $title  . " "  . $first_name . " " . $surname . " <" . $email_address . " >";
            $message       = "Order Number: " . $order_number . "/r/n" . "Topic: " . $topic . "/r/n" . "Comment: " . $comment;

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

            if (!$result) {

                echo json_encode(array("status" => "error", "message" => "Message failed."));

            } else {

               echo json_encode(array("status" => "OK", "message" => "Message sent."));

            }  
        }
    }
}

1 Answer 1

0

you are not parsing the json response in your success function,you need to use $.parseJSON(response) like below

    success:function(res) {
var response=$.parseJSON(res);
                if(response.status === "OK") {
                    $("#contactFormResponse").html("<div class='alert alert-success' id='message'></div>");
                    $("#message").html(response.message).fadeIn("100");
                    $("#contactForm")[0].reset();
                    $(window).scrollTop(0); 
                } else if (response.status === "error") {
                    $("#contactFormResponse").html("<div class='alert alert-danger' id='message'></div>");
                    $("#message").html(response.message).fadeIn("100");
                    $(window).scrollTop(0);
                }  
           },
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer Muhammad Omer Aslam. Unfortunately adding $.parseJSON() does not resolve the problem and I get the same error message.

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.