-2

Hello i've got a json parse error. This is simple jquery+ajax+php code that validates a data that user inputs into contact form.

jq+ajax:

$(document).ready(function() {
$("#cbutton").click('submit', function(e) {
    e.preventDefault();
    var name = $("#fname").val();
    var email = $("#fmail").val();
    var phone = $("#fphone").val();
    var message = $("#fmess").val();

    if (name == '' || email == '' || phone == '' || message == '') {
        console.log("Please Fill Required Fields");

    }
    $.ajax({
        method: "POST",
        contentType:"application/json",
        url: "php/some.php",
        dataType: "json",
        data: { 
            name: 'name', 
            email: 'email',
            phone: 'phone', 
            message: 'message',
        },
        success : function(data){
            // if (data.code == "200"){
                // console.log("Success: " +data.msg);
            // }
            $.each(data, function(index, element) {

                console.log("Success: " +element.name);

            });
        },
        error: function(jqXHR, exception) {
            if (jqXHR.status === 0) {
                alert('Not connect.\n Verify Network.');
            } else if (jqXHR.status == 404) {
                alert('Requested page not found. [404]');
            } else if (jqXHR.status == 500) {
                alert('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
                alert('Requested JSON parse failed.');
            } else if (exception === 'timeout') {
                alert('Time out error.');
            } else if (exception === 'abort') {
                alert('Ajax request aborted.');
            } else {
                alert('Uncaught Error.\n' + jqXHR.responseText);
            }
        }
    });
});

});

and php:

<?php

header('Content-Type: application/json');

$errorMSG = "";

if (empty($_POST["name"])) 
    $errorMSG = "<li>Name is required</<li>";
} else {
    $name = $_POST["name"];
}

if (empty($_POST["email"])) {
    $errorMSG .= "<li>Email is required</li>";
} else if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
    $errorMSG .= "<li>Invalid email format</li>";
} else {
    $email = $_POST["email"];
}

if (empty($_POST["phone"])) {
    $errorMSG = "<li>Phone is required</<li>";
} else {
    $name = $_POST["phone"];

}
if (empty($_POST["message"])) {
    $errorMSG .= "<li>Message is required</li>";
} else {
    $message = $_POST["message"];
}


if (empty($errorMSG)) {
    $msg = "Name: " . $name . ", Email: " . $email . ", Phone: " . $phone . ", Message:" . $message;
    //echo json_encode(['code'=>200, 'msg'=>$msg]);
    echo $msg;
    exit;
}
?>

I've tried to fix it with a several methods (as you see by comments) and nothing's working. Script should create json and check if data is correct (correct email and no blank spots).

Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34

3 Answers3

1

message: 'message', the last comma must be removed

-1

In your ajax request, you have set return data type to JSON, so you can only send JSON data, try following, it will work.

if(empty($errorMSG)){
    $msg = "Name: ".$name.", Email: ".$email.", Phone: ".$phone.", 
    Message:".$message;

    $result = array();
    $result['code'] = 200;
    $result['msg'] = $msg;

    echo json_encode($result);
    exit;
}
-2

Your php file is not returning valid JSON response even though you set response header as header('Content-Type: application/json') in case of failure. php file should echo valid JSON string like below.

$errorMSG = "{errMsg: 'Name is required'}"
Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34