Send POST request to REST API via javascript

28,361

Solution 1

The problem with your code is that you are not "intercepting" the submit event of your form so it will execute the default behavior which is POST to itself (since it doesn't have an instruction that tells it where to go). Unless you can have a chance to stop this default behavior, the form will perform this action.

To intercept the form's submit event you have to tell the browser to watch out of this event and execute a custom function instead of using an event listener like below:

<script>

document.getElementById('whatever-form-id')
  .addEventListener('submit', check);

function check(e) {
  e.preventDefault();
  // and now anything else you want to do.
}

</script>

This will prevent your form from posting and it will execute your function instead.

Solution 2

1) Your validation function always returns true
2) When you use fetch..then, its promises can be executed later than return statement

So your form will be refresh again and again. You should return false, and manually submit the form with JavaScript when you get an onSuccess response.

<script>
    function check(event) {
        document.getElementById('message').innerHTML = "checking";

        const url = "https://localhost:8080/login";
        const data = {
            'email' : document.getElementById('email').value,
            'password' : document.getElementById('new_password').value
        };
        const other_params = {
            headers : { "content-type" : "application/json; charset=UTF-8" },
            body : data,
            method : "POST",
            mode : "cors"
        };

        fetch(url, other_params)
            .then(function(response) {
                if (response.ok) {
                    alert(response.json());
                } else {
                    throw new Error("Could not reach the API: " + response.statusText);
                }
            }).then(function(data) {
                document.getElementById("message").innerHTML = data.encoded;
            }).catch(function(error) {
                document.getElementById("message").innerHTML = error.message;
            });
        return false;
    }
</script>

<form method="POST" onsubmit="return check();">{% csrf_token %}
    <p><b>Login</b></p>
    <input type="email" id = "email" name="email" placeholder="Email" required></input>
    <input type="password" name="password" placeholder="Password" id='new_password' ></input>
    <span id='message'>{{msg}}</span>
    <button type="submit" name="Submit"><b>Submit</b></button>
</form>

Update:

Page not refreshed, error message displayed: enter image description here

Share:
28,361
Pratibha
Author by

Pratibha

Sr. Python Developer with Django development experience

Updated on December 07, 2020

Comments

  • Pratibha
    Pratibha over 3 years

    First, I read somewhere that we should not use XMLHttpRequest.

    Second, I am a newbie in Javascript.

    Third, I created a webpage to submit email and password.

    <form method="POST" onsubmit="return check();">{% csrf_token %}
        <p><b>Login</b></p>
        <input type="email" name="email" placeholder="Email" required></input>
        <input type="password" name="password" placeholder="Password" id='new_password' ></input>
        <span id='message'>{{msg}}</span>
        <button type="submit" onclick="check()" name="Submit"><b>Submit</b></button>
    </form>
    

    My check function is

    function check() {        
        document.getElementById('message').innerHTML = "checking";
        const url = "https://<hostname/login";
        const data = {
            'email' : document.getElementById('email').value,
            'password' : document.getElementById('password').value
        };
    
        const other_params = {
            headers : { "content-type" : "application/json; charset=UTF-8" },
            body : data,
            method : "POST",
            mode : "cors"
        };
    
        fetch(url, other_params)
            .then(function(response) {
                if (response.ok) {
                    return response.json();
                } else {
                    throw new Error("Could not reach the API: " + response.statusText);
                }
            }).then(function(data) {
                document.getElementById("message").innerHTML = data.encoded;
            }).catch(function(error) {
                document.getElementById("message").innerHTML = error.message;
            });
        return true;
    }
    

    This code is not working and just redirects me to the same page again and again.

    Please help me understand what am I doing wrong.

  • Pratibha
    Pratibha over 5 years
    I want to show the response message that API is sending. it is a string.
  • Pratibha
    Pratibha over 5 years
    how to do that?
  • Pratibha
    Pratibha over 5 years
    it is just showing "checking" message, not the response from API. API is returning a JSON.
  • Mayank Shekhar
    Mayank Shekhar over 5 years
    @pratibha remove the return statement form check function
  • mrgrechkinn
    mrgrechkinn over 5 years
    @pratibha Can you share more information? What not working? What do you expect?
  • Pratibha
    Pratibha over 5 years
    It is just refreshing the page, it is not calling the API.
  • James Chen
    James Chen over 5 years
    what isn't working exactly? the page still refeshing from postback? or the returned message is not showing where you want it to?
  • Rajender Verma
    Rajender Verma over 5 years
    @pratibha, I've only done fixing for running ajax request, i cannot work more on it, you need to figure it out by yourself and good for your learning, still I can show you the ajax post request in browser inspector: prntscr.com/la8ppc
  • mrgrechkinn
    mrgrechkinn over 5 years
    @pratibha No, it's shouldn't. Please check your sources and try to add infromation from browser debugger
  • Pratibha
    Pratibha over 5 years
    can you please share your html file?
  • Pratibha
    Pratibha over 5 years
    It is stuck at "checking" message
  • Pratibha
    Pratibha over 5 years
    and nothing in browser debugger
  • Pratibha
    Pratibha over 5 years
    and nothing in browser debugger
  • Pratibha
    Pratibha over 5 years
    @Rajendra I understand, just now i put actual hostname there but it is not working. API is not getting the hit
  • Pratibha
    Pratibha over 5 years
    can you please share the html file
  • mrgrechkinn
    mrgrechkinn over 5 years