jQuery ajax() function

jquery jQuery ajax() function How To Use Ajax

We can submit the form data or any type of data to another page without the page reloading using JavaScript jQuery ajax() function.

ajax() function attributes

Ajax function has nearly 24 attributes, we have to pass these parameters into the ajax function , some of them are required and some of them are optional. Now we will discuss the important parameters

  • 'type' Specifies the type of request. (GET or POST) that will send to the submission page.
  • 'url' Specifies the URL where we want to submit this data.
  • 'dataType' The data type expected of the server response. e.g JSON
  • 'data' Specifies data to be sent to the server.
  • 'success(result,status,xhr)' A function to be run when the request succeeds.

Submit a username and password using ajax function and return the valid or invalid message about username and password.

We are going to take the two input fields for username and password. Then on button submission we will send username and password to the action.php page using ajax() function.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="text" name="username" id='username' placeholder="Enter username. . ."> <input type="text" name="password" id='password' placeholder="Enter password. . ."> <button type="submit" class="submit">Submit</button> <script type="text/javascript"> $(".submit").click(function(){ var username = $("#username").val(); var password = $("#password").val(); $.ajax({ url: "action.php", // Url to which the request is send type: "POST", //Type of request to be send, called as method data: {username:username,password:password}, //Data sent to server(i.e. form fields and values) success: function(response_msg) { alert(response_msg); } }); }); </script>

The PHP code in the action.php file

<?php error_reporting(1); if( ($_POST[username]=='admin') && ($_POST[password]=='admin') ) { echo "Valid Username and Password"; } else { echo "Invalid Username and Password"; } ?>

Output of the above ajax() function code

In action page if have write condition if the username and password both are equal to 'admin' then the data is valid else the data is invalid.

jquery How To Use Ajax Chapter Next »