rahulg
rahulg

Reputation: 93

XMLHttpRequest not working on button click

I am developing this chrome extension and I have the backend on Django. I am doing an XMLHttpRequest POST to login the user. When I call the function on 'DOMContentLoaded', it works. However, when I do it on a button click, it doesn't work.

Here is the javascript code:

function login(){
    //alert("hello");
    var http = new XMLHttpRequest();
    var url = "someURL";
    //var email = document.getElementById("email").value;
    //var password = document.getElementById("password").value;
    var params = "email=someEmail&password=Password";
    //alert(params);
    //var params = "email=" + email + "&password=" + password;
    http.open("POST", url, true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.setRequestHeader("Content-length", params.length);
    http.setRequestHeader("Connection", "close");
    http.onreadystatechange = function() {
        //alert(http.responseText);
        if(http.readyState == 4 && http.status == 200) {
            alert(http.responseText);
        }
    }
    http.send(params);
}

Now, when I do this:

document.addEventListener('DOMContentLoaded', function(){
    login();
});

It works. On clicking the extension, I get a success message.

However, when I do this:

document.addEventListener('DOMContentLoaded', function(){
    document.getElementById("btn").addEventListener("click", login);
});

It doesn't work.

Here is the popup.html:

<html>
    <head>
        <script src="popup.js"></script>
    </head>
    <body>
        <div id="content">
            <p id="demo"></p>
            <form>
                <input type="email" id="email">
                <input type="password" id="password">
                <button id="btn">Login</button>
            </form>
        </div>
    </body>
</html>

and this is the manifest.json

{
  "manifest_version": 2,
  "name": "payback",
  "description": "payback.",
  "version": "1.0",
  "content_scripts": [
    {
      "matches": ["http://*/", "https://*/"],
      "js": ["popup.js"]
    }
  ],
  "browser_action": {
    "default_popup":"popup.html"
  },
  "permissions": [
    "http://*/", "https://*/"
  ]
}

Upvotes: 1

Views: 5730

Answers (2)

Manraj Singh
Manraj Singh

Reputation: 123

Remove lines

http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. Read this for more information.

Also use

<input type="button" id="btn" value="Login"/>

instead of

<button id="btn">Login</button>

because button will submit form itself.

Upvotes: 4

devnull69
devnull69

Reputation: 16544

By default, a click on a <button> will submit the form (because the default type is submit). Try this

<button id="btn" type="button">Login</button>

Upvotes: 2

Related Questions