RoyBarOn
RoyBarOn

Reputation: 987

How to prevent from json-server to reload page after post?

I'm using Json Server for mocking API requests and i'm experiencing an annoying behavior , each post that i'm doing causes the page to reload... i've read their api documentation but didn't came up with anything. I'm using a simple jquery ajax request that looks like this :

$.ajax({
url: 'http://localhost:3000/list',
type: 'post',
data: itemObj,

dataType: 'json',

success: function (itemObj) {
 
  todoListArr.push(itemObj);
  createMarkup(); 
  $(this).val(''); // clear input
  return false;

  }
});

I've tried e.preventDefault() but it's nothing to do with the ajax call - it's the json-server that causes it... the command that i'm using for running the server is : npx json-server --watch db.json tried also npx json-server

Upvotes: 1

Views: 2577

Answers (3)

Val M
Val M

Reputation: 617

I suffered the same problem using VSCode with LiveServer extension and JSON server.

In my case, i had a form sending a post with vanilla AJAX, and every time I submitted the form, the page became reloaded.

Then, I tried to avoid this returning false on the callback method. ie:

<form id="forma" onsubmit="postAlumno(); return false;" method="POST">

But it wasn´t enough :(

In a casual way, i discovered that if you run a JSONserver process from other VScode Window the auto reloading stops!

Other solution, maybe open the page locally -if possible-, without any server.

Upvotes: 0

Michael Adel
Michael Adel

Reputation: 51

I had the same issue, if your using VS code try not use the live server extension(disable it), and it should work fine.

Upvotes: 2

render4me
render4me

Reputation: 23

It may be because of live server extension or something like that refresh html pages if you're using for example vs code live server. Another possibility is if you're using a form and if something inside the form or outside the form is listening to the same submit event that may cause event bubbling so you may try e.stopPropagation(); as well.

Upvotes: 0

Related Questions