jquery ajax submit always comes back as successful after validation

旧城冷巷雨未停 提交于 2020-01-24 01:10:32

问题


I've created a form using jquery validate. The form validates correctly and as soon as every field has been validated as correct, it's meant to submit via ajax. This is where the problem appears. I've purposely set incorrect login details for the database so I'm expecting the ajax submit to return with an error, but it always comes back as successful (the debug() confirms that there is a problem connecting to the DB). I've used the correct credentials as well and it submits to the DB and also replys with the same "successful" alert message.

Here's the relative code:

$("#form1").validate({
        ignore: "hidden:not(select)",
        rules: {
            //custom rules
        },
        messages:{
            //custom messages
        },
        errorPlacement: function(error, element) {
            //custom error placement
        },
        submitHandler: function(form){
                $.ajax({
                url: "submitForm.php",
                type: "post",
                data: $(form).serialize(),
                success: function(){
                    alert("successful");
                },
                error: function(jq,status,message){
                    alert("failed");
                }
            });
            return false;
        }
    });

回答1:


The reason you are still getting "Successful" is because PHP sends a 200 response in order for the browser to display the PHP error and the success: handler checks for a 200 response.

If PHP did not send a 200 response then you would never see PHP errors.

The ideal solution is to do server-side validation as to whether or not the query succeeded and then send back a custom success and error response to AJAX's success handler.

Below is a quick n' dirty demo

AJAX

$.ajax({
    url: "submitForm.php",
    type: "post",
    data: $(form).serialize(),
    dataType: 'json'
    success: function(data){
        alert(data['success']+' : '+data['message']);

        if(data['success']){
            // do successful things
        }
        else{
            // do failure things
        }
    },
    error: function(jq,status,message){
        alert("failed");
    }
});

submitForm.php

<?php
if($query == 'successful'){
    $return['success'] = true;
    $return['message'] = 'Success!';
}
else{
    $return['success'] = false;
    $return['message'] = 'Failed!';
}

echo json_encode($return);
?>



回答2:


There is another way to do it.

if($("#form1").validate())
{




$.ajax({
                url: "submitForm.php",
                type: "post",
                data: $(form).serialize(),
                success: function(){
                    alert("successful");
                },
                error: function(jq,status,message){
                    alert("failed");
                }
            });
            return false;

 }



回答3:


This code:

success: function(){
    alert("successful");
},

Gets executed when your AJAX call is successful, not when a login is successful. You need to pass a login result response to your JavaScript, such as:

success: function(response){
    if ( response === 'successful' )
    {
        alert('success');
    }
    else
    {
        alert('failed to login');
    }
},

Also be careful to give a proper response. For example, the response will be a whole HTML page (which we don't really want to pass around), so in your PHP you could do something like this:

if ( login_checking_function() )
{
    if ( empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
         strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
       )
    {
        echo 'successful';
    }
        else
        {
            // do something for non AJAX call, but successful login
        }
}

You check for $_SERVER['HTTP_X_REQUESTED_WITH'] because jQuery adds this header to the AJAX call, that way you know the page is being requsted via AJAX.



来源:https://stackoverflow.com/questions/18897704/jquery-ajax-submit-always-comes-back-as-successful-after-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!