How To build jquery ajax with php

Submitted by: 
Language: 
Visitors have accessed this post 1884 times.

This tutorial describes how to insert, update, and delete method using php/ajax. In this tutorial I am creating small project for user account creation. That will guide you how to process server side script using Ajax without refreshing the page.

What is Ajax?

Ajax stands for Asynchronous JavaScript and XML. It is a technology to use communicates to sever and load severs side content without refreshing the page. Ajax is an efficient way for a web application to handle user interactions with a web page - a way that reduces the need to do a page refresh or full page reload for every user interaction. For the beginner better to used query ajax method which is simplified usage of technology. You can find jquery ajax documentation here http://api.jquery.com/jquery.ajax/

To register users we are going to used register table and it has following structure

  1. CREATE TABLE `register` (
  2. `user_id` INT(11) NOT NULL AUTO_INCREMENT,
  3. `firstname` VARCHAR(100) NOT NULL,
  4. `lastname` VARCHAR(100) NOT NULL,
  5. `username` VARCHAR(100) NOT NULL,
  6. `password` VARCHAR(15) NOT NULL,
  7. `email` VARCHAR(100) NOT NULL,
  8. `contact` VARCHAR(20) NOT NULL,
  9. PRIMARY KEY (`user_id`)
  10. )

Then we need to create a html page and add jquery library to code. For easy maintain purpose I break up page and put in to top part as header file. Here is its code

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.  
  4. <meta charset="utf-8"/>
  5. <title>Admin Panel</title>
  6. <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
  7. <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  8. <script src="js/hideshow.js" type="text/javascript"></script>
  9. <script src="js/jquery.tablesorter.min.js" type="text/javascript"></script>
  10. <script type="text/javascript" src="js/jquery.equalHeight.js"></script>
  11. <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>

After creating page we need to code for user registration form that’s we are going to load by ajax in to jquery dialog box.

  1. <head>
  2. <link rel="stylesheet" href="<a href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
  3. " rel="nofollow">https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
  4. </a> <link rel="stylesheet" href="<a href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
  5. " rel="nofollow">https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min....</a> <script src="<a href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
  6. " rel="nofollow">https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></s...</a> <link rel="stylesheet" href="admin_style.css" type="text/css" media="screen" />
  7. </head>
  8.  
  9. <div class="">
  10. <form id="frmuser" name="frmuser" action="register_formaction.php" method="post">
  11. <table class="">
  12. <tr>
  13. <td class="lab"><label>First name:</label></td>
  14. <td class="lab1">
  15. <input type="text" name="fname" size="30"></td>
  16. </td>
  17. </tr>
  18. <tr>
  19. <td class="lab"><label>Last name:</label></td>
  20. <td class="lab1">
  21. <input type="text" name="lname" size="30"></td>
  22. </td>
  23. </tr>
  24. <tr>
  25. <td class="lab"><label>Username:</label></td>
  26. <td class="lab1">
  27. <input type="text" name="uname" size="30"></td>
  28. </td>
  29. </tr>
  30. <tr>
  31. <td class="lab"><label>Password:</label></td>
  32. <td class="lab1">
  33. <input type="password" name="pass" size="30"></td>
  34. </td>
  35. </tr>
  36. <tr>
  37. <td class="lab"><label>Email:</label></td>
  38. <td class="lab1">
  39. <input type="email" name="email" size="30"></td>
  40. </td>
  41. </tr>
  42. <tr>
  43. <td class="lab"><label>Contact:</label></td>
  44. <td class="lab1">
  45. <input type="text" name="contact" size="30"></td>
  46. </td>
  47. </tr>
  48. <tr>
  49. <td colspan="2" class="tab-log">
  50. <input type="submit" id="insertuser" class="sub-form" name="submit" value="Add">
  51. </td>
  52. </tr>
  53. </table>
  54. <br />
  55. </form>
  56.  
  57.  
  58. </div>

After creating form then we need to load content to Jquery dialog box when user cliqued add button

  1. $("#btnnewuser").on( "click", function(e) {
  2.  
  3.  
  4. dialog_newuser = $('<div></div>').load('register_form.php').dialog({
  5. autoOpen: false,
  6. title:'Add new user',
  7. width: 600,
  8. height: 400
  9. });
  10.  
  11. dialog_newuser.dialog('open');
  12.  
  13. });

Then we are going to create our Ajax add method. Usually AJAX can be pass two ways. Using url with some setting or as a JSON object.

  1. $(document).on('click',"#insertuser", function(event){
  2.  
  3. event.preventDefault();
  4.  
  5. var formData = $("#frmuser").serialize();
  6.  
  7.  
  8. $.ajax({
  9. type: "POST",
  10. url: "register_formaction.php",
  11. data: formData,
  12. // contentType: false,
  13. // processData: false,
  14. dataType: 'JSON',
  15. success: function(response) {
  16.  
  17. console.log(response.msg);
  18.  
  19. if(response.status == true){
  20.  
  21.  
  22.  
  23. $('#emessageerr').hide();
  24. $('#dmessage').show();
  25. $('#gmsg').attr('class','alert alert-success');
  26. $('#gmsg').html(response.msg);
  27. // alert(response.msg);
  28. dialog_newuser.dialog('close');
  29. }
  30. else{
  31. alert(response.msg);
  32. $('#dmessage').hide();
  33. $('#emessageerr').show();
  34. // $('#ghmsgerr').switchClass('alert alert-danger','alert alert-success');
  35. $('#ghmsgerr').html(response.msg);
  36.  
  37.  
  38. }
  39. },
  40. error: function(response) {
  41.  
  42. alert(response.msg);
  43. $('#dmessage').hide();
  44. $('#emessageerr').show();
  45. // $('#ghmsgerr').switchClass('alert alert-danger','alert alert-success');
  46. $('#ghmsgerr').html(response.msg);
  47.  
  48.  
  49. console.log(response. responseText);
  50.  
  51. }
  52. });
  53.  
  54. });

Then we need to code our php add method with proper error message handling. So we need to track all the errors happening on server to client side. we need to implement formal message handling mechanism. In our code we are using response array with proper messaging. its look like follows

  1. $response = array();
  2. $response['msg']= "";
  3. $response['status']= FALSE;

then we are creating our add method

  1. <?php
  2.  
  3. include('connect.php');
  4.  
  5. $response = array();
  6. $response['msg']= "";
  7. $response['status']= FALSE;
  8.  
  9. if(isset($_POST['fname'])){
  10.  
  11. $firstname = $_POST['fname'];
  12. $lastname = $_POST['lname'];
  13. $username = $_POST['uname'];
  14. $password = $_POST['pass'];
  15. $useremail = $_POST['email'];
  16. $usercontact = $_POST['contact'];
  17.  
  18. if($firstname == '' )
  19. {
  20. $response['msg']= "Firstname is empty";
  21. $response['status']= FALSE;
  22. }
  23. else if($lastname == '')
  24. {
  25. $response['msg']= "Lastname is empty";
  26. $response['status']= FALSE;
  27. }
  28. else if($username == '')
  29. {
  30. $response['msg']= "Username is empty";
  31. $response['status']= FALSE;
  32. }
  33. else if($password == '')
  34. {
  35. $response['msg']= "Password is empty";
  36. $response['status']= FALSE;
  37. }
  38. else if($useremail == '')
  39. {
  40. $response['msg']= "Usermail is empty";
  41. $response['status']= FALSE;
  42. }
  43. else if($usercontact == '')
  44. {
  45. $response['msg']= "Contact is empty";
  46. $response['status']= FALSE;
  47. }
  48. else
  49. {
  50.  
  51. $passwordmd5 = md5($password);
  52. $insert_query = "insert into register(firstname, lastname, username, password, email, contact) values('$firstname', '$lastname',
  53. '$username', '$passwordmd5', '$useremail', '$usercontact')";
  54.  
  55. if(mysql_query($insert_query))
  56. {
  57. $response['msg']= "Susscessfully Inserted";
  58. $response['status']= TRUE;
  59. }
  60. else{
  61.  
  62. $response['msg']= "Insertion error";
  63. $response['status']= FALSE;
  64. }
  65.  
  66. }
  67.  
  68.  
  69.  
  70.  
  71. }
  72. else{
  73. $response['msg']= "Invalied post";
  74. $response['status']= FALSE;
  75. }
  76.  
  77. echo json_encode($response);
  78.  
  79. ?>

sample code contained number of ajax usage with several method on header file. This will be very useful for beginner.


Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Comments

missing parts and edit does not work, insert needed tweaking?????

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.