数据不通过AJAX调用发送

时间:2015-08-14 13:13:02

标签: javascript php jquery mysql ajax

我在使用AJAX时遇到困难。我正在尝试发送正在发布通知的用户的ID,然后发送消息。由于某种原因,user_id没有发送过来。消息正在发送,但我收到一条错误,说它有一个未定义的索引,但是我将所有内容处理成另一个文件并且消息正在通过。我正在尝试使用用户ID的会话来发送,但我也尝试进行public double EndAngleValue { get { return _EndAngleValue; } set { SetProperty(ref _EndAngleValue, value); OnPropertyChanged("EndAngleValue"); } } private OnPropertyChanged(string propertyName) { if(PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } 查询并以此方式发送,但仍然无法发送。

这是我的会话代码..

SELECT

我做错了是什么让用户ID不能通过我的查询发送到我的数据库?

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

表格

$(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.
                         }
                     });
                 });
             });

insertannouncements.php

  <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>

我收到以下错误

$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!";
    }
?>

公告INSERT execute()失败:列'message'不能为空

但是我发送的内容发送到我的文件并且邮件正在发送?只是user_id显示为空白。

4 个答案:

答案 0 :(得分:1)

有一些错误:

  1. var customIcons = { restaurant: { icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png', shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png' }, bar: { icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png', shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png' } }; function load() { var map = new google.maps.Map(document.getElementById("map"), { center: new google.maps.LatLng(37.4419, -122.1419), zoom: 13, mapTypeId: 'roadmap' }); var infoWindow = new google.maps.InfoWindow; // Change this depending on the name of your PHP file downloadUrl("phpsqlajax_genxml.php", function (data) { var xml = data.responseXML; var markers = xml.documentElement.getElementsByTagName("marker"); for (var i = 0; i < markers.length; i++) { var name = markers[i].getAttribute("name"); var address = markers[i].getAttribute("address"); var type = markers[i].getAttribute("type"); // var latlng = markers[i].getPosition(); var latitude = markers[i].getAttribute("lat"); var longitude = markers[i].getAttribute("lng"); var point = new google.maps.LatLng( parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng"))); var html = "<table class='tg'>" + "<tr>" + "<th class='tg-031e'>Name</th>" + "<th class='tg-031e'>Address</th>" + "<th class='tg-031e'>Work Type</th>" + "<th class='tg-031e'>Latitude</th>" + "</tr>" + "<tr>" + "<td class='tg-031e'><input type='text' id='name' value='" + name + "'/> </td>" + "<td class='tg-031e'><input type='text' id='address' value='" + address + "'/> </td>" + "<td class='tg-031e'><input type='text' id='type' value='" + type + "'/> </td>" + "<td class='tg-031e'><input type='text' id='lat' value='" + latitude + "'/> </td>" + "</tr>" + "</table>" + "<input type='submit' value='submit' onclick='return chk()'>"; // var html = "<b>" + name + "</b> <br/>" + address + "<br/>" + type + "<br/>" + latitude + "<br/>" + longitude + "<input"; var icon = customIcons[type] || {}; var marker = new google.maps.Marker({ map: map, position: point, draggable: true, icon: icon.icon, shadow: icon.shadow }); bindInfoWindow(marker, map, infoWindow, html); } }); } function bindInfoWindow(marker, map, infoWindow, html) { google.maps.event.addListener(marker, 'click', function () { infoWindow.setContent(html); infoWindow.open(map, marker); }); } function downloadUrl(url, callback) { var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest; request.onreadystatechange = function () { if (request.readyState == 4) { request.onreadystatechange = doNothing; callback(request, request.status); } }; request.open('GET', url, true); request.send(null); } function doNothing() {}
  2. $user = $("#approved_id").val();

答案 1 :(得分:0)

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

更改为user_message

答案 2 :(得分:0)

使用:@Override public void getView(int position, View convertView, ViewGroup parent) { // Some code here holder.bindProduct(myproductlist.get(position)); //other code... }

您正在尝试获取所点击元素的值(提交按钮)。

应该是:$user = this.value;

同时检查$user = $("#approved_id").val();变量的名称,在js / client端重命名为'user_message':

message

'消息'在php /服务器端。

"user_message": user_message

答案 3 :(得分:0)

这是我看到的问题:

在您的AJAX通话中,您发送以下参数:

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

其中$user的定义如下:$user = this.value;这意味着该值来自它所在的函数,click上的"#submit_announcement"事件就像这样:< / p>

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

这样做就是将元素#submit_announcement的值分配给$user但是如果我们查看HTML,我们会发现#submit_announcement只是一个没有价值的简单按钮:

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

您尝试做的是获取表单提交的值。为此,您需要使用事件处理程序.submit()而不是.click(),因为您要提交formsubmit()事件应附加到表单元素,如下所示:

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

另外,请确保将button元素的type属性更改为submit,如下所示:

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

完成此操作后,现在您可以使用.serialize()将表单元素和值编码为可在POST请求中发送的字符串形式,如下所示:

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

现在你拥有了所有这些,你可以通过ajax发送它,因此

最终结果:

$("#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;
});