简体   繁体   English

Ajax,添加到数据库并更新div内容

[英]Ajax, add to database and update div content

Okay, so I am trying to use ajax. 好的,所以我正在尝试使用Ajax。 I've tried several ways of doing this but nothing is working for me. 我已经尝试了几种方法来执行此操作,但是没有任何工作对我有用。 I believe the main problem I have is that ajax won't add to my database, the rest is managable for me. 我相信主要的问题是ajax不会添加到我的数据库中,其余的对我来说都是可以管理的。

Here is the relevant ajax-code: 这是相关的ajax代码:

$(document).ready(function(){
console.log($("going to attach submit to:","form[name='threadForm']"));
$("form[name='threadForm']").on("submit",function(e){
    e.preventDefault();
    var message = $("#message").val();
   //assumming validate_post returns true of false(y)
   if(!validatepost(message)){
       console.log("invalid, do not post");
       return;
   }
   console.log("submitting threadForm");
   update_post(message);
});
});

function update_post(message){
    var dataString = "message=" + message;
    alert(dataString);

    $.ajax({
        url: 'post_process.php',
        async: true,
        data: dataString ,
        type: 'post',
        success: function() {
            posts();
        }
    });
 }

 function posts(){
     console.log("getting url:",sessionStorage.page);
     $.get(sessionStorage.page,function(data){
         $("#threads").html(data);
     });
 }

 function validatepost(text){
     $(document).ready(function(){

    var y = $.trim(text);
    if (y==null || y=="") {
        alert("String is empty");
        return false;
    } else {
        return true;
    }
    }); 
  }

Here is the post_process.php: 这是post_process.php:

<?php
    // Contains sessionStart and the db-connection
require_once "include/bootstrap.php";   

$message = $con->real_escape_string($_POST["message"]); 

if (validateEmpty($message)){
    send();
}

function send(){
    global $con, $message;

    $con->create_post($_SESSION['username'], $_SESSION['category'], $_SESSION("subject"), $message);
}

//header("Location: index.php");
?>

And lastly, here is the html-form: 最后,这是html表单:

<div id="post_div">
<form name="threadForm" method="POST" action="">
    <label for="message">Meddelande</label><br>
    <textarea id="message" name="message" id="message" maxlength="500">

    </textarea><br>
    <input type="submit" value="Skicka!" name="post_btn" id="post_btn"><br>
</form>

create_post is a function I've written, it and everything else worked fine until I introduced ajax. create_post是我编写的一个函数,在我介绍ajax之前,它和其他所有东西都工作正常。

As it is now, none of the console.log:S are getting reached. 到目前为止,没有console.log:S可以访问。

Ajax works when jumping between pages on the website but the code above literally does nothing right now. 当在网站上的页面之间跳转时,Ajax可以工作,但是上面的代码目前不执行任何操作。 And also, it works if I put post_process.php as the form action and don't comment out the header in post_process-php. 而且,如果我将post_process.php作为表单操作并且不注释掉post_process-php中的标头,它也可以工作。

I apologize for forgetting some info. 抱歉,我忘记了一些信息。 I am tired and just want this to work. 我很累,只想这个工作。

I would first test the update_post by removing the button.submit.onclick and making the form.onsubmit=return update_post. 我首先通过删除button.submit.onclick并制作form.onsubmit = return update_post来测试update_post。 If that is successful place the validate_post in the update_post as a condition, if( !validate_post(this) ){ return false;} 如果成功,则将validate_post作为条件放置在update_post中,如果(!validate_post(this)){return false;}

If it's not successful then the problem is in the php. 如果不成功,则问题出在php中。

You also call posts() to do what looks like what $.get would do. 您还可以调用posts()来完成$ .get的工作。 You could simply call $.get in the ajax return. 您可以简单地在ajax返回中调用$ .get。 I'm not clear what you are trying to accomplish in the "posts" function. 我不清楚您在“帖子”功能中要完成什么。

First you can just submit the form to PHP and see if PHP does what it's supposed to do. 首先,您可以将表单提交给PHP,然后查看PHP是否完成了应做的工作。 If so then try to submit using JavaScript: 如果是这样,请尝试使用JavaScript提交:

$("form[name='threadForm']").on("submit",function(e){
  e.preventDefault();
  //assumming validate_post returns true of false(y)
  if(!validate_post()){
    console.log("invalid, do not post");
    return;
  }
  console.log("submitting threadForm");
  update_post();
});

Press F12 in Chrome or firefox with the firebug plugin installed and see if there are any errors. 在安装了firebug插件的Chrome或firefox中按F12键,查看是否有任何错误。 The POST should show in the console as well so you can inspect what's posted. POST也应显示在控制台中,以便您可以检查发布的内容。 Note that console.log causes an error in IE when you don't have the console opened (press F12 to open), you should remove the logs if you want to support IE. 请注意,当您未打开控制台(按F12打开)时,console.log会在IE中导致错误,如果要支持IE,则应删除日志。

Your function posts could use jQuery as well as it makes the code shorter: 您的函数文章可以使用jQuery并使代码更短:

function posts(){
  console.log("getting url:",sessionStorage.page);
  $.get(sessionStorage.page,function(data){
    $("#threads").html(data);
  });
}

UPDATE 更新

Can you console log if the form is found when you attach the event listener to it? 将事件侦听器附加到表单后,是否可以控制台记录是否找到该表单?

console.log($("going to attach submit to:","form[name='threadForm']"));
$("form[name='threadForm']").on("submit",function(e){
   ....

Then set the action of the form to google.com or something to see if the form gets submitted (it should not if the code works). 然后将表单的操作设置为google.com或其他内容,以查看表单是否已提交(如果代码有效,则不应该提交)。 Then check out the console to see the xhr request and see if there are any errors in the request/responses. 然后,检查控制台以查看xhr请求,并查看请求/响应中是否有任何错误。

Looking at your code it seems you got the post ajax request wrong. 查看您的代码,看来您收到了错误的ajax请求。

function update_post(message){ console.log(message); 函数update_post(message){console.log(message);

$.ajax({
    url: 'post_process.php',
    async: true,
    //data could be a string but I guess it has to
    // be a valid POST or GET string (escape message)
    // easier to just let jQuery handle this one
    data: {message:message} ,
    type: 'post',
    success: function() {
        posts();
    }
});

UPDATE 更新

Something is wrong with your binding to the submit event. 您对Submit事件的绑定存在问题。 Here is an example how it can be done: 这是一个如何完成的示例:

<!DOCTYPE html>
<html>
  <head>
    <script src="the jquery library"></script>
  </head>
  <body>
<form name="threadForm" method="POST" action="http://www.google.com">
    <label for="message">Meddelande</label><br>
    <textarea id="message" name="message" id="message" maxlength="500">
    </textarea><br>
    <input type="submit" value="Skicka!" name="post_btn" id="post_btn"><br>
</form>
      <script>
$("form[name='threadForm']").on("submit",function(e){
  e.preventDefault();
  console.log("message is:",$("#message").val());
});   
      </script>
  </body>
</html>

Even with message having 2 id properties (you should remove one) it works fine, the form is not submitted. 即使消息具有2个id属性(您应该删除一个),它也可以正常工作,但不会提交表单。 Maybe your html is invalid or you are not attaching the event handler but looking at your updated question I think you got how to use document.ready wrong, in my example I don't need to use document.ready because the script accesses the form after the html is loaded, if the script was before the html code that defines the form you should use document ready. 也许您的html无效,或者您没有附加事件处理程序,而是查看更新的问题,我认为您已经知道如何使用document.ready,在我的示例中,我不需要使用document.ready,因为脚本可以访问表单加载html之后,如果脚本位于定义表单的html代码之前,则应准备使用文档。

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

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