简体   繁体   English

数据未通过AJAX调用发送

[英]Data not sending through with AJAX call

I am having difficulties with an AJAX call. 我在拨打AJAX电话时遇到困难。 I am trying to send over the id of the user who is making the announcement and then the message. 我正在尝试发送公告的用户ID,然后发送消息。 For some reason the user_id is not sending over. 由于某种原因,user_id没有发送出去。 The message is sending over, but I am getting an error saying it has an undefined index, but I process all of the contents into another file and the message is going through. 消息正在发送,但是我收到一条错误消息,说它具有未定义的索引,但是我将所有内容处理到另一个文件中,消息正在通过。 I am trying to use a session of the user's id for that to send through, but I have also tried doing a SELECT query and sending it that way and it still doesn't send. 我正在尝试使用用户ID的会话来进行发送,但我也尝试过执行SELECT查询并以这种方式发送,但仍然无法发送。

Here is my session code.. 这是我的会话代码。

$userid = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );

What am I doing wrong that is making the userid not send through and for my query to not send to my database? 我做错了什么,导致用户ID无法发送并且查询无法发送到数据库?

$(document).ready(function(){ 
             $("#submit_announcement").on("click", function () {

             var user_message = $("#announcement_message").val();
                $user = this.value;
                $.ajax({ 
                    url: "insert_announcements.php", 
                    type: "POST",
                    //data : 
                    //{'message':message,'anothermessgae':another}
                    data: {
                           "user_id": $user,
                                        "message": user_message
                            },
                    success: function (data) {
                           //  console.log(data); // data object will return the response when status code is 200
                             if (data == "Error!") {
                                 alert("Unable to get user info!");
                                 alert(data);
                             } else {
                                 $(".announcement_success").fadeIn();
                                 $(".announcement_success").show();
                                 $('.announcement_success').html('Payment Status Changed!');
                                 $('.announcement_success').delay(5000).fadeOut(400);
                             }
                         },
                         error: function (xhr, textStatus, errorThrown) {
                             alert(textStatus + "|" + errorThrown);
                             //console.log("error"); //otherwise error if status code is other than 200.
                         }
                     });
                 });
             });

Form 形成

  <div class="announcement_success"></div>
        <p>Add New Announcement</p>
            <form action="" method="POST" id="insert_announcements">
            <input type="hidden" value="<?php echo $userid; ?>" id="approved_id" name="user_id" />
                <textarea rows="4" cols="50" id="announcement_message" name="message" class="inputbarmessage" placeholder="Message" required></textarea>
                <label for="contactButton">
                    <button type="button" class="contactButton" id="submit_announcement">Add Announcement</button>
                </label>
            </form>

insertannouncements.php insertannouncements.php

$announcement_user_id= $_POST['user_id'];
$announcement_message= $_POST['user_message'];
//$test = print_r($_POST, true); 
//file_put_contents('test.txt', $test); 
//var_dump($announcement_user_id);

$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('is', $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!";
    }
?>

I get the following error 我收到以下错误

<b>Notice</b>:  Undefined index: user_message in <b>/home4/gregre/public_html/example.com/insert_announcements.php</b> on line <b>9</b><br />

Announcement INSERT execute() failed: Column 'message' cannot be null 公告INSERT execute()失败:“消息”列不能为空

But I am sending the content of what is sent over to my file and the message is sending through? 但是我正在发送的内容已发送到我的文件中,并且消息正在通过发送? Just the user_id is showing blank. 仅user_id显示为空白。

有一些错误:

  1. $user = $("#approved_id").val();
  2. "user_message": user_message
data: {
   "user_id": $user,
   "user_message": user_message
 },

Change to user_message 更改为user_message

With: $user = this.value; 使用: $user = this.value;

you are trying to get the value of the clicked element (the submit button). 您正在尝试获取clicked元素的值(提交按钮)。

It should be: $user = $("#approved_id").val(); 应该是: $user = $("#approved_id").val();

Also check the name of the message variable, either rename it 'user_message' on the js/client side: 还要检查message变量的名称,在js /客户端将其重命名为“ user_message”:

"user_message": user_message

or 'message' on the php/server side. 在PHP /服务器端的“消息”。

$announcement_message= $_POST['message'];

This is the issue I am seeing: 这是我看到的问题:

In your AJAX call you are sending these parameters: 在AJAX调用中,您正在发送以下参数:

data: {
  "user_id": $user,
  "message": user_message
},

Where $user is defined like this: $user = this.value; 其中$user的定义如下: $user = this.value; which means the value comes from the the function it resides in which is the click event on "#submit_announcement" like this: 这意味着该值来自其所驻留的函数,即"#submit_announcement"上的click事件,如下所示:

$("#submit_announcement").on("click", function () {
    //..code
    $user = this.value;
    //..code
});

Doing it this way you are assigning the value of the element #submit_announcement to $user however if we look at the HTML, we see that #submit_announcement is just a simple button with no value: 通过这种方式,您可以将元素#submit_announcement的值分配给$user但是,如果我们查看HTML,我们会看到#submit_announcement只是一个简单的没有值的按钮:

<button type="button" class="contactButton" id="submit_announcement">Add Announcement</button>

What it seems you are trying to do is get values submitted by the form. 您似乎想做的就是获取表单提交的值。 To do that you need to use the event handler .submit() rather then .click() since you are submitting a form . 为此,您需要使用事件处理程序.submit()而不是.submit() .click()因为您要提交form The submit() event should be attached to the form element like this: submit()事件应像这样附加到form元素:

$("#insert_announcements").submit(function () {
    //..code
});

Also make sure you change your button element's type attribute to submit like this: 还要确保将button元素的type属性更改为像这样submit

<button type="submit" class="contactButton" id="submit_announcement">Add Announcement</button>

Once you do that, now you can use .serialize() to encode your form elements and values to a string form that can be sent in your POST request like this: 完成此操作后,现在可以使用.serialize()将表单元素和值编码为可在POST请求中发送的字符串形式,如下所示:

$("#insert_announcements").submit(function () {
    var form_elems = $(this).serialize();
});

Now that you have all that, you can send it through ajax, thus 现在您已经拥有了所有这些,您可以通过ajax发送它,这样

FINAL RESULT: 最后结果:

$("#insert_announcements").submit(function () {
    var form_elems = $(this).serialize();
    $.ajax({ 
         url: "insert_announcements.php", 
         type: "POST",
         data: form_elems,
         success: function (data) {
             //your result code
         }
    });
    return false;
});

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

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