-1

I want my program below to return false if the employee ID exists. My PHP file echoes true if the employee ID exists and it is returned to the AJAX function.

$.post("connect_ajax_php.php",
    {type: "checkId", val: val, field: "emp_id", table: "employee"})
    .done(function(data, succ){
        data = $.trim(data);
        if( succ =="success" && data=="true" ){
            $( errContId ).html( val+" already exist" );
            $( id ).css( {"border":"1px solid red"} );
            $('#'+sucImg).html("<img src='images/background/error.png'>");
            return false;
        }else{
            $( errContId ).html("");
            $( id ).css( {"border":"1px solid #ccc"} );
            $('#'+sucImg).html("<img src='images/background/success.png'>");
        }
    });
TreeTree
  • 3,200
  • 3
  • 27
  • 39

1 Answers1

0

If you are using the ajax call as a validation step you will manually submit the form in the ajax callback. Then move the return false to the click handler rather than call it from the ajax response handler.

<form id="myform" action="/url" method="post">
    ...
    <button id="submitbtn" type="submit">Submit</button>
</form>

$("#submitbtn").on("click", function(event) {
    $.ajax({
        url: "connect_ajax_php.php",
        method: "post",
        data: {type: "checkId", val: val, field: "emp_id", table: "employee"}
    })
    .done(function(result) {
        if (result == "true") {
            // id exists
        }
        else {
            $("#myform").submit();
        }
    });

    return false;  // prevent standard form submission
});
Jasen
  • 14,030
  • 3
  • 51
  • 68