How To build jquery ajax with php

Language

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

Submitted byRichie Rich (not verified)on Sun, 11/23/2014 - 18:30

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

Add new comment