如何使用AJAX

时间:2016-02-11 07:25:54

标签: php jquery ajax

如果我将电子邮件和/或密码代码字段留空并尝试提交表单,则会向我提供客户端错误消息以填充输入框中的所需数据。

在表单页面输入正确的电子邮件和密码后提交表单后,它会在数据库表中插入数据并给出成功消息。

但是如果我在表单页面输入错误的电子邮件和/或密码后提交表单,由于我写的服务器端验证脚本,它不会在数据库表中插入数据,但仍然给我成功消息而不是给出错误电子邮件和/或密码的特定错误消息。

我需要做些什么来显示我从服务器端页面获取错误数据的特定错误消息?

客户端页面(contact.js)

$(function() {
    $("#MyFormName input).jqBootstrapValidation({
    preventSubmit: true,
    submitError: function($form, event, errors) {
        // something to have when submit produces an error ?
        // Not decided if I need it yet
    },
    submitSuccess: function($form, event) {
        event.preventDefault(); // prevent default submit behaviour
        // get values from FORM
        var emailid = $("input#emailid").val();
        var secretcode = $("input#secretcode").val();

        $.ajax({
            url: "./contact_p.php",
            type: "POST",
            data: {
                emailid: emailid,
                secretcode: secretcode
            },
            cache: false,
            success: function() {
                // Success message
                $('#success').html("<div class='alert alert-success'>");
                $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                    .append("</button>");
                $('#success > .alert-success')
                    .append("<strong>Success Message will come here.</strong>");
                $('#success > .alert-success')
                    .append('</div>');

                //clear all fields
                $('#FormPRegister').trigger("reset");
            },
            error: function() {
                // Fail message
                $('#success').html("<div class='alert alert-danger'>");
                $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                    .append("</button>");
                $('#success > .alert-danger').append("<strong>Sorry " + " Error Message will come here!");
                $('#success > .alert-danger').append('</div>');
                //clear all fields
                $('#FormPRegister').trigger("reset");
            },
        })
    },
    filter: function() {
        return $(this).is(":visible");
    },
});

$("a[data-toggle=\"tab\"]").click(function(e) {
    e.preventDefault();
    $(this).tab("show");
});
});

/*When clicking on Full hide fail/success boxes */
$('#r_name').focus(function() {
    $('#success').html('');
});

服务器端页面(contact_p.php)

if( empty($str_emailid) )
{
    echo "No Email ID entered!";
    return false;
}
if( empty($str_secretcode) || $_SESSION['image_secret_code'] != $str_secretcode )
{
    echo "Invalid Secret Code!";
    return false;
}

$str_insert = "INSERT INTO t_contact (emailid,idate,ipaddress) VALUES('".$str_emailid."','".date("Y-m-d H:i:s")."','".$_SERVER['REMOTE_ADDR']."')";
RunQuery($str_insert);

return true;            

4 个答案:

答案 0 :(得分:1)

这不是你的“服务器端页面”因为你给出了回报,这是一种方法。根据您的设置,您可能应该在JSON对象中返回信息,以便javascript可以轻松访问您的信息,也可以提供对象的名称。

{errors:[email:“no email entered”]}

等。虽然这样做,如果你遵循标准,你也应该返回400标题(当出现问题时,在代码中的任何地方)。

header('HTTP/1.1 400 Bad-Request', true, 400); 

这会导致错误功能被触发。

避免只回显字符串,尽管在你设置这个标题时它应该适用于你的情况。

你可能也应该在你的问题中标记jQuery,因为这与jQuery有关。

编辑:

忘了一件事,实际上利用服务器的响应实现以下内容:

是这样的:

    error: function() {

应该是

    error: function(response, status, xhr) {

有关更多信息,请查看jquery文档,同样适用于成功消息。你可以用同样的方式检查那里的反应。

如果您只是回显字符串,则响应应包含错误消息对象。例如,Json对象将允许返回更多信息。

http://api.jquery.com/jquery.ajax/

答案 1 :(得分:0)

我认为你应该使用json格式在php中高效,如下所示 -

if( empty($str_emailid) )
{
    $response['status']='ERR';
    $response['message']= "No Email ID entered!";
    return json_encode($response);
}
if( empty($str_secretcode) || $_SESSION['image_secret_code'] !=        $str_secretcode )
{
    $response['status']='ERR';
    $response['message']= "Invalid Secrete Code!";
    return json_encode($response);
}
$str_insert = "INSERT INTO t_contact (emailid,idate,ipaddress) VALUES('".$str_emailid."','".date("Y-m-d H:i:s")."','".$_SERVER['REMOTE_ADDR']."')";
RunQuery($str_insert);
$response['status']='OK';
$response['message']='Inserted successfully';
return json_encode($response); 

在jquery方面成功

 success: function(data) {
            // Success message
             $responsetext=JSON.parse(data);
             if($responseText.status=='OK')
             {
                $('#success').html("<div class='alert alert-success'>");
                $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                .append("</button>");
                $('#success > .alert-success')
                .append("<strong>Success Message will come here.</strong>");
                $('#success > .alert-success')
                .append('</div>');

                //clear all fields
                $('#FormPRegister').trigger("reset");
             }
            else if($responseText.status=='ERR')
           {
                // do your stuff with your error 
            }

        },

希望这对你很有帮助吗?

答案 2 :(得分:0)

我在这里用PHP,AJAX,JSON发布我的整个工作脚本。我相信其他人会为联系表单页面提供不同类型的工作脚本,但这对我来说很好。

我从这里得到了很多人的帮助,让它发挥作用。所以这是所有人的努力,我真的要感谢他们的帮助。所以我认为我应该在这里发布整个脚本,这样对于像我这样的其他人也会有用。

注意#1:警报(数据); 将有助于通过状态和消息提醒JSON数组响应

注意#2:我没有使用任何现成的captacha脚本

<强> contact.php

<form name="FormPRegister" id="FormPRegister" novalidate>
.
.
other form fields will come here
.
.
<div class="control-group form-group">
    <div class="controls">
        <label>Email Address:</label>
        <input type="email" class="form-control" id="r_email" name="r_email" required data-validation-required-message="Please enter your email address.">
    </div>
</div>
<div class="control-group form-group">
    <div class="controls">
        <label>Secret Code:</label>
        <div class="input-group">
        <input type="text" class="form-control" id="r_secretcode" name="r_secretcode" required data-validation-required-message="Please enter secret code from given image."><span class="input-group-addon input-group-addon-no-padding"><img src="./includes/get_unique_image.php" border="0"></span>
    </div>
</div>
</div>
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="btn btn-primary" tabindex="9">Send Message</button>
</form>

<强> contact.js

$.ajax({
    url: "./contact_p.php",
    type: "POST",
    data: {
    emailid: emailid,
    secretcode: secretcode
},
cache: false,

success: function(data) 
{
//alert(data);
var $responseText=JSON.parse(data);
if($responseText.staus == 'SUC')
{
    // Success message
    $('#success').html("<div class='alert alert-success'>");
    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
    .append("</button>");
    $('#success > .alert-success').append("<strong> " + $responseText.message + " </strong>");
    $('#success > .alert-success').append('</div>');

    //clear all fields
    $('#FormPRegister').trigger("reset");
}

else if($responseText.status == 'ERR')
{
    // Fail message
    $('#success').html("<div class='alert alert-danger'>");
    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
    .append("</button>");
    $('#success > .alert-danger').append("<strong> " + $responseText.message + " ");
    $('#success > .alert-danger').append('</div>');
}
},
})

<强> contact_p.php

.
.
other script will come here as per requirements
.
.
if( empty($_POST["r_email"]) )
{
    $response['status']='ERR';
    $response['message']= "Invalid Email ID!";
    echo json_encode($response); 
    return;
}
if( empty($_POST["r_secretcode"]) || $_SESSION['image_secret_code'] != $_POST["r_secretcode"] )
{
    $response['status']='ERR';
    $response['message']= "Invalid Secrete Code!";
    echo json_encode($response);
    return;
}
.
.
other script will come here as per requirements
.
.
if( Invalid data then do this )
{
    $response['status']='ERR';
    $response['message']= "Invalid Secrete Code!";
    echo json_encode($response);
    return;
}
if( Valid data then do this )
{
    $response['status']='SUC';
    $response['message']= "Inquiry submitted successfully";
    echo json_encode($response);
    return;
}
.
.
other script will come here as per requirements
.
.

答案 3 :(得分:-1)

这就是ajax的工作方式。你的PHP代码很好,这就是你的ajax执行error函数的原因。只有在您的请求失败时才会执行success

在这种情况下,您需要在if( empty($str_emailid) ) { $arr = array("msg"=>"No Email ID entered!","status"=>400); } else if( empty($str_secretcode) || $_SESSION['image_secret_code'] != $str_secretcode ) { $arr = array("msg"=>"Invalid Secret Code!","status"=>400); } else { $str_insert = "INSERT INTO t_contact (emailid,idate,ipaddress) VALUES('".$str_emailid."','".date("Y-m-d H:i:s")."','".$_SERVER['REMOTE_ADDR']."')"; RunQuery($str_insert); $arr = array("msg"=>"Success","status"=>200); } echo json_encode($arr); exit; 函数中处理错误消息。

试试这个:

PHP代码:

success: function(res) {
                if(res.status == 400) {
                  //error message
                } else {
                  //success message
                }
            }

你的成功功能在ajax:

if (isset($_POST['submit'])) {

            echo "<div class='block-content block-content-full bg-danger text-white-op'>";
            $deleterecords = "UPDATE TABLE data"; //empty the table of its current records
            mysql_query($deleterecords);

            $product = $_POST['product'];
            $courier = $_POST['courier'];
            $billmonth = $_POST['billmonth'];
            $billyear = $_POST['billyear'];
            $billrun = $_POST['billrun'];
            $dispatchtype = $_POST['dispatchtype'];


            if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
                //echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
                echo "<p>Displaying contents:</p>";
                echo "<p>Product - <strong style='color: #ffc128'>".$product. " </strong> Service Provider - <strong style='color: #ffc128'>".$courier. "</strong> Bill Month - <strong style='color: #ffc128'>".$billmonth. " </strong> Bill Year - <strong style='color: #ffc128'>".$billyear. "</strong> Bill Run- <strong style='color: #ffc128'>" .$billrun. " </strong> Dispatch Type - <strong style='color: #ffc128'>".$dispatchtype."</strong></p><br/>";
                echo "<span style='color:#feffa4'>";
                readfile($_FILES['filename']['tmp_name']);
                echo "</span>";
            }

            //Import uploaded file to Database
            $handle = fopen($_FILES['filename']['tmp_name'], "r");

            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                /*$linecount = count(file('filename.csv'));*/


                if (($product==$data[0]) && ($courier==$data[1]) && ($billmonth==$data[6]) && ($billyear==$data[7]) && ($billrun==$data[8]) && ($dispatchtype==$data[9])) {

                    $import = "INSERT into data(Product,Courier,Received_Date,Acc_No,Received_By,Delivered_Date,Month,Year,Bill_Run,Dispatch_Type,Status,Bounce_Code) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]','$data[11]')";

                } else {

                    echo " <br/> <br/>Data Error.<br/>";
                    echo "  <br/><br/><a href='javascript:history.go(-1)' class='btn btn-sm btn-primary'><i class='si si-action-undo'></i> Go Back and Upload Again</a> <br/> <br/>";
                }

                mysql_query($import) or die(mysql_error());
            }

        fclose($handle);

        echo "<br/><br/><br/>";
        print "Import done ";/*$linecount*/
        echo "  <br/><br/><a href='javascript:history.go(-1)' class='btn btn-sm btn-primary'><i class='si si-action-undo'></i> Go Back and Upload Again</a> <a href='index.php' class='btn btn-sm btn-primary'><i class='si si-home'></i> Home</a>  <br/> <br/>";

        //view upload form

        echo "</div>";