提交表单时如何将值传递到同一页面? 使用Ajax

问题描述:

Basically, the form has to send data to my database and my database informations should be shown at the same page when user submit the form without refreshing the page. I did something wrong and couldn't find how to fix this. And looked at all the questions but couldn't figure it out. Thanks for the help.

 <div  id="tweetSpace">
      <form id="formTweet" method="post" >
        <textarea id="areaTweet" name="message" rows="2" cols="120" placeholder="Write your tweet here..."></textarea>
        <br>
        <input id="sendTweet" type="submit" value="Send">
      </form>
    </div>

    <div id="txtHint"></div>

<script>
$("#sendTweet").on("submit", function(e){


    var tweet = $('areaTweet').val();
    var update = $('#txtHint');

    $.ajax({
        type: 'POST',
        url: 'tweet2.php',
        data: , tweet,  
        success:function(html){
           update.html(html);
        }
    });
});


</script>

tweet2.php file

<?php 

 include 'connect.php';
  session_start();

$tweet=$_POST['tweet'];
$email =$_SESSION['login_user'];
$sqlr = "INSERT INTO tweets(tweet,member_email) VALUES ('$tweet','$email')";
$rqu = mysqli_query($conn,$sqlr);


$x=0;
$arrayName = array();
$sql= "SELECT tweet FROM tweets WHERE member_email= '$email' "
$rq = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($rq)) {
           $arrayName[$x]  = $row["tweet"];
           $x=$x+1;
}


<?php for($k = 0; $k < $x; $k++) {?>

 <p><?php echo  $arrayName[$k]; ?></p>

<?php } ?


?>

Here is the working code...Note all changes did in 2 files..

HTML

<html>
<head>
    <title>Tweets</title>
</head>

<body>
    <div id="tweetSpace">
      <form id="formTweet" method="post" >
        <textarea id="areaTweet" name="message" rows="2" cols="120" placeholder="Write your tweet here..."></textarea>
        <br>
        <input id="sendTweet" type="button" value="Send">
      </form>
    </div>

    <div id="txtHint"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
  $("#sendTweet").click(function(e){

      var tweet = $('#areaTweet').val();
      var update = $('#txtHint');

      $.ajax({
          type: 'POST',
          data: {'tweet':tweet},
          url: 'tweet2.php',
          success:function(html){
             update.html(html);
          }
      });
  });
</script>

</body>
</html>

tweet2.php

<?php 
session_start();
include 'connect.php';
/*
$servername = "localhost";
$username = "root";
$password = "";
$db = "sflow";
$conn = mysqli_connect($servername, $username, $password, $db); 
*/

$tweet = $_POST['tweet'];
$email = /*"sample@s.com";//*/$_SESSION['login_user'];
$sqlr  = "INSERT INTO tweets(tweet,member_email) VALUES ('$tweet','$email')";
$rqu   = mysqli_query($conn,$sqlr);

$x=0;
$arrayName = array();
$sql= "SELECT tweet FROM tweets WHERE member_email= '$email'";
$rq = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($rq)) {
           $arrayName[$x]  = $row["tweet"];
           $x=$x+1;
}

for($k = 0; $k < $x; $k++)
echo '<p>'.$arrayName[$k].'</p>';
?>

Sample Table

CREATE TABLE IF NOT EXISTS `tweets` (
  `ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `tweet` varchar(255) NOT NULL,
  `member_email` varchar(255) NOT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `sid_2` (`tweet`),
  KEY `sid` (`tweet`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `tweets`
--

INSERT INTO `tweets` (`ID`, `tweet`, `member_email`) VALUES
(1, 'sasa', 's@g.com'),
(2, 'fgfg', 'sample@s.com');

is that an extra comma in your ajax before tweet? data: , tweet,

if so it wont work. should be data: tweet,

You don't want to refresh page ,so must use preventDefault but its only work with form id .So need to change submit button id with form id .Second thing is your data format function must like json {key : value}

$("#formTweet").on("submit", function(e){

e.preventDefault(); //prevent refresh page
var tweet = $('#areaTweet').val();
var update = $('#txtHint');

$.ajax({
    type: 'POST',
    url: 'tweet2.php',
    data: {tweet:tweet},  
    success:function(html){
       update.html(html);
    }
});
});

I think you need to modify your tweet2.php

<?php 

 include 'connect.php';
  session_start();

$tweet=$_POST['tweet'];
$email =$_SESSION['login_user'];
$sqlr = "INSERT INTO tweets(tweet,member_email) VALUES ('$tweet','$email')";
$rqu = mysqli_query($conn,$sqlr);

$sql= "SELECT tweet FROM tweets WHERE member_email= '$email' ";
$rq = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($rq)) {
           echo  "<p>".$row["tweet"]."</p>";
}

?>

Make sure to set exit(); at the end of tweet2.php file. Then only you will able to get response back. Moreover, You should define data in the form of data: {tweet:tweet} format. tweet Variable will go with the ajax to your php file.

$("#sendTweet").on("submit", function(e){

var tweet = $('areaTweet').val();
var update = $('#txtHint');

$.ajax({
        type: 'POST',
        url: 'tweet2.php',
        data: {tweet:tweet},  
        success:function(html){
           update.html(html);
        }
    });
});

UPDATED Instead of this var tweet = $('areaTweet').val();

use

var tweet = $('#areaTweet').val();