1

I have a page powered with PHP and AJAX, when a user submits one of my forms I check for errors in the getData.php script.

This example is if the user submits the form with the default value I'm wondering if there is a way to pass back those errors or trigger the AJAX to fire an error if the user commits on or if I need to do error handling before the AJAX call

$('form').on('submit', function (e) {
    e.preventDefault();
    $.ajax({
        type: 'post',
        url: '_ajax/addData.php',
        data: $('form').serialize(),
        success: function () {
            $("input").val('Info Here');
            $("form").hide();
            reloadInfo();
        }
    });
});

PHP

$info = $_POST['info'];

if($info != 'Info Here') {
    $conn = mysqli_connect();
    $query = "INSERT INTO leads VALUES(0, '$companyName', 1, NOW(), 3)";
    $result = mysqli_query($conn, $query) or die ('Error Could Not Query');

    $id = mysqli_insert_id($result);
    header("Location: http://localhost/manage/info.php?id=$id");

    mysqli_close($conn);
} else { 
    echo '<script>alert("Error");/script>'
}

PART 2

3 Answers 3

2

Javascript:

success: function (data) {
           if(!data.success) alert(data.errors); // Just for demonstration purposes
            $("input").val(data.errors);
            $("form").hide();
            reloadInfo();
        }

PHP:

header("Content-Type: text/json; charset=utf8");
if($info != 'Info Here') {
    $conn = mysqli_connect();
    $query = "INSERT INTO leads VALUES(0, '$companyName', 1, NOW(), 3)";
    $result = mysqli_query($conn, $query) or die ('Error Could Not Query');

    $id = mysqli_insert_id($result);
    header("Location: http://localhost/manage/info.php?id=$id");

    mysqli_close($conn);
} else { 
    echo json_encode(array("success" => false,"error" => "Some random error happened"));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Well, this is a problem in the code logic. In PHP you need to echo the error if it failed. Clientside everything works.
1

There are several issues with your code:

  • $companyName is not defined anywhere
  • You should use prepared statements instead of throwing data into your SQL query
  • You should put your entire AJAX PHP code inside one try..catch block
  • At the end of your AJAX PHP code, write something some JSON
  • I don't get why you are trying to redirect an AJAX call, usually you'd tell the client to do the redirect.

For example, I would write your PHP code like so:

try {

    if(!isset($_POST['info']))
        throw new Exception('Post info was not set');

    $info = $_POST['info'];

    if($info == 'Info Here')
        throw new Exception('Invalid value for info');

    $conn = mysqli_connect();
    if(!$conn)
        throw new Exception('Database connection failure');

    $companyName = '?????';

    $query = 'INSERT INTO leads VALUES(0, ?, 1, NOW(), 3)';
    $stmt = mysqli_prepare($query);

    if(!$stmt)
        throw new Exception('Could not query database');

    mysqli_stmt_bind_param($stmt, 's', $companyName);
    mysqli_stmt_close($stmt);

    $id = mysqli_stmt_insert_id($stmt);

    mysqli_close($conn);

    echo json_encode(array(
        'success' => true,
        'new_id'  => $id,
    ));

}catch(Exception $ex){

    echo json_encode(array(
        'success' => false,
        'reason'  => $ex->getMessage(),
    ));

}

Comments

0

Alternate Approach

HTML: place this paragraph tag where you want to display an error.

<p id="display_error"></p>

Ajax success call: change your Ajax code bit like...

success: function(response) 
{
      if((response !== "") && ($.isNumeric(response))) {
        {
         //redirect in ajax success
         location.href = "http://localhost/manage/info.php?id="+ response;
        } 
      else {
             //this will display the custom error.
             $("#display_error").html("<p>" + response + "</p>"); //output: something went wrong!
           }
 }

PHP

$info = $_POST['info'];

if($info != 'Info Here') {
    $conn = mysqli_connect();
    $query = "INSERT INTO leads VALUES(0, '$companyName', 1, NOW(), 3)";
    $result = mysqli_query($conn, $query) or die ('Error Could Not Query');

    $id = mysqli_insert_id($result);

    echo $id;

   //header("Location: http://localhost/manage/info.php?id=$id");

    mysqli_close($conn);
} else { 
    echo 'something went wrong!';
}

Comments

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.