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

After successfully sending a GET request to the API, the Next.js 13.4.3 website still does not reflect new posts added on the hosting platform

I am currently using Next.js version 13.4.3 in my app directory to create a blog site. However, I am facing an issue. When I run npm run build locally on my computer and then start with npm run start, the new posts are displayed normally after adding them ...

Eliminate duplicate time slots in Laravel and Vuejs

Currently, I am delving into laravel(5.2) and vuejs as a newcomer to both frameworks. My goal is to utilize vuejs to eliminate redundant time slots. In my blade file, the code looks like this: <div class="form-group"> <label for="form-fi ...

Guide to setting the first tab as the default tab using Thymeleaf, Css, and Bootstrap

I am currently working on a project where I need to dynamically create tabs based on a list retrieved from my Spring backend using Thymleaf and Bootstrap. While I have managed to successfully create the tabs and content, I am facing an issue where the fi ...

Skipping is a common issue encountered when utilizing Bootstrap's Affix feature

I'm trying to implement Bootstraps Affix feature in a sticky subnav. <div class="container" data-spy="affix" data-offset-top="417" id="subnav"> I've adjusted the offset to ensure there's no "skip" or "jump" when the subnav sticks. Ho ...

Unable to establish a connection with the docker container

I have developed a server-api application. When running the app on my localhost, only two simple commands are needed to get it up and running: npm install npm start With just these commands, the app runs perfectly on port 3000. Now, I am trying to dock ...

Tips for fixing an error encountered when running a react native project for the first time

I am encountering some errors while attempting to run this project for the first time and I am unable to resolve them. Below is the content of the package.json file: { "scripts": { "start": "expo start", "andro ...

Using Javascript to extract information from the div element

Within my HTML code, I have a total of 4 <div> tags and a corresponding <a> tag for each of these <div> tags. Inside each div tag, there are 2 span tags and an additional a tag. Upon clicking the a tag, I aim to extract the product name ...

Is your Bootstrap input displaying the has-error class with a glyphicon, but the alignment is not vertically centered?

What is the reason for the misalignment of glyphicon-warning-sign form-control-feedback vertically in the code below after applying font-size: 20px; to the label? <div class="container"> <div class="content align-left contact"> ...

Dynamically delete a property from a JSON object

I am currently working on a task that involves removing properties from a JSON object. I need to create a system where I can specify an array of locations from which the fields should be redacted. The JSON request I am dealing with looks like this: { "nam ...

Encountering an error when setting up a React-TypeScript ContextAPI

I am currently attempting to understand and replicate the functionality of a specific package found at: https://github.com/AlexSegen/react-shopping-cart Working within a React-Typescript project, I have encountered challenges when creating the ProductCont ...

The text color remains the same even after the method has returned a value

I have a vuex query that returns a list of books. I want to display each book with a specific color based on its status. I tried using a method to determine the color name for each book and bind it to the v-icon, but it's not working as expected - no ...

Is there a way to track when the Angular DTOptionsBuilder ajax call is complete and trigger a callback function?

Working with angular datatables, I have the following code: beforeSend:

success callback causes the table on the page not to populate with the data. How can I implement a callback that triggers once the ajax is done without interfering with the nor ...

Wait for a reply from one GET request before initiating the next one in node

When working with node, I am making two consecutive calls to an API. My goal is to ensure that the first GET request has completed before triggering the second one, using data from the response of the first call. To achieve this, I have experimented with ...

Having trouble with Autocomplete not entering cities into the form?

While experimenting with Google's API, I have encountered confusion regarding why cities like Staten Island, Brooklyn, Queens, and various others are not being placed into the form like other cities. According to Google's API, "locality" is suppo ...

Python is experiencing difficulties with copying xpath elements

I attempted to utilize some Python code to access Twitter and retrieve the "Happening now" text. Unfortunately, it was unsuccessful. import webbrowser print("Visiting Twitter.com...") webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/c ...

The div inside an iframe is not displaying the desired background color as intended from the parent page

The code snippet below is included in the <head> section of the main page: <script type="text/javascript"> $(document).ready(function () { $('#innerframe').load(function () { $(this).contents().find($(".TitleB ...

Styling the button in jQuery to switch between disabled and enabled

I'm currently working on creating a disabled/enable button style using jQuery. You can check out my demonstration page on Codepen for reference. In the demo, you'll notice a blue submit button. When you input text into the field, the button bec ...

Node.js exporting fails due to an undefined variable

When attempting to export variables in Node.js, I keep receiving an undefined error. I'm not sure what the issue is, can anyone provide assistance or suggestions? Here is a snippet from index.js: var test = 10; module.exports.test = test; And here i ...

One of the challenges faced with using AngularJS is that it can often

I have a piece of code that is functioning correctly: angular.module('foo', []).config( function($locationProvider) { $locationProvider.html5Mode(true); } ); However, when the code is minified, it gets compressed and looks like this: a ...

Looking to dynamically update label text when clicking a button. ASP pages utilizing C# for backend functionality

Currently, I am working on a web application that utilizes ASP pages and has a C# backend. Within this application, there is a button that initiates a lengthy method. This method involves calling about 20 different functions, which encompass tasks such as ...