The Mustache feature is bringing back old information alongside fresh updates

Currently, I am utilizing mustache.js to display JSON data in a template. However, I have encountered an issue where Mustache is appending previous response data along with the new one when I make a $.ajax post request. How can I prevent Mustache from retaining previous data and only return the latest response?

Script

$.ajax({ type: 'POST',
         url: 'actions/addpost.php',
         data: {wallid: wallid, postmessage: postmessage, files: files},
         dataType: 'json',
         encode: true
       })
       .done(function (data) {
              var template = $('#template').html();
              Mustache.parse(template);   // optional, speeds up future uses
              var rendered = Mustache.render(template, data);
              $('#newpost').prepend(rendered);
       });

Template

<script id="template" type="x-tmpl-mustache">
      <div class="panel panel-white">
          <div class="panel-heading">
              <label>UserID: {{ userid }}</label>
              <span class="help-block">{{ date_created }}</span>
          </div>
          <div class="panel-body">
             <div class="well-white well-sm">{{ post_text }}</div>
          </div>
          <div class="panel-footer">
             <div id="attachmentlist">
               {{ #attachments }}
                   <p>{{ filename }} ({{ filetype }})</p>
               {{ /attachments }}
             </div>
             <br>
             <div class="comment-textarea">
                <form name="commentform">
                    <div class="comment-box media">
                       <a id="comment-box-a" class="pull-left" href="#">
                          <img class="media-object" src="source/images/nophoto.png" alt="...">
                       </a>
                       <div class="media-body form-group">
                          <textarea id="comment-box-msg" name="postMessage" class="form-control" row="1" placeholder="Write a comment..."></textarea>
                       </div>
                       <button id="comment-box-btn-post" class="btn btn-primary btn-sm pull-right" aria-hidden="true" type="button">Δημοσίευση</button>
                   </div>
                </form>
             </div>
          </div>
      </div>
 </script>

Answer №1

Why not try using this instead:

$('#newpost').html(rendered);

It might be better than using .prepend because it adds the new HTML before the old one, rather than replacing it.

UPDATE : Following a discussion, it seems that the issue may not be with Mustache after all, but possibly due to multiple PHP calls. Mustache appears to be functioning correctly in this case.

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

I struggle to format a classic HTML form dropdown menu that is populated using JavaScript

Hey everyone, I'm having an issue with styling a drop down menu that is populated by JavaScript. I've tried different things but nothing seems to be working. Any suggestions on how I can style the elements in the drop down? <form action="" me ...

When attempting to call Firebase Functions, ensure that Access-Control-Allow-Origin is set up correctly

Although it may seem straightforward, I am confused about how Firebase's functions are supposed to work. Is the main purpose of Firebase functions to enable me to execute functions on the server-side by making calls from client-side code? Whenever I t ...

Python: Adding an Element to a Dictionary

I'm struggling with merging a JSON object into an existing one. Despite adding the new object first in my code, it still appears at the bottom of the JSON structure. Here's an example of the current JSON structure... { "Header": { " ...

Feature to insert a fresh row into SAPUI5 table

I've been attempting to insert new rows into a SAPUI5 table with the click of a button. Despite watching numerous tutorials online, I haven't found one that fits my specific situation. Currently, the JSON data is loaded via a mock server with th ...

Error message: "Root resolution error encountered". Need assistance in granting watchman access?

After setting up a react-native starter project, I was prompted to allow watchman access to my system's files. Unfortunately, I declined and now whenever I try to run the folder, I encounter the following error: Error: unable to resolve root /Users/ck ...

The Node.js JSON string displays as "[object Object]" in the output

Front End // js / jquery var content = { info : 'this is info', extra : 'more info' } $.ajax({ type: 'POST', url: '/tosave', data: content }); Node // app.js app.post('/tosave', funct ...

I am currently working on creating a shopping cart that includes a delete button for removing items with just a click

I am currently working on developing a shopping cart feature that includes a remove button to delete items when clicked. I have achieved this using the filter method. However, I am facing an issue where after deleting an item and then adding it back, the ...

The Electronjs application encountered an error while loading with the message "ReferenceError: require is not defined."

Having trouble with an electron application as I encounter an error when running npm start: $ npm start > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="483c2d3b3c087966786678">[email protected]</a> start C:& ...

The link containing special characters like % cannot access the api

I am facing an issue with retrieving a signUrl from S3. When I make the call with special characters like %, my code does not parse it correctly and I receive a 404 not found error. Here is the ajax request I am using: My API setup: app.get('/websi ...

Runtime.UnhandledPromiseRejection - Oops! Looks like we're trying to read properties of something that doesn't exist (specifically 'headers')

I'm facing an unexpected error that has left me puzzled. Let me walk you through what I am trying to accomplish: The task at hand involves fetching data from one API and then transmitting it to another. This process is executed as a background-funct ...

Tips for preventing a page refresh using HTML, JQuery, AJAX, and PHP

I need assistance with transferring the value of a selected radio button to a PHP session variable using Javascript/AJAX. Everything seems to be working fine, except that the page refreshes each time. Is there a way to prevent this from happening? Below i ...

Can you recommend a technology similar to WebSockets that does not rely on a framework like Node.js?

I am currently developing a basic betting game and I want to enhance the user experience by updating values in real-time. The challenge is that most of my application is written in jQuery and JavaScript, with a MySQL database set up by a different develo ...

"Creating varying lengths of time with useSpring: A Step-by-Step Guide

Is there a way for my component to have an animation that fully displays in 0.3s when my mouse enters, but disappears in 0.1s when my mouse leaves? Currently, with useSpring, I can only define one duration for both scenarios. How can I set different dura ...

Exposing a Hidden Division with a Link via jQuery

I currently have a jQuery Panel set up to open when clicking a button. Now, I am looking to add a second link at the bottom of the page that will also open the same panel. Can anyone provide guidance on how to accomplish this? You can view my JSFiddle a ...

Steps to trigger a JsonProcessingException with Jackson

Here's an interesting query - I'm looking to enhance the test coverage of my code and have encountered a challenge. Despite coding against a JsonProcessingException, I am unable to create a payload that triggers this exception. It seems that Jack ...

Convert the PHP datetime and timezone function to a JavaScript function

I have a helpful function in my solution that I'd like to share: public static function formatTime($time, $timezone) { $timezone = new \DateTimeZone($timezone); $time = $time->setTimezone($timezone); return \Locale::getDefaul ...

Mastering the art of grouping by a key and generating sub-objects from a plain array of key-value pairs in JavaScript ES5 without relying on third-party libraries

My dataset consists of an array of objects, each containing 4 keys: [ { "team": "USA", "team_profile_id": "10", "player": "Captain America", "player_id": "10X1" }, { "team": "USA", "team_profile_id": "10", "player": "The ...

The serialize() method in Ajax is not capturing all the data fields from an HTML form

Attempting to use the jQuery get() method to send form data from my website, I encountered an issue where only a few of the field data were actually transmitted to the server upon form submission. The Form: <form class="form-horizontal" id="addpost" ...

What can I do to resolve the issue of my Navigation Bar being blocked by a Javascript map?

My navbar creates a dropdown menu when I hover over it, but the map generated with the script tag blocks it. Here is the current setup: // JavaScript Document //This will make the navigation bar responsive. function myFunction() { var x = document.ge ...

Attempting to deserialize serialized data from Django using JSON.parse

I need assistance with some client-side tasks using Javascript. In my view, I serialize a Queryset from my models into JSON and pass it to the template. data = serializers.serialize("json", Profile.objects.filter(user_id=self.request.user)) This results ...