ajax interaction case

Posted by markduce on Fri, 13 Sep 2019 15:48:46 +0200

Data interaction is an important part of front-end, static pages are the foundation, and interaction is the essence of web pages. Interaction is also divided into human-computer interaction and front-end and back-end data interaction. At this stage, most websites need front-end and back-end data interaction. How to interact? The process of interaction is that the front end sends data to the back end, the back end receives data, processes the data, sends the processed results to the front end, and the front end receives data. What does the front end and back end receive and send through?

The front end sends data through forms and ajax, and accepts data only through ajax; the back end (php) receives data through $_GET [], $_POST [], $_REQUEST [] and prints statements to send: echo, print, print_r(), die().

ajax is an important means of front-end and back-end interaction. The full name of ajax is asynchronous JavaScript and XML (asynchronous JavaScript and XML).

Maybe you can't feel anything like that. Let's feel the case.

First, we need to prepare the layout of the next page. The layout uses the bootstrap modal box. You can see it by Baidu yourself.

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8     <link rel="stylesheet" href="libs/bootstrap.css">
 9     <title>Document</title>
10 </head>
11 
12 <body>
13     <div class="container">
14         <div class="row align-items-center">
15             <div class="col-2 h1">LOGO</div>
16             <div class="col-2 h4">Student Information System</div>
17             <button type="button" class="btn btn-primary col-1" data-toggle="modal" data-target="#exampleModal"
18                 data-whatever="@mdo" id="insert">Add information</button>
19         </div>
20         <div class="row my-5">
21             <table class="table table-bordered thead-default table-sm">
22                 <thead>
23                     <tr>
24                         <th>ID</th>
25                         <th>name</th>
26                         <th>machine</th>
27                         <th>examination</th>
28                         <th>delete</th>
29                         <th>update</th>
30                     </tr>
31                 </thead>
32                 <tbody>
33                     <!-- <tr>
34                         <td>1</td>
35                         <td>admin</td>
36                         <td>23</td>
37                         <td>87</td>
38                         <td><span class="btn btn-primary btn-info" ly="delete">delete</span></td>
39                         <td><button type="button" class="btn btn-primary btn-info" data-toggle="modal"
40                             data-target="#ExampleModal "data-whatever="@fat "ly=" update "> modify </button>.</td>
41                     </tr> -->
42                 </tbody>
43             </table>
44         </div>
45         <div class="row">
46             <nav aria-label="Page navigation example" class="w-100">
47                 <ul class="pagination pagination-sm justify-content-center">
48                     <li class="page-item disabled"><a class="page-link" href="#">Previous page</a></li>
49                     <li class="page-item"><a class="page-link" href="#">1</a></li>
50                     <li class="page-item"><a class="page-link" href="#">2</a></li>
51                     <li class="page-item"><a class="page-link" href="#">3</a></li>
52                     <li class="page-item"><a class="page-link" href="#">next page</a></li>
53                 </ul>
54             </nav>
55         </div>
56     </div>
57     <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
58         <div class="modal-dialog" role="document">
59             <div class="modal-content">
60                 <div class="modal-header">
61                     <h4 class="modal-title" id="exampleModalLabel">Please enter information:</h4>
62                     <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
63                             aria-hidden="true">&times;</span></button>
64                 </div>
65                 <div class="modal-body">
66                     <form>
67                         <div class="form-group">
68                             <label for="recipient-name" class="control-label">Full name:</label>
69                             <input type="text" class="form-control" id="name">
70                         </div>
71                         <div class="form-group">
72                             <label for="message-text" class="control-label">Machine test:</label>
73                             <input class="form-control" id="cpt" />
74                         </div>
75                         <div class="form-group">
76                             <label for="message-text" class="control-label">Written examination:</label>
77                             <input class="form-control" id="pen" />
78                         </div>
79                     </form>
80                 </div>
81                 <div class="modal-footer">
82                     <button type="button" class="btn btn-primary mx-auto" data-dismiss="modal" id="send">Submission</button>
83                 </div>
84             </div>
85         </div>
86     </div>
87 </body>
88 <script src="libs/jquery-2.2.4.js"></script>
89 <script src="libs/popper.js"></script>
90 <script src="libs/bootstrap.js"></script>
91 <script src="js/ajax.js"></script>
92 <script src="js/index.js"></script>
93 </html>

The next step is js. Actually, the interaction is to add, delete and modify. Let's look at it first.

; (function () {
 2     class Project {
 3         constructor() {
 4             // Get elements
 5             this.tbody=document.querySelector("tbody");
 6             this.addBtn=document.querySelector("#insert");
 7             this.submit=document.querySelector("#send");
 8             this.name = document.getElementById("name");
 9             this.cpt = document.getElementById("cpt");
10             this.pen = document.getElementById("pen");
11             // console.log(this.addBtn);
12             this.selectUrl = "http://localhost/test/project/php/select.php";
16             this.select();
17       }   
18          select() {
19             var that = this;
20             ajax({
21                 url: this.selectUrl,
22                 success: function (res) {
23                     // console.log(res);
24                     that.res = JSON.parse(res);
25                     if (that.res.code) {
26                         alert(that.res.msg);
27                     } else {
28                         // console.log(that.res);
29                         that.display();
30                     }
31                 }
32             });
33         }
34     display() {
35             // console.log(this.res.length);
36             var str = "";
37             for (var i = 0; i < this.res.length; i++) {
38                 str += `<tr>
39                 <td>${this.res[i].Id}</td>
40                 <td>${this.res[i].name}</td>
41                 <td>${this.res[i].machine}</td>
42                 <td>${this.res[i].examination}</td>
43                 <td><span class="btn btn-primary btn-info" ly="delete">delete</span></td>
44                 <td><button type="button" class="btn btn-primary btn-info" data-toggle="modal"
45                     data-target="#ExampleModal "data-whatever="@fat "ly=" update "> modify </button>.</td>
46             </tr> `
47             }
48             this.tbody.innerHTML=str;
49         }
50     }
51     new Project();
52 })();

Above is the js part of the code, encapsulated ajax, so I called directly. Look at the php section again.

 1 <?php
 2     $link=@new mysqli("localhost:3306","root","root","test");
 3     if($link->connect_error){
 4         $err = array("code"=>1,"msg"=>$link->connect_error);
 5         die(json_encode($err));
 6     }
 7     $select="SELECT * FROM stu";
 8     $res=$link->query($select);
 9     if($res){
10         $str="";
11         while ($arr=$res->fetch_assoc()) {
12            $str=$str.json_encode($arr).",";
13         }
14         die ("[".substr($str,0,-1)."]");
15     }else{
16         $err = array("code"=>2,"msg"=>"fail");
17         die(json_encode($err));
18     }
19 ?>

When the page is refreshed, the data in the database is automatically retrieved and rendered onto the page. Then add and modify the data, because a modal box is used, so write at the same time, because the submit button in the modal box needs to determine whether the Add button triggers or the Modify button triggers, it needs an identification. Ibid., Code Feeling!

  1 ; (function () {
  2     class Project {
  3         constructor() {
  4             // Get elements
  5             this.tbody=document.querySelector("tbody");
  6             this.addBtn=document.querySelector("#insert");
  7             this.submit=document.querySelector("#send");
  8             this.name = document.getElementById("name");
  9             this.cpt = document.getElementById("cpt");
 10             this.pen = document.getElementById("pen");
 11             // console.log(this.addBtn);
 12             this.selectUrl = "http://localhost/test/project/php/select.php";
 13             this.insertUrl="http://localhost/test/project/php/insert.php";
 14             this.updateUrl="http://localhost/test/project/php/update.php";
 15             
 16 
 17             this.type=0;
 18             this.select();
 19             this.addEvent();
 20         }
 21         select() {
 22             var that = this;
 23             ajax({
 24                 url: this.selectUrl,
 25                 success: function (res) {
 26                     // console.log(res);
 27                     that.res = JSON.parse(res);
 28                     if (that.res.code) {
 29                         alert(that.res.msg);
 30                     } else {
 31                         // console.log(that.res);
 32                         that.display();
 33                     }
 34                 }
 35             });
 36         }
 37         addEvent(){
 38             var that=this;
 39             this.addBtn.addEventListener("click",function(){
 40                 that.type=0;
 41             });
 42             this.tbody.addEventListener("click",function(eve){
 43                 var e = eve || window.event;
 44                 that.target = e.target || e.srcElement;
 45                 if(that.target.getAttribute("y") === "update"){
 46                     that.type = 1;
 47                     that.id=that.target.parentNode.parentNode.children[0].innerHTML;
 48                     that.name.value=that.target.parentNode.parentNode.children[1].innerHTML;
 49                     that.cpt.value=that.target.parentNode.parentNode.children[2].innerHTML;
 50                     that.pen.value=that.target.parentNode.parentNode.children[3].innerHTML;
 51                 }
 52             });
 53             this.submit.addEventListener("click",function(){
 54                 that.n=that.name.value;
 55                 that.c=that.cpt.value;
 56                 that.p=that.pen.value;
 57                 if(that.type==0){
 58                     that.name.value=that.cpt.value=that.pen.value="";
 59                     that.insertLoad();
 60                 }else{
 61                     // console.log();
 62                    that.updateLoad();
 63                 }
 64             })
 65         }
 66         insertLoad(){
 67             var that=this;
 68             ajax({
 69                 url:this.insertUrl,
 70                 data:{
 71                     name:this.n,
 72                     cpt:this.c,
 73                     pen:this.p
 74                 },
 75                 success:function(res){
 76                     // console.log(res);
 77                     that.res=JSON.parse(res);
 78                     if(that.res.code){
 79                         alert(that.res.msg);
 80                     }else{
 81                         that.display();
 82                     }
 83                 }
 84             });
 85         }
 86         updateLoad(){
 87             var that=this;
 88             ajax({
 89                 url:this.updateUrl,
 90                 data:{
 91                     id:this.id,
 92                     name:this.n,
 93                     cpt:this.c,
 94                     pen:this.p
 95                 },
 96                 success:function (res) {
 97                     that.res=JSON.parse(res);
 98                     if(that.res.code){
 99                         alert(that.res.msg);
100                     }else{
101                         that.display();
102                     }
103                 }
104             })
105         }
106         display() {
107             // console.log(this.res.length);
108             var str = "";
109             for (var i = 0; i < this.res.length; i++) {
110                 str += `<tr>
111                 <td>${this.res[i].Id}</td>
112                 <td>${this.res[i].name}</td>
113                 <td>${this.res[i].machine}</td>
114                 <td>${this.res[i].examination}</td>
115                 <td><span class="btn btn-primary btn-info" ly="delete">delete</span></td>
116                 <td><button type="button" class="btn btn-primary btn-info" data-toggle="modal"
117                     data-target="#ExampleModal "data-whatever="@fat "ly=" update "> modify </button>.</td>
118             </tr> `
119             }
120             this.tbody.innerHTML=str;
121         }
122     }
123     new Project();
124 })();

Here is the php code corresponding to the add button!

 1 <?php
 2     $link=@new mysqli("localhost:3306","root","root","test");
 3     if($link->connect_error){
 4         $err = array("code"=>1,"msg"=>$link->connect_error);
 5         die(json_encode($err));
 6     }
 7     $n=@$_REQUEST["name"];
 8     $c=@$_REQUEST["cpt"];
 9     $p=@$_REQUEST["pen"];
10     $insert="INSERT stu (name,machine,examination) VALUES('".$n."',".$c.",".$p.")";
11     $q=$link->query($insert);
12     if($q){
13        echo select();
14     }else{
15         $err = array("code"=>3,"msg"=>"Add failure");
16         die(json_encode($err));
17     }
18     function select(){
19         global $link;
20         $select="SELECT * FROM stu";
21         $res=$link->query($select);
22         if($res){
23             $str="";
24             while ($arr=$res->fetch_assoc()) {
25                $str=$str.json_encode($arr).",";
26             }
27             die ("[".substr($str,0,-1)."]");
28         }else{
29             $err = array("code"=>2,"msg"=>"fail");
30             die(json_encode($err));
31         }
32     }
33 ?>

Here is the php code for modifying the button!

 1 <?php
 2     $link=@new mysqli("localhost:3306","root","root","test");
 3     if($link->connect_error){
 4         $err = array("code"=>1,"msg"=>$link->connect_error);
 5         die(json_encode($err));
 6     }
 7     $id=@$_REQUEST["id"];
 8     $n=@$_REQUEST["name"];
 9     $c=@$_REQUEST["cpt"];
10     $p=@$_REQUEST["pen"];
11     $update="UPDATE stu SET name='".$n."',machine=".$c.",examination=".$p." WHERE Id=".$id;
12     $q=$link->query($update);
13     if($q){
14         echo select();
15     }else{
16         $err = array("code"=>3,"msg"=>"Add failure");
17         die(json_encode($err));
18     }
19     function select(){
20         global $link;
21         $select="SELECT * FROM stu";
22         $res=$link->query($select);
23         if($res){
24             $str="";
25             while ($arr=$res->fetch_assoc()) {
26                $str=$str.json_encode($arr).",";
27             }
28             die ("[".substr($str,0,-1)."]");
29         }else{
30             $err = array("code"=>2,"msg"=>"fail");
31             die(json_encode($err));
32         }
33     }
34 ?>

Add, modify the completion of the operation is deletion, deletion is relatively simple, as long as access to click delete the corresponding data can be!

  1 ; (function () {
  2     class Project {
  3         constructor() {
  4             // Get elements
  5             this.tbody=document.querySelector("tbody");
  6             this.addBtn=document.querySelector("#insert");
  7             this.submit=document.querySelector("#send");
  8             this.name = document.getElementById("name");
  9             this.cpt = document.getElementById("cpt");
 10             this.pen = document.getElementById("pen");
 11             // console.log(this.addBtn);
 12             this.selectUrl = "http://localhost/test/project/php/select.php";
 13             this.insertUrl="http://localhost/test/project/php/insert.php";
 14             this.updateUrl="http://localhost/test/project/php/update.php";
 15             this.deleteUrl="http://localhost/test/project/php/delect.php";
 16 
 17             this.type=0;
 18             this.select();
 19             this.addEvent();
 20         }
 21         select() {
 22             var that = this;
 23             ajax({
 24                 url: this.selectUrl,
 25                 success: function (res) {
 26                     // console.log(res);
 27                     that.res = JSON.parse(res);
 28                     if (that.res.code) {
 29                         alert(that.res.msg);
 30                     } else {
 31                         // console.log(that.res);
 32                         that.display();
 33                     }
 34                 }
 35             });
 36         }
 37         addEvent(){
 38             var that=this;
 39             this.addBtn.addEventListener("click",function(){
 40                 that.type=0;
 41             });
 42             this.tbody.addEventListener("click",function(eve){
 43                 var e = eve || window.event;
 44                 that.target = e.target || e.srcElement;
 45                 if(that.target.getAttribute("ly") === "update"){
 46                     that.type = 1;
 47                     that.id=that.target.parentNode.parentNode.children[0].innerHTML;
 48                     that.name.value=that.target.parentNode.parentNode.children[1].innerHTML;
 49                     that.cpt.value=that.target.parentNode.parentNode.children[2].innerHTML;
 50                     that.pen.value=that.target.parentNode.parentNode.children[3].innerHTML;
 51                 }else if(that.target.getAttribute("ly") === "delete"){
 52                     that.i=that.target.parentNode.parentNode.children[0].innerHTML;
 53                     that.na=that.target.parentNode.parentNode.children[1].innerHTML;
 54                     that.ma=that.target.parentNode.parentNode.children[2].innerHTML;
 55                     that.ex=that.target.parentNode.parentNode.children[3].innerHTML;
 56                     
 57                     that.deleteLoad();
 58                 }
 59             });
 60             this.submit.addEventListener("click",function(){
 61                 that.n=that.name.value;
 62                 that.c=that.cpt.value;
 63                 that.p=that.pen.value;
 64                 if(that.type==0){
 65                     that.name.value=that.cpt.value=that.pen.value="";
 66                     that.insertLoad();
 67                 }else{
 68                     // console.log();
 69                    that.updateLoad();
 70                 }
 71             })
 72         }
 73  93 113         deleteLoad(){
114             var that=this;
115             ajax({
116                 url:this.deleteUrl,
117                 data:{
118                     id:this.i,
119                     name:this.na,
120                     cpt:this.ma,
121                     pen:this.ex,
122                 },
123                 success:function(res){
124                     that.res=JSON.parse(res);
125                     if(that.res.code){
126                         alert(that.res.msg);
127                     }else{
128                         that.display();
129                     }
130                 }
131             })
132         }
133         display() {
134             // console.log(this.res.length);
135             var str = "";
136             for (var i = 0; i < this.res.length; i++) {
137                 str += `<tr>
138                 <td>${this.res[i].Id}</td>
139                 <td>${this.res[i].name}</td>
140                 <td>${this.res[i].machine}</td>
141                 <td>${this.res[i].examination}</td>
142                 <td><span class="btn btn-primary btn-info" ly="delete">delete</span></td>
143                 <td><button type="button" class="btn btn-primary btn-info" data-toggle="modal"
144                     data-target="#ExampleModal "data-whatever="@fat "ly=" update "> modify </button>.</td>
145             </tr> `
146             }
147             this.tbody.innerHTML=str;
148         }
149     }
150     new Project();
151 })();

Deleted php code!

 1 <?php
 2     $link=@new mysqli("localhost:3306","root","root","test");
 3     if($link->connect_error){
 4         $err = array("code"=>1,"msg"=>$link->connect_error);
 5         die(json_encode($err));
 6     }
 7     $id=@$_REQUEST["id"];
 8     $n=@$_REQUEST["name"];
 9     $c=@$_REQUEST["cpt"];
10     $p=@$_REQUEST["pen"];
11     $delete="DELETE FROM stu WHERE Id=".$id;
12     $q=$link->query($delete);
13     if($q){
14         echo select();
15     }else{
16         $err = array("code"=>3,"msg"=>"Add failure");
17         die(json_encode($err));
18     }
19     function select(){
20         global $link;
21         $select="SELECT * FROM stu";
22         $res=$link->query($select);
23         if($res){
24             $str="";
25             while ($arr=$res->fetch_assoc()) {
26                $str=$str.json_encode($arr).",";
27             }
28             die ("[".substr($str,0,-1)."]");
29         }else{
30             $err = array("code"=>2,"msg"=>"fail");
31             die(json_encode($err));
32         }
33     }
34 ?>

This is all the code of the interaction case. Let's see how it feels. In fact, as long as the relationship can be sorted out, what we do is to send the data to the back end and accept the data returned by the back end.

Topics: Javascript PHP JSON xml