AJAX函数表现得很奇怪

时间:2013-10-06 18:51:51

标签: javascript php mysql ajax post

我有这个AJAX函数应该将数据传递给php代码,然后将其输入到数据库中,然后发生这种情况,但AJAX实际上并没有按照它应该的方式工作。

             <?php         
     session_start();
    include_once("../engine/database.php");
    if (isset($_POST["name"],$_POST["password"]) ) {      
      $uname  = htmlspecialchars(mysql_real_escape_string($_POST["name"]) );
      $passwd = htmlspecialchars(mysql_real_escape_string($_POST["password"]) );
      $query = "SELECT * FROM users WHERE username ='".$uname."' AND password='".$passwd."' LIMIT 1";
      $query= mysql_query($query);
      if(mysql_num_rows($query) == 1) {        
        $_SESSION['admin'] = "Welcome to the Admin Panel {$_POST['name']} ";
        $_SESSION['onOff'] = 'on';
       ?>        
     <!DOCTYPE html>
      <html>
      <head>
          <meta charset="utf-8">
          <meta http-equiv="X-UA-Compatible" content="IE=edge">
          <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.3.0/pure-min.css">
          <script type="text/javascript" src="//tinymce.cachefly.net/4.0/tinymce.min.js"></script> 
          <script>
          tinymce.init({
              selector: "textarea#postCont",
              plugins: [
                  "advlist autolink lists link image charmap print preview anchor",
                  "searchreplace visualblocks code fullscreen",
                  "insertdatetime media table contextmenu paste"
              ],
              toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image"
          });
        </script>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript" charset="utf-8" async defer></script>

          <title>Admin Panel</title>     
      </head>
      <body>        
        <div class="pure-g-r" style="letter-spacing:0em; padding-left:2em; padding-right:2em;">   
           <div class="pure-u-5-10">                                
              <form class="pure-form pure-form-stacked" action='../engine/engine.php' method='post'>
                <fieldset>         
                  <legend><?php echo  $_SESSION['admin']; ?></legend>
                  <div style="margin:0 auto;">                      
                      <input type='text' name='postTitle' class="pure-input-1" placeholder='Article Title'/>                                
                  </div>
                  <textarea  class="pure-input-1" name='postDes' name='postDes' cols='102' placeholder='Article Summary'></textarea>                  
                  <textarea  id="postCont" name='postCont' cols='60' rows='10'></textarea>                  
                  <br />
                  <button type="submit" name="blogsubmit" class="pure-button pure-input-1 pure-button-primary">Submit</button>                  
                </fieldset>                
              </form>
          </div>
          <div class="pure-u-1-10">

          </div>
          <div class="pure-u-4-10">                             
                  <h2 style="margin:0 auto;">Posted articles</h2>
                  <dl>
                      <dt>How to create a Text editor</dt>
                      <dd><a href=""><small><a href="">Edit</a></small> | <small><a href=""> Delete</a></small></a>
                      <dt>How to create a Text editor</dt>
                      <dd><a href=""><small><a href="">Edit</a></small> | <small><a href="">Delete</a></small></a>                                 
                  </dl>                                
          </div>                  
        </div>
        <script type="text/javascript">
                function submit() {
                      var xhr = new XMLHttpRequest();
                      try {
                        xhr = new new ActiveXObject("Msxml2.XMLHTTP");
                      }
                      catch (e) {
                        try {
                          xhr = new ActiveXObject("Microsoft.XMLHTTP");
                        }
                        catch (e) {
                          alert(" Please upgrade your broswer");  
                          return false;
                        }
                      }

                     xhr.onreadystatechange = function () {
                          if (xhr.readyState === 4) {
                                if (xhr.status === 200) {
                                     alert(xhr.responseText);                                                 
                                  } else {
                                            alert("dang!!!");
                                            return false;
                                      }
                          } else {
                                alert("dang!!!! 2 buahahaha");
                                return false;
                          } 
                       var title = document.getElementById('postTitle').value;
                       var postDes = document.getElementById('postDes').value;                                        
                       var postCont = document.getElementById('postCont').value;                                           
                       var data = "title=" + title + "&summary=" + postDes + "&content=" + postCont;                                            
                       xhr.open("POST", "../engine/engine.php",true );
                       xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                       xhr.send(data);                    
                     }                      

                }

          </script>  
      </body>
    </html>         

<?php   }
      else {
          echo "username or password is incorrect";
          die(mysql_error());

      }
    }  

?>

应该将其传递给此代码

                 <?php
include_once('database.php');
if (isset($_POST['blogsubmit'])  ) {
    $title   =  mysql_real_escape_string($_POST['postTitle']);
    $summary =  mysql_real_escape_string($_POST['postDes']);
    $content =  mysql_real_escape_string($_POST['postCont']);
    insertBlogPost($title,$summary,$content);
}

function insertBlogPost($title,$summary,$content) { 
    $query = "INSERT INTO `blogposts` SET
            `title`     = '$title',
            `summary`   = '$summary',               
            `content`   = '$content' ";                                     
    mysql_query($query) or die(mysql_error());
    echo "Yaaaay";      
}
?>

问题是我得到一个打印Yaaay部分而不是警告的页面。我已经尝试过任何我知道的解决问题的方法,所以我真的很感激帮助。我也试过在POST之间切换true和false,但它没有帮助。

PS:很抱歉使用mysql_ *,我仍然不习惯使用PDO。提前谢谢了。

2 个答案:

答案 0 :(得分:3)

你在哪里调用这个AJAX函数?目前,如果你剥夺所有的残余,你有这个:

<form action='../engine/engine.php' method='post'>
    <button type="submit" name="blogsubmit">Submit</button>
</form>
<script type="text/javascript">
    function submit() {
    }
</script>

您没有使用该功能,只是定义它。表单是提交正常POST请求的普通表单,与AJAX无关。在提交POST请求后,它会显示响应中给出的唯一输出:

echo "Yaaaay";

阻止表单提交的一种快捷方法是使按钮不再是submit按钮:

<button name="blogsubmit">Submit</button>

然后你只需要将click处理程序附加到它来调用你的函数。像这样:

<script type="text/javascript">
    function submit() {
        // the rest of your function
    }

    document.getElementsByName('blogsubmit')[0].onclick = submit;
</script>

还有various other ways附加点击事件处理程序。

答案 1 :(得分:1)

从我可以看到你永远不会将你的提交函数绑定到表单的提交事件。 目前你的函数从未被调用,并且表单正在对./engine/engine.php页面进行常规发布,这就是你在新页面上看到它的结果的原因。

您应该将以下属性添加到表单标记:

onsubmit="return submit()"

并且为了覆盖常规表单帖子以便您的功能可以完成工作,您还必须从函数返回false