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;"; } ?>" /> (<span id="likes_<?php echo $postid . "_" . $userid; ?>"><?php echo htmlentities($total_likes); ?></span>)
</div>
</div>
<?php
}
}
}
2
Answers
You need to send from a form in ajax when clicking the button
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
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:
Then inside your while loop:
Then after your while loop:
Then in your JS ( jQuery ) do something like this:
Hope this helps you out, if you have any questions let me know.