Edward
Edward

Reputation: 3081

AJAX form executes PHP script but returns error

My PHP script is executing successfully and the records from the form are being inserted into the Database, however, every time I press "submit form button" it gives me the alert "error" so my success function is not being executed and I don't know why.

JAVASCRIPT

$(document).ready(function () {
    $(".button").click(function () {
        var dataString = 'name=' + name + '&email=' + email + '&comment=' + comment;
        $.ajax({
            type: 'POST',
            url: 'submit_form.php',
            dataType: 'json',

            data: dataString,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert('error');
                $('#message').removeClass().addClass('error')
                    .text('There was an error.').show(500);
            },
            success: function (data) {
                $('#contact_form').html("<div id='message'></div>");
                $('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
                    .text(data.msg).show(500);
                $('#contact_form').hide();
            }
        });
        return false;
    });
});

PHP

//mysql connection string // 
$result = $mysqli->query("**fetch # of rows**");
$count  = $result->fetch_object()->Total;
$result->free();

echo "number of rows is $count";

if ($count > 10) {
    $return['error'] = true;
    $return['msg']   = 'Sorry The Queue is full';
}elseif ($stmt = $mysqli->prepare("**insert into db**")) {
    /* Bind our params */
    $stmt->bind_param("sss", $param1, $param2, $param3);

    /* Set our params */
    $param1 = $_POST["param1"];
    $param2 = $_POST["param2"];
    $param3 = $_POST["param3"];

    /* Execute the prepared Statement */
    $stmt->execute();
    $return['error'] = false;
    $return['msg']   = 'Thanks your comment was added!';

    /* Close the statement */
    $stmt->close();
} else {
    /* Error */
    printf("Prepared Statement Error: %s\n", $mysqli->error);
}

echo json_encode($return);

Upvotes: 0

Views: 341

Answers (1)

Barmar
Barmar

Reputation: 780974

The line:

echo "number of rows is $count";

will result in invalid JSON.

Upvotes: 5

Related Questions