简体   繁体   English

将AJAX调用的结果传递给PHP脚本

[英]Passing result from AJAX call to PHP script

I'm working on my first HTML form that performs an AJAX HTTP POST using jQuery. 我正在处理我的第一个使用jQuery执行AJAX HTTP POST的HTML表单。 When a user makes a change to an input text field and tabs out of the field it triggers the AJAX script which in turn calls a PHP script which performs a database update. 当用户更改输入文本字段并在该字段外进行制表时,它将触发AJAX脚本,该脚本随后调用执行数据库更新的PHP脚本。

The AJAX call can be successful but the database update could be unsuccessful (eg database related error) - I would like to insert the result of the PHP script into an alert. AJAX调用可以成功,但是数据库更新可能失败(例如,与数据库相关的错误)-我想将PHP脚本的结果插入警报中。 I can echo out any errors in in my PHP script, but I'm not sure how to get that into the appropriate alert. 我可以在PHP脚本中回显任何错误,但是我不确定如何将其引入适当的警报中。

Here's my Javascript: 这是我的Javascript:

 <script type="text/javascript">
   $(document).ready(function() {
    $("#storeManager").change(function(){
        var storeManager = $("#storeManager").val();
        $.post('editProject.php', { storeManager: storeManager, id: '1E1DDA14-D2C6-4FC8-BA5F-DBCCC7ABAF7F' }, function(data) {
            $("#managerRow").addClass("success");

        }).fail(function () {
            // no data available in this context
            $("#managerRow").addClass("danger");
            $("#ajaxAlert").addClass("alert alert-danger");
        });
     }); 
});
</script>

Here's the HTML table that contains the input field that triggers the AJAX call: 这是HTML表,其中包含触发AJAX调用的输入字段:

    <table class="table table-striped table-bordered table-hover">
    <tbody>
    <tr>
    <td>Store</td>
    <td>Acme Widgets Inc</td>
    </tr>
    <tr>
    <td>Retailer</td>
    <td>Acme Corp</td>
    </tr>
    <tr>
    <td>Store ID</td>
    <td>9876543</td>
    </tr>
    <tr>
    <td>State</td>
    <td>NSW</td>
    </tr>
    <tr class="" id="managerRow">
    <td>Manager</td>
    <td>

    <input type="text" class="form-control" id="storeManager" name="storeManager" value="Peter Johns">

    </td>
    </tr>
    <tr>
    <td>Phone</td>
    <td>9222 3456</td>
    </tr>
    </tbody>
    </table>

    <div class="" id="ajaxAlert" role="alert"></div>

What I would like to do is, if there is any error from the editProject.php script that it stores in a $error variable and can echo out, to then insert this into the ajaxAlert and add a class: alert: 我想做的是,如果editProject.php脚本中有任何错误(存储在$ error变量中并且可以回显),然后将其插入ajaxAlert并添加一个类:alert:

<div class="alert alert-danger" id="ajaxAlert" role="alert">The error from the database update from the php script appears here</div>

I'm new to jQuery and AJAX and everything I've tried hasn't updated the alert with the new class and alert text and I can't seem to find a similar to example that demonstrates this. 我是jQuery和AJAX的新手,我尝试过的所有操作都没有使用新的类和警报文本来更新警报,而且似乎无法找到类似于演示此示例的示例。

You can use the append() in jquery. 您可以在jquery中使用append() Try using 尝试使用

fail(function () {
        // no data available in this context
        $("#managerRow").addClass("danger");
        //append error to the div using its ID
        $('#ajaxAlert').append('error from database');
    });

Try this: instead of .fail(); 试试这个:代替.fail();

    var storeManager = $("#storeManager").val();
    $.post('editProject.php', { storeManager: storeManager, id: '1E1DDA14-D2C6-4FC8-BA5F-DBCCC7ABAF7F' }, function(data) {
        alert(data);

    },function (xhr, data, jx) {
        // the error function should be mentioned like this with comma after success fucntion
        console.log(xhr);//for console logging the error...
         alert(xhr);//NOW you will get data and alert will show...
    });

index.php index.php

----php start---------     
if(isset($_POST['name'])){
    $dbc = mysqli_connect('','','','');
    $sql = "UPDATE accounts set name='".$_POST['name']." WHERE email='".$_POST['mail']."' LIMIT 1";
    if(mysqli_query($dbc, $sql) === true)){
        echo 'success'; exit();
    }else{
        echo 'connection error'; exit();
    }
}
----php end  ---------
<script>
    function test(){
        var formDATA = {
            'name': $('#input_name').val(),
            'mail': $('#input_mail').val()
        };
        $.ajax({
            type: 'POST',
            url: 'index.php',
            data: formDATA,
            success: function(response){
                if(response == 'success'){
                    $('#result').html('Your Update Was Complete');
                }else{
                    $('#result').html();
                }
            }
        });
    }
</script>
<input id="input_mail" type="text" value="">
<input id="input_name" type="text" value="">
<button onclick="test();">Test Ajax</button>
<div id="result"></div>

Try something simple, this is a very basic version of ajax and php all in one page. 尝试简单的方法,这是ajax和php的非常基本的版本,全部都在一个页面中。 Since the button triggers the function you don't even need a form (doesn't mean you shouldn't use one). 由于按钮触发了该功能,因此您甚至不需要表单(并不意味着您不应该使用表单)。 But i left it simple so you could follow everything. 但是我让它简单了,所以您可以遵循所有内容。

Sorry when i added php open and closing tags it didn't show up as code. 抱歉,当我添加php打开和关闭标签时,它没有显示为代码。 Also don't forget to include your jquery resources. 另外,不要忘记包括您的jquery资源。

WARNING: DO NOT DO QUERIES LIKE THE EXAMPLE, THIS IS A HUGE SECURITY RISK! 警告:请勿像示例一样进行查询,这是巨大的安全风险!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM