dongyin0628
dongyin0628
2016-06-25 04:46

提交表单时如何将值传递到同一页面? 使用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 } ?


?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

4条回答

  • doudeng5764 doudeng5764 5年前

    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');
    
    点赞 评论 复制链接分享
  • dongtaotao19830418 dongtaotao19830418 5年前

    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();

    点赞 评论 复制链接分享
  • dongrou2920 dongrou2920 5年前

    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>";
    }
    
    ?>
    
    点赞 评论 复制链接分享
  • doouzlrvb01417498 doouzlrvb01417498 5年前

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

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

    点赞 评论 复制链接分享

为你推荐