skip to Main Content

I’m looking to convert the below php form submission to a JQuery Ajax submission. I have used Ajax with some simple requests before, but I’m not sure how to submit and return data from MySQL for the below code.

The code below submits the user input entry to a MySql query returning single columns rows. A While loop then looks at these rows and fires another mysql query returning the number of user likes per row.

<?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 
                }

    }

}

2

Answers


  1. You need to send from a form in ajax when clicking the button

    $.ajax({
      method: "POST",
      url: "some.php",
      data: { message: "message text" }
    })
      .done(function( msg ) {
        // process your data back here
        alert( "Data Saved: " + msg );
      });
    

    Examples here. https://api.jquery.com/jquery.ajax/
    $.post is shortcut of ajax, method post.

    I think would be better to split the files and not do everything in one.
    form.php -> ajax request -> backend.php -> data retrieved with ajax back to form.php

    Login or Signup to reply.
  2. Easiest would be to rewrite you PHP script to return only the data so you can use this in your JS to build the HTML.

    What I would suggest is simply creating a array and adding all your data to this array in you while loop, so for example:

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

    Then inside your while loop:

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

    Then after your while loop:

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

    Then in your JS ( jQuery ) do something like this:

    // 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>` );
      }
    });
    

    Hope this helps you out, if you have any questions let me know.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search