Ajax - unable to show posts upon submission

Whenever I submit a post, I am unable to display them and I'm not sure why it's not working. The getPosts() function works fine when I refresh the page. However, after submitting the posts, I can't seem to retrieve them. I am using a JSON fake server for the backend.

// On load
document.addEventListener('DOMContentLoaded', function () {
  getPosts();
});

// Submit post
document.querySelector('#wrapper-form').addEventListener('click', submitPost);

// Function Helpers
function submitPost(e) {
 if(e.target.dataset.role === 'submit-post') {
   http.submitPost();
   getPosts();
}

 e.preventDefault();
}

// Get posts
function getPosts() {
 http.getPosts()
   .then(response => {
     ui.populateList(response);
  })
  .catch(err => console.log(err));
}

Below are the requests:

// Get
getPosts() {
  return new Promise((resolve, reject) => {

  this.xhr.open('GET', 'http://localhost:3000/posts', true);

  this.xhr.onload(
   const response = JSON.parse(this.xhr.responseText);

    if(this.xhr.status === 200 && this.xhr.readyState === 4) {
     resolve(response);
    } else {
     reject('Some Error' + status);
    }
 );

  this.xhr.send();
 });
}

// Submit
submitPost() {
  return new Promise((resolve, reject) => {
   const data = {
    title: document.querySelector(UiSelectors.titleInput).value,
    body: document.querySelector(UiSelectors.bodyInput).value
   };

  this.xhr.open('POST', 'http://localhost:3000/posts', true);

  this.xhr.setRequestHeader('Content-type', 'application/json;charset=UTF-8');

  this.xhr.send(JSON.stringify(data));
 });
}

Answer №1

After some trial and error, I learned the following:

http.submitPost()
 .then(response => {
   getPosts();
});

I discovered that attempting to make two requests simultaneously does not work in programming. Therefore, I need to ensure that I first submit the post before trying to fetch any posts.

Initially, my approach was:

function submitPost(e) {
 if(e.target.dataset.role === 'submit-post') {
   // Unfortunately, I attempted to do two requests at once, which caused issues
   http.submitPost();
   getPosts();
}

 e.preventDefault();
}

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

Is there a way for me to detect if the user has manipulated the CSS or JavaScript in order to alter the look of my website?

Is there a way to determine if someone is utilizing script or CSS extension tools? For instance, if they have adjusted alignments, applied display: none; to multiple elements, or utilized jQuery's .hasClass to manipulate divs. ...

What steps are required to insert additional tags into select2?

I've successfully retrieved the tags from my API, but I'm facing an issue with adding new tags. Here's the code snippet I've been using: $(function(){ var user_email = localStorage.getItem('email'); var api = ...

Forwarding based on URL/Query Parameters

I'm looking to create a redirect for users based on URL or query parameters, but I'm not sure how to go about it. For example, if the URL is https://www.tamoghnak.tk/redirect?link=https://www.tamoghnak.tk/gobob, I want to redirect to /gobob. If ...

The Ajax request is not passing the values of the submit button as expected

In my current setup, I am using ajax code to send name/email/message parameters to a "messageaction.cfm" template and then display those same 3 parameters on the original submission page. The code works fine in achieving this functionality: <script ...

Implementing precise search functionality in a table with jquery datatables

Hey there, I'm attempting to implement an exact search feature in jQuery datatables. In my table, I have a column called "status" with values of either "paid" or "unpaid". Currently, when I type "unpaid", it correctly displays only the unpaid record ...

"Exploring the best way to structure an array in an ajax post

I have created a dialog using php. When the data is submitted, I use ajax to send it back to the dialog for storage without closing it. The functionality is mostly working, but the format of the posted data is not ideal. Below is the ajax code snippet: ...

Keep the multiselect dropdown list of the select component open

I am currently utilizing the Select component from material-ui-next. Overall, it functions quite smoothly. One scenario where I implement it is within a cell element of an Ag-Grid. Specifically, in this use case, I am making use of the multiselect feature ...

Retrieve the key{index} property from the .map method in React for the element that was just clicked

I am facing an issue with my code const Component = () => { const [Clicked, setClicked] = useState(false); const handleClick = (prop, e) => { console.log(prop); } return ( <div> {arrayCard.map((item, i) => { ...

What is the process for defining the host in a websocket connection?

When working on my page, I establish a websocket connection to the server using ws://127.0.0.1:5000/ws in development and ws://www.mymachine.com/ws when deployed to production. Is there a more efficient way to handle this so that I don't have to manua ...

The function of cookieParser() is causing confusion

Having an issue that I've been searching for answers to without success. When using app.use(express.cookieParser('Secret'));, how can we ensure that the 'Secret' is truly kept secret? I'm feeling a bit lost on this topic. Is ...

Next.JS: The Key to Long-Term Data Storage

How can we retrieve and maintain data during app initialization or user login so that it persists throughout the application? Currently, every time a page is refreshed, the context is cleared and attempting to use getServerSideProps results in undefined ...

Steps to attach a trigger to an UpdatePanel using a UserControl

Our Default.aspx page contains an updatepanel where we load ASCx user controls. We are currently looking to dynamically add triggers for the updatepanel from our usercontrols. Are there any methods available for achieving this? If yes, what would be the b ...

Tips for efficiently playing a WAV file in JavaScript by building an AudioBuffer

I'm having trouble playing the WAV file located at this link. The file plays fine in VLC and the details show that it is a Mono IMA WAV APDCM Audio (ms) file sampled at 24000Hz with 16 bits per sample. However, when I try to play the file by embeddin ...

The timing of the JavaScript dialog with the AJAX call is off-kilter

Encountering an issue with a JavaScript script designed to showcase a JQUERY dialog box based on a C# ViewModel. Within a repeater, there is an ASP drop-down menu displaying 'Registration Date' details. The objective is for the JavaScript dialog ...

Troubleshooting the issue of data retrieval failure in asp.net mvc controller using jquery.post()

I am currently working on an ASP.NET MVC web application that is written in VB.NET. My goal is to send data using jQuery to my controller. Below is the code for my controller: <HttpPost()> Function GetData(p As DataManager) As JsonResult ...

Are you experiencing a clash among various JS files in your WordPress installation?

I'm in a bit of a bind here. I've been tasked with working on a Wordpress website for a friend, using a free theme that he provided. Naturally, he wants some modifications made, so I've been editing the theme accordingly. The theme relies on ...

When the function is executed, the error message "obtaining ID

As I attempt to remove items from a group and automatically delete the group if there are no items left, I encounter an error in Vue indicating that 'id' is not defined. This seems puzzling to me because it should have already completed the opera ...

What is the best way to create a reliable and distinct identifier in React while using server-side rendering (

Currently, I am utilizing SSR within Next.js. My goal is to create a unique ID within a component in order to use it as an attribute for a DOM element's id. Since this component might be utilized multiple times on a single page, the ID needs to be dis ...

Assigning a value to a select2 option based on data retrieved from a database

Is there a way to edit this form so that the select2 option can display selected data returned from the database and also be changeable? I've attempted to make these changes but am still unable to display the selected data. Thank you for any help :) ...

The parameters used in the json.parse function in javascript may be difficult to interpret

Currently, I am examining a JavaScript file on this website. It contains the following code: let source = fs.readFileSync("contracts.json"); let contracts = JSON.parse(source)["contracts"]; I'm curious about what exactly the JSON.parse function is d ...