Advertisement
Guest User

Untitled

a guest
Oct 25th, 2014
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. function loginAjax(event){
  3.     var username = document.getElementById("username").value; // Get the username from the form
  4.     var password = document.getElementById("password").value; // Get the password from the form
  5.  
  6.     // Make a URL-encoded string for passing POST data:
  7.     var dataString = "username=" + encodeURIComponent(username) + "&password=" + encodeURIComponent(password);
  8.  
  9.     var xmlHttp = new XMLHttpRequest(); // Initialize our XMLHttpRequest instance
  10.     xmlHttp.open("POST", "login_ajax.php", true); // Starting a POST request (NEVER send passwords as GET variables!!!)
  11.     xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // It's easy to forget this line for POST requests
  12.     xmlHttp.addEventListener("load", function(event){
  13.         console.log(event.target.responseText);
  14.         var jsonData = JSON.parse(event.target.responseText); // parse the JSON into a JavaScript object
  15.         console.log(jsonData);
  16.         if(jsonData.success){  // in PHP, this was the "success" key in the associative array; in JavaScript, it's the .success property of jsonData
  17.             alert("You've been Logged In!");
  18.         }else{
  19.             alert("You were not logged in.  "+jsonData.message);
  20.         }
  21.     }, false); // Bind the callback to the load event
  22.     xmlHttp.send(dataString); // Send the data
  23. }
  24.  
  25. document.getElementById("login_btn").addEventListener("click", loginAjax, false); // Bind the AJAX call to button click
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement