2

im trying to achieve something pretty simple, i just wanna post the form to itself without a refresh, however i require it to post the data from the form as it is captured by the controller. im getting the data in the back end i just need the form to post successfully without a refresh and then show and hide certain things. Also, i get this error

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

i presume this is why im not reaching my conditional

const wrappers = document.querySelectorAll('.form-wrapper');

if (wrappers) {
wrappers.forEach(function(el){
    const form = el.querySelector('.submit-form');
    let currentURL = window.location.href;
    const output = el.nextElementSibling;

    form.addEventListener('submit', function(e){
        const data = new FormData(form);
        fetch(`${currentURL}`, {
            credentials: 'include',
            method: 'POST',
            body: data,
        })
        .then((res) => res.json())
        .then((res) => {
            if (res.success) {
                console.log('submitted');
                output.classList.remove('none');
                form.classList.add('none');
            }
            else if (res.error) {
                console.log('Error: ' + res.error); 
            }
        });
        e.preventDefault();
    },false);
});
}

1 Answer 1

2

Use preventDefault from the event object towards the beginning of your block:

form.addEventListener('submit', function(e) {
  e.preventDefault();
  ...
}

In the event that your POST request wasn't successful, supply a catch block:

fetch(`${currentURL}`, {
  credentials: 'include',
  method: 'POST',
  body: data,
})
.catch(err => console.log(err));
Sign up to request clarification or add additional context in comments.

12 Comments

i need to check if its successful or not. if the post is good then show a thank you message etc i cant check with just preventDefault()
If the POST request wasn't successful that's where a catch block comes into play. Reload your location in there.
could you elaborate further or point me to a resource. i am still a junior in the js world. can you catch a success?
First things first. Are you able to get a successful response from what you have now?
with the code i have now. no i get an error. Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.