1<!doctype html>
2<html>
3<head>
4<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
5</head>
6<body>
7<form id="loginform" method="post">
8 <div>
9 Username:
10 <input type="text" name="username" id="username" />
11 Password:
12 <input type="password" name="password" id="password" />
13 <input type="submit" name="loginBtn" id="loginBtn" value="Login" />
14 </div>
15</form>
16<script type="text/javascript">
17$(document).ready(function() {
18 $('#loginform').submit(function(e) {
19 e.preventDefault();
20 $.ajax({
21 type: "POST",
22 url: 'login.php',
23 data: $(this).serialize(),
24 success: function(response)
25 {
26 var jsonData = JSON.parse(response);
27
28 // user is logged in successfully in the back-end
29 // let's redirect
30 if (jsonData.success == "1")
31 {
32 location.href = 'my_profile.php';
33 }
34 else
35 {
36 alert('Invalid Credentials!');
37 }
38 }
39 });
40 });
41});
42</script>
43</body>
44</html>
45
1<script>
2var objXMLHttpRequest = new XMLHttpRequest();
3objXMLHttpRequest.onreadystatechange = function() {
4 if(objXMLHttpRequest.readyState === 4) {
5 if(objXMLHttpRequest.status === 200) {
6 alert(objXMLHttpRequest.responseText);
7 } else {
8 alert('Error Code: ' + objXMLHttpRequest.status);
9 alert('Error Message: ' + objXMLHttpRequest.statusText);
10 }
11 }
12}
13objXMLHttpRequest.open('GET', 'request_ajax_data.php');
14objXMLHttpRequest.send();
15</script>
16
1function AjaxCallWithPromise() {
2 return new Promise(function (resolve, reject) {
3 const objXMLHttpRequest = new XMLHttpRequest();
4
5 objXMLHttpRequest.onreadystatechange = function () {
6 if (objXMLHttpRequest.readyState === 4) {
7 if (objXMLHttpRequest.status == 200) {
8 resolve(objXMLHttpRequest.responseText);
9 } else {
10 reject('Error Code: ' + objXMLHttpRequest.status + ' Error Message: ' + objXMLHttpRequest.statusText);
11 }
12 }
13 }
14
15 objXMLHttpRequest.open('GET', 'request_ajax_data.php');
16 objXMLHttpRequest.send();
17 });
18}
19
20AjaxCallWithPromise().then(
21 data => { console.log('Success Response: ' + data) },
22 error => { console.log(error) }
23);
24
1<?php
2if (isset($_POST['username']) && $_POST['username'] && isset($_POST['password']) && $_POST['password']) {
3 // do user authentication as per your requirements
4 // ...
5 // ...
6 // based on successful authentication
7 echo json_encode(array('success' => 1));
8} else {
9 echo json_encode(array('success' => 0));
10}
11