php - 提交表单 PHP 修改为 JQuery AJAX

标签 php jquery mysql ajax

我希望将下面的 php 表单提交转换为 JQuery Ajax 提交。我之前使用过 Ajax 来处理一些简单的请求,但我不确定如何为下面的代码从 MySQL 提交和返回数据。

下面的代码将用户输入条目提交给返回单列行的 MySql 查询。然后,While 循环查看这些行并触发另一个 mysql 查询,返回每行的用户喜欢数。

<?php

if(!empty($_POST['Message']))
{
      $userid = session_id();
      $searchStr = get_post($con,'Message');
      $aKeyword = explode(" ", $searchStr);

      $aKeyword = array_filter($aKeyword);

      $stmt = $con->prepare(
          'SELECT m.ID, m.MessageText 
          FROM MessageMain m 
          LEFT OUTER JOIN Likes l on m.ID = l.PostID 
          WHERE MessageText REGEXP ?
          GROUP BY m.ID, m.MessageText ORDER BY count(m.id) desc'
      );

      $regexString = implode('|', $aKeyword);
      $stmt->bind_param('s', $regexString);
      $stmt->execute();
      $result = $stmt->get_result();

       $rowcount=mysqli_num_rows($result);

       echo "<pre> Returned ".  $rowcount . " matches</pre>";

     if(mysqli_num_rows($result) > 0) {
        $row_count=0;
        While($row = $result->fetch_assoc()) {   
            $postid = $row['ID'];
            $row_count++;

                    // Checking user status
                    $status_query = $con->prepare("SELECT COUNT(*) AS type FROM likes WHERE userid = ? AND postid = ?");
                    $status_query->bind_param('ss',$userid,$postid);
                    $status_query->execute();
                    $status_result = $status_query->get_result();
                    $status_row = $status_result->fetch_assoc();
                    $type = $status_row['type'];

                    // Count post total likes
                    $like_query = $con->prepare("SELECT COUNT(*) AS cntLikes FROM likes WHERE postid = ?");
                    $like_query->bind_param('s',$postid);
                    $like_query->execute();
                    $like_result = $like_query->get_result();
                    $like_row = $like_result->fetch_assoc();
                    $total_likes = $like_row['cntLikes'];

?>
                    <div class="post">
                        <div class="post-text">
            <?php

            echo nl2br(htmlentities($row['MessageText'],ENT_COMPAT|ENT_IGNORE, "UTF-8") );

            ?>

             </div>
                        <div class="post-action">

                            <input type="button" value="Like" id="like_<?php echo htmlentities($postid . "_" . $userid); ?>" class="like" style="<?php if($type == 1){ echo "color: #ffa449;"; } ?>" />&nbsp;(<span id="likes_<?php echo $postid . "_" . $userid; ?>"><?php echo htmlentities($total_likes); ?></span>)&nbsp;

                        </div>
                    </div>
        <?php 
                }

    }

}

最佳答案

最简单的方法是重写 PHP 脚本以仅返回数据,这样您就可以在 JS 中使用它来构建 HTML。

我的建议是简单地创建一个数组,然后在 while 循环中将所有数据添加到该数组中,例如:

// Add the array declaration somewhere at the beginning of your script ( outside the while loop )
$likesData = array();

然后在 while 循环中:

$likesData[] = array(
  'ID' => $postid,
  'type' => $type,
  'totallikes' => $total_likes
);

然后在 while 循环之后:

// Return the array as JSON, die script to ensure no other data gets send after the json response
die( json_encode( $likesData ) );

然后在你的 JS ( jQuery ) 中执行如下操作:

// Do the AJAX request
$.post( "yourscript/url/maybephpfile.php", function( jsonResponse ) {
  // Loop over json response
  for( var key of Object.keys( jsonResponse ) ) {
    $( '.your_existing_element' ).append( `<div class="post"><div class="post-text">${jsonResponse[key].totallikes}</div></div>` );
  }
});

希望这对您有所帮助,如果您有任何疑问,请告诉我。

关于php - 提交表单 PHP 修改为 JQuery AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59239438/

相关文章:

php - 为什么要在php中使用类?

javascript - jquery ajax 响应中缺少 responseJSON

php - 如何使用 MySQL 和 PHP 安全地删除向用户显示的行?

mysql - SQL语法帮助,条件AND

php - 显示mysqli查询的单列值

php - 填充数据库的返回值

php - 供应商/autoload.php : failed to open stream

php - 登录脚本 - 计算行数或使用 COUNT ('column' )

javascript - jQuery 通过其文本从选择框获取值

javascript - 按数字处理输入字段