2015-04-17 92 views
0

我正在進行一個php聊天,一切都很好,但我想要ajax來停止刷新頁面。聊天表單不提交

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
<script> 
$(document).ready(function() { 
    $("#submit").on("click", function (event) { 
     event.preventDefault(); 
     $.ajax({ 
      type: "POST", 
      url: "index.php", 
      data: $("#chat").serialize(), 
      success: function() { 
       alert('lorem ipsum'); 
      } 
     }); 
    }); 
}); 
</script> 

<form name="chat" action="" method="post" id="chat"> 
<b>Msg:</b> 
<input type="text" name="msg" size="30" class="text"> 
<input type="submit" name="submit" value="Send!" class="bttn" id="submit"> 
<input type="hidden" name="lastcat" value="<?php echo $simplecat; ?>"> 
<input type="hidden" name="lastwas" value="<?php echo $command; ?>"> 
</form> 

<hr> 
<div class="leftalign"> 
    <b class="yousay">You say:</b> <?php echo stripslashes($usermessage); ?><br /><br /> 

<b class="catsays">Cat replies:</b> <?php echo $catreply;?><br /><br /> 

我看到信息框和頁面不會刷新,但我的$ _POST ['msg']是空的,所以我錯過了什麼?

回答

1

你是不是很清楚您的消息應該去,但是這應該修復它......在一定程度上:

page1.php中

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
<script> 
$(document).ready(function() { 
    $("#submit").on("click", function (event) { 
     event.preventDefault(); 
     $.ajax({ 
      type: "POST", 
      url: "index.php", 
      data: $("#chat").serialize(), 
      success: function (response) { 
       alert('lorem ipsum'); 
       // You need somewhere to drop the response into. 
       // I've chosen the id "response" 
       $("#response").html(response); 
      } 
     }); 
    }); 
}); 
</script> 

<form name="chat" action="" method="post" id="chat"> 
<b>Msg:</b> 
<input type="text" name="msg" size="30" class="text"> 
<input type="submit" name="submit" value="Send!" class="bttn" id="submit"> 
<input type="hidden" name="lastcat" value="<?php echo $simplecat; ?>"> 
<input type="hidden" name="lastwas" value="<?php echo $command; ?>"> 
</form> 
<hr> 
<div class="leftalign"> 
    <!-- I replaced your php response with where the AJAX should drop in --> 
    <b class="yousay">You say:</b><div id="response"></div><br /><br /> 
    <b class="catsays">Cat replies:</b> <?php echo $catreply;?><br /><br /> 

的index.php

<?php if(isset($_POST['msg'])) { print_r($_POST); return; } ?> 
+0

我的留言應該放在我的代碼下面的同一頁上我有 if(isset($ _ POST ['msg'])){ bla bla bla } –

+0

是的,看看我把它放在哪裏。你需要兩頁來完成這項工作。一個用你的表單,一個用來執行PHP請求。 – Rasclatt

+0

好吧,我看到它爲什麼沒有工作,如果我使用相同的頁面 –