Cannot seem to get my AJAX code working correctly to show comments

Having some trouble with my comment system code. The PHP part is working fine, comments are being inserted into the table without any issues. However, I am struggling with the Ajax part. The comments are not being displayed unless the page is reloaded. Can someone help me fix my Ajax code?

<?php
if(isset($_POST['content'])) {
$comment=strip_tags($_POST['content']);
$com = $db->prepare("INSERT INTO comments (comment,userto, userfrom, blog) VALUES (:comment, :userto, :userfrom, :blog)");
$com->execute(array(':comment'=>$comment,':userto'=>$userid,':userfrom'=>$uid,':blog'=>$blogId));   
}
?>


  <div class='db'>
  <table>
  <tr>
  <td>
  <img src='<?php echo $tar['profile_pic']; ?>' style='width:40px;height:40px;'/>
  </td>
  <td>
  <a href='<?php echo $tar['username']; ?>'><?php echo $tar['first_name'].' '.$tar['last_name']; ?></a>
  <p><?php echo $tar['comment']; ?></p>
  </td> 
  <td>
   <a href='#' id='<?php echo $tar['id']; ?>' class='delcomment' style='color:#555555;text-decoration:none;' title='Delete'>X</a>
   </td>
   </tr>
   </table>
        </div>

<script type="text/javascript" >
$(function() {
  $(".comment_button").click(function() {

    var test = $("#content").val();
    var dataString = 'content=' + test;

    if (test == '') {
      alert("Please Enter Some Text");
    } else {

      $.ajax({
        type: "POST",
        url: "",
        data: dataString,
        cache: false,
        success: function(html) {
          $(".db").show(html);
        }
      });
    }
    return false;
  });
});
</script>


<form method='post' name='form' action='' class='commentbox'>
<textarea cols='30' rows='2' name='content' id='content'></textarea><br />
<input type='submit' value='Comment' name='submit'class='comment_button'/>
</form>

Answer №1

Avoid using the variable dataString and update the $.ajax() function as shown below:

var test = $("#content").val();

$.ajax({
    type: "POST",
    url: "",
    data: {
        content: test;
    },
    success: function(response) {
      $(".db").append(response);
    }
  });

To prevent page refresh, modify the following line:

$(".comment_button").click(function(event) {
    event.preventDefault();

Alternatively, change the attribute type="submit" of your button to type="button", like this:

<button type='button' name='submit' class='comment_button'>Comment</button>

This information should be useful for you...

Answer №2

Give this a try and make sure to include the jQuery library in your webpage.

HTML CODE

<script type="text/javascript">
    $(function() {
        $(".comment_button").click(function() {
            var test = $("#content").val();
            var comment = test;

            if (test == '') {
                alert("Please Enter Some Text");
            } else {

                $.ajax({
                    type: "POST",
                    url: "process.php",
                    data: { content : comment },
                    cache: false,
                    success: function(html) {
                        $("#db").append(html);
                    }
                });

            }
            return false;
        });
    });
</script>

    <div id="db">
         <!--Returned comment will appear here-->
    </div>

    <form method='post' name='form' action='process.php' class='commentbox'>
        <textarea cols='30' rows='2' name='content' id='content'></textarea><br />
        <input type='submit' value='Comment' name='submit' class='comment_button'/>
    </form>

PHP PAGE
process.php

 <?php

    if(isset($_POST['content'])) {
        $comment=strip_tags($_POST['content']);
        $com = $db->prepare("INSERT INTO comments (comment, userto, userfrom, blog) VALUES (:comment, :userto, :userfrom, :blog)");
        $com->execute(array(':comment'=>$comment,':userto'=>$userid,':userfrom'=>$uid,':blog'=>$blogId));   
    }
?>
<table>
  <tr>
      <td>
          <img src='<?php echo $tar['profile_pic']; ?>' style='width:40px;height:40px;'/>
      </td>
      <td>
          <a href='<?php echo $tar['username']; ?>'><?php echo $tar['first_name'].' '.$tar['last_name']; ?></a>
          <p><?php echo $tar['comment']; ?></p>
      </td> 
      <td>
          <a href='#' id='<?php echo $tar['id']; ?>' class='delcomment' style='color:#555555;text-decoration:none;' title='Delete'>X</a>
      </td>
  </tr>
</table>

Answer №3

Utilize

$(".update").prepend(content);

In case you already possess prior feedback such as:

<div class = "update">
  Feedback 1
  Feedback 2
  ...
</div>

.prepend shall insert additional HTML content at the beginning of the existing tag.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Continuously iterate through collection as it expands over time

As I cycle through an array, I'm performing additional actions that could potentially prolong the loop if new elements are added to the array during iteration. (I understand it's not recommended to modify the object being iterated over, but pleas ...

The Django POST request is rejecting due to a missing or incorrect CSRF token, despite having included the token in the form

I'm encountering a 403 response when making a POST request despite including csrf_token in the data for an AJAX request. I made sure that csrf_token is not empty before sending the request, so everything seems correct. What could be causing this error ...

Kendo UI Web - MultiSelect: choosing an option multiple times

Currently, I am encountering an issue with the Kendo UI MultiSelect widget when trying to select an option multiple times. An example of this is shown in the image below where I want to choose Schindler's List again after selecting The Dark Knight. Ho ...

Upgrading outdated pagination mysql_query PHP code to PDO

Currently in the process of transitioning to PDO for database management, I have implemented a news section on my website. The database connection is located within the header of the site. While using the following code for pagination, I am struggling to ...

Potential Cross-Origin Resource Sharing (CORS) problem arises when integrating Node Express with an Ionic

Currently, I have an Ionic application that communicates with a Node Express application using Restangular. Everything works smoothly when the Node Express server is configured to use HTTP. On the Ionic app side: RestangularProvider.setBaseUrl('http ...

Transferring data from AJAX to PHP class methods

Q. Is it feasible to transfer data from ajax to a specific php class with functions? For instance, verifying a username on the registration form to check if the user already exists. This form is straightforward and will gather a username input along with ...

Can someone help me figure out how to increase the values of two specific attributes within a class?

Currently facing a challenge with adjusting the number of likes and comments using increment for properties 'numberOfLikes' and 'comments'. Unsure whether to utilize a for loop or just the increment operator. Still new to coding, so apo ...

Which is better for privacy: underscored prototype properties or encapsulated variables?

There's something that's been on my mind lately - it seems like people are aware of something that I'm not. Let's take a look at an example in FOSS (simplified below)... When creating a class in JavaScript, I personally prefer Crockford ...

Missing data: Node JS fails to recognize req.body

I've looked through various posts and I'm feeling quite lost with this issue. When I run console.log(req), the output is as follows: ServerResponse { ... req: IncomingMessage { ... url: '/my-endpoint', method: &a ...

Implement a dialog on top of a current web page, achieve php-ajax query result, and enhance with

My website features 'dynamic' content, where 'static' nav-buttons replace specific div contents upon clicking. While I am able to retrieve my php/ajax results in a dialog box, I am struggling with placing this dialog above my current p ...

Retrieve data from a URL using jQuery's .get method and iterate over each element using

After successfully retrieving the HTML using the jQuery get function and displaying it, I now have a question. How can I use the .each jQuery function to iterate through each div contained within the retrieved data? Specifically, I want to target a single ...

Important notice: It is not possible to assign refs to function components. Any attempt to do so will result in failure. If you intended to assign a ref, consider

My console is showing a warning when I use the nextJs Link component. Can someone assist me in resolving this issue and providing an explanation? Here is the message from the console: https://i.stack.imgur.com/jY4FA.png Below is a snippet of my code: im ...

After clicking on the checkbox, req.body.task becomes undefined

Whenever I click on the checkbox, the value of req.body.task returns as undefined. <input type="checkbox" name="task" autocomplete="off" checked="" onchange="onToDochange({{id}})"> This function is triggered by a change event on the checkbox and it ...

Is a cron job the best solution for managing a job queue?

I am currently developing a small application that involves the uploading of images via email. The application is being created using PHP (without a framework), with MySQL and S3 integration. At present, my setup involves storing emails on a POP3 account. ...

PHP Commenting System with Hierarchical Structure

I am looking to create a commenting system similar to Discus or Reddit. In my comment database, I have a field called "id_answer" which is set to 0 by default. When a user replies to another comment, this field will be populated with the "id" of the parent ...

Tips for verifying if the input in a Material UI textfield is an <iframe> tag

In my ReactJS code, I am utilizing the TextField component from material-ui. I need to verify if the user input is an iframe. How can I achieve this? Currently, I am attempting to use window.parent.frames.length > 0; to determine if the page contains a ...

The jQuery countdown plugin is yielding some unexpected outcomes

Feeling a bit rushed for time, so I thought I'd ask here. The date is currently 2012-10-06 and I'm attempting to implement a jQuery plugin called "jquery.countdown.js". It seems pretty straightforward. Can anyone point out what I might be doing i ...

Confused about having to use window.variableName in my code and not understanding the reason

Working on a web app with JS, Angular, and Meteor that integrates the Youtube API has been quite challenging. In one of my controllers, I initialized the youtube player object in the constructor following the necessary steps outlined by the Youtube API. Ho ...

Using jQuery each, the output is an undefined Object or HTMLElement

Using jQuery's each/getJSON to iterate through a data.json file, collect and format the data, and display it on the page within the #output div. The functionality is working correctly, except for the unexpected addition of [object HTMLElement] that a ...

"Empty array conundrum in Node.js: A query on asynchronous data

I need assistance with making multiple API calls and adding the results to an array before returning it. The issue I am facing is that the result array is empty, likely due to the async nature of the function. Any help or suggestions would be greatly appre ...