AJAX呼叫不发送

时间:2015-08-12 12:48:51

标签: php jquery ajax forms

我正在尝试创建我的第一个AJAX调用。我所要做的就是向我的数据库发送一条消息,其中包含user_id,消息和日期。

截至目前,当我点击提交按钮时,甚至都没有发生任何事情。为什么这不提交,我不确定我是否正确创建了ajax调用。

我做错了什么?

我的ajax电话

$(document).ready(function () {
    $("#submit_announcement").on("click", function () {
        $user = this.value;
        $.ajax({
            url: "insert_announcements.php",
            type: "POST",
            data: "username=" + $user,
            success: function (text) {
                if (text == "Error!") {
                    alert("Unable to get user info!");
                    $(".announcement_success").fadeIn();
                    $(".announcement_success").show();
                    $('.announcement_success').html('Payment Status Changed!');
                    $('.announcement_success').delay(5000).fadeOut(400);
                    alert(data);
                } else {
                    var txtArr = text.split('|');
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                alert(textStatus + "|" + errorThrown);
            }
        });
    });
});

表格

<div class="announcement_success"></div>
<p>Add New Announcement</p>
<form action="" method="POST" id="insert_announcements">
    <textarea rows="4" cols="50" id="announcement_message " name="message" class="inputbarmessage" placeholder="Message" required></textarea>
    <label for="contactButton">
        <input type="button" class="contactButton" value="Add Announcement" id="submit">
    </label>
</form>

PHP文件insert_announcements.php

$con = mysqli_connect("localhost", "", "", "");
$stmt2 = $con->prepare("INSERT INTO announcements (user_id, message, date) VALUES (?, ?, NOW())");
    if ( !$stmt2 || $con->error ) {
        // Check Errors for prepare
         die('Announcement INSERT prepare() failed: ' . htmlspecialchars($con->error));
    }
    if(!$stmt2->bind_param('isi', $announcement_user_id, $announcement_message)) {
        // Check errors for binding parameters
        die('Announcement INSERT bind_param() failed: ' . htmlspecialchars($stmt2->error));
    }
    if(!$stmt2->execute()) {
        die('Announcement INSERT execute() failed: ' . htmlspecialchars($stmt2->error));
    }
        echo "Announcement was added successfully!";
    else
    {
         echo "Announcement Failed!";
    }

7 个答案:

答案 0 :(得分:2)

您的按钮的jquery选择器出错了,请将其更改为:

$("#submit").on("click", function(){

答案 1 :(得分:2)

您正在触发ID为#submit_announcement的元素的点击,该元素与您的表单提交按钮的ID不同。更改$("#submit_announcement").on("click", function(){

 $("#submit").on("click", function(){

答案 2 :(得分:2)

在PHP中,您无法在}else

之间回应
 }
        echo "Announcement was added successfully!";
    else

答案 3 :(得分:1)

使用以下事件绑定方法之一:

$(document).ready(function(){
    $("#submit").on("click", function(){ console.log('reached'); /* code here */ });

    $('#insert_announcements').on('submit',function(){ /* code here */ })


 }) 

上述方法之一应该有效。你的ajax代码看起来很好。只需使用上面的事件绑定包装器之一,让魔法发生。

<强>更新

检查工作小提琴:https://jsfiddle.net/hfddcop0/

你犯的错误

1)指定错误的提交按钮ID。它是submit_announcement而不是#submit

2)定义了名为usermessage的未知变量。我用小提琴中的字符串值替换它。

有效负载应该像

data : {'message':message,'anothermessgae':another}  , You were mentioning like     data : {'message':message;} which is a syntax error . 

答案 4 :(得分:0)

因为您在单击提交按钮时未创建该功能。按钮ID为submit

所以试试:

$(document).ready(function(){ 
        $("#submit").on("click", function(){
            $user = this.value;
            $.ajax({ 
                url: "insert_announcements.php", 
                type: "POST",
                data: "username="+$user, 
                success: function(text){ 
                    if(text == "Error!"){ 
                        alert("Unable to get user info!"); 
                        $(".announcement_success").fadeIn();
                        $(".announcement_success").show();
                        $('.announcement_success').html('Payment Status Changed!');
                        $('.announcement_success').delay(5000).fadeOut(400);
                        alert(data);
                    } else { 
                        var txtArr = text.split('|');
                    } 
                }, 
                error: function(xhr, textStatus, errorThrown){ 
                    alert(textStatus + "|" + errorThrown); 
                } 
            });
        });
    });

答案 5 :(得分:0)

您没有向服务器发送user_id,消息和日期以获取响应。 首先获取输入的值,然后发送。如下所示:

var announcement_message = $("#announcement_message).val();

而不是类型,它应该是method.a在ajax中定义数据类型。 在html中,删除method =&#34; post&#34 ;,只定义方法一次。

答案 6 :(得分:0)

 $("#submit").on("click", function(){

var usermessage = $("#announcement_message).val();
var username = "ralph"; // let say you get the username value;
var date_now = Date.now();

$.ajax({
url:"insert_announcements.php",
method:"POST",
data:{
    "user_id":username,
    "message":usermessage,
    "date":date_now

}
success:function(data){
  console.log(data); // data object will return the response when status code is 200
},
error:function(){
console.log("error");//otherwise error if status code is other than 200.
}

});


});