Source Explanation for Ajax Actual Projects (Quick Start Example) Github Source

Keywords: Front-end PHP SQL JSON JQuery

Author| Jeskson

Source|Dada Front End Bistro

Source address:

https://github.com/huangguangda/Ajaxitm

What is Ajax technology?Use Ajax technology in the real world, understand the way the front and back end interact, understand the mode of the mobile end, understand the new technology of H5, understand the use of CSS3, and the use of JQuery.

Ajax technology can improve the user experience, interact with background data without refreshing, operate asynchronously, and improve performance without refreshing pages.

Understanding the front-end and back-end interaction process, mainly divided into three parts, client, server, database, environment setup, wamp, phpMyAdmin.

wamp,window,Apache,mysql,php.

Create a project:

Create a small project named AjaxItem

Next, attach my code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form>
    //User name: <input type="text">
    <input type="submit" value="register">
</form>
</body>
</html>

The effect of running is the following screenshot

Add a page reg.php that the server jumps to find the value of the input box

Form submission method: GET, POST

Specify the encoding of the current page

header("Content-type:text/html;charset=utf-8");

Connect to database mysql

$con = mysql_connect();

Default value: config.default.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="reg.php">
    //User name: <input type="text" name="username">
    <input type="submit" value="register">
</form>
</body>
</html>

2

Features of get submissions:

post submission features:

The screenshots above show the differences in data transmission. We usually use get for data query, but we can use post to modify, add or delete data.

Writing on the server side:

Select a database: mysql_select_db(); create a database, create tables, key fields

Specify encoding format for database

mysql_query("set names utf8");

Get Transfer Data

$_GET
$_POST

Create a database:

Create tables:

Create data

sql query:

select * from surface where field = value
mysql_query
mysql_num_rows

reg.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="reg.php" method="post">
    //User name: <input type="text" name="username">
    <input type="submit" value="register">
</form>
</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="reg.php" method="post">
    //User name: <input type="text" name="username">
    <input type="submit" value="register">
</form>
</body>
</html>

reg.php code:

<?php
// Define encoding formats
header("Content-type:text/html;charset=utf-8");
// Connect mysql
$con = mysql_connect("localhost",'root','123456');
mysql_select_db('ajaxitem');
mysql_query('set names utf8');

$username = $_POST['username'];
$sql = "select * from reg where username = '$username'";
$query = mysql_query($sql);

// How do I distinguish between queries and no queries?
//mysql_num_rows($query);
// Found 1, not 0

if($query && mysql_num_rows($query)){
 echo "<script>alert('Someone has already registered')</script>";
 echo "<script>history.back()</script>";
}else {
$sql = "insert into reg(username) values ('$username')";
$sql = mysql_query($sql);
if($query){
    echo "<script>alert('login was successful')</script>";
    echo "<script>window.location = 'index.html'</script>";
}
}
?>

: 3

sql query:

select * from surface where field = value
mysql_query
mysql_num_rows

sql Add to

insert into Table (field) values(Value)

Basic use of Ajax:

XMLHttpRequest
open
onreadystatechange

readyState
0 uninitialized
1 Initialization
2 send data
3 In Data Transfer
4 complete

send
onreadystatechange

status
http Status Code
200
301
304
403
404
500

statusText
responseText
 responseXML
 JSON.parse

POST:
Header information needs to be set
 Position before send

setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
setRequestHeader('Content-Type', 'application/json');

JSON_stringify
JQuery In Ajax

$.ajax

url
type
data
success
error
dataType
async

Provide public code

require_once()

get data
mysql_fetch_row
mysql_fetch_assoc
mysql_fetch_array
mysql_fetch_object

crud
 delete from table where field = value
 update table set field = new value where id = $id;
Functions to create xhrs

function createStandardXHR() {
 try {
  return new window.XMLHttpRequest();
 }catch(e){}
}

function createActiveXHR() {
 try {
  return new window.ActiveXObject("Microsoft.XMLHTTP");
  }catch(e){}
}

index.html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="reg.php" method="post">
    User name:<input type="text" name="username">
    <input type="submit" value="register">
</form>
<div id="div">

</div>
<script>
var oInput = document.getElementById("input1");
var oDiv = document.getElementById('div1');

oInput.onblur = function () {
    var xhr = new XMLHttpRequest();
    xhr.open('POST','user.php',true);

}
</script>
</body>
</html>

user.php

<?php
// Define encoding formats
header("Content-type:text/html;charset=utf-8");
// Connect mysql
$con = mysql_connect("localhost",'root','123456');
mysql_select_db('ajaxitem');
mysql_query('set names utf8');

$username = $_GET['username'];
$sql = "select * from reg where username = '$username'";
$query = mysql_query($sql);

if($sql && mysql_num_rows($query)){
    echo '{"code":0, "message": "Already registered" }';
}else {
    echo  '{"code":1,"message":"Can be registered"}';
}
?>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="reg.php" method="post">
    //User name: <input type="text" name="username">
    <input type="submit" value="register">
</form>
<div id="div">

</div>
<script>
var oInput = document.getElementById("input1");
var oDiv = document.getElementById('div1');

oInput.onblur = function () {
    var xhr = new XMLHttpRequest();
    // xhr.open('POST','user.php?username='+encodeURIComponent(this.value),true);
    xhr.open('POST','user.php',true);

    // Monitor the entire process, trigger multiple times
    xhr.onreadystatechange = function () {
        if(xhr.readyState == 4) {
            if(xhr.status == 200) {
                xhr.responseText;
                // xhr.responseXML
                // console.log(JSON.parse(xhr.responseText));
                var obj = JSON.parse(xhr.responseText);
                if(obj.code) {
                    oDiv.innerHTML = obj.message
                }else {
                    oDiv.innerHTML = obj.message
                }
            }
        }
    };
    // xhr.send(null);
    xhr.send('username'+encodeURIComponent(this.value));
}
</script>
</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="reg.php" method="post">
    //User name: <input type="text" name="username">
    <input type="submit" value="register">
</form>
<div id="div">

</div>
<script>
var oInput = document.getElementById("input1");
var oDiv = document.getElementById('div1');

oInput.onblur = function () {
    var xhr = new XMLHttpRequest();
    // xhr.open('POST','user.php?username='+encodeURIComponent(this.value),true);
    xhr.open('POST','user.php',true);

    // Monitor the entire process, trigger multiple times
    xhr.onreadystatechange = function () {
        if(xhr.readyState == 4) {
            if(xhr.status == 200) {
                xhr.responseText;
                // xhr.responseXML
                // console.log(JSON.parse(xhr.responseText));
                var obj = JSON.parse(xhr.responseText);
                if(obj.code) {
                    oDiv.innerHTML = obj.message
                }else {
                    oDiv.innerHTML = obj.message
                }
            }
        }
    };
    // xhr.send(null);
    // xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    // xhr.send('username'+encodeURIComponent(this.value));

    // 'username=dada&age=12'
    // xhr.setRequestHeader('Content-Type','application/json');
    // xhr.send('{ "username": dada, "age": 12}');
    // xhr.send(JSON.stringify({"username":"dada","age":12}));

    // {"username":"dada","age":12} -> $.param() -> "useranme=dada&age=12"
}
</script>
</body>
</html>

JQuery:

if(s.data && s.processData && typeof s.data !== "string"){
 s.data = JQuery.param(s.data, s.traditional);
}

inspectPrefiltersOrTransports(prefilters, s, options, jqXHR);

if(state === 2){
return jqXHR;
}

ajax.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
$.ajax({
 url: 'jquery.php',
 type:  'GET',
 data: {username: "dada"},
 success: function(data){
  console.log(data);
 }
});
</body>
</html>

jquery.php

<?PHP

  //echo 'red';
  echo '{"color":"red","width":"200px"}';

?>

Request the same part:

require_once('connect.php');

ajax1.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script>
//get : http://localhost/reg.php?username=dada
//post : http://localhost/reg.php
</script>
</head>

<body>
<form action="reg.php" method="post">
  User name : <input type="text" name="username">   <!--username=dada-->
    <input type="submit" value="register">
</form>
</body>
</html>

ajax2.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>

</head>

<body>
<form action="reg.php" method="post">
  //User name: <input id="input1" type="text" name="username"> <!--username=dada-->
    <input type="submit" value="register">
</form>
<div id="div1"></div>
<script>
var oInput = document.getElementById('input1');
var oDiv = document.getElementById('div1');

oInput.onblur = function(){
  var xhr = new XMLHttpRequest();
  xhr.open('GET','user.php?username='+encodeURIComponent(this.value),true);
  xhr.onreadystatechange = function(){
    
    if(xhr.readyState == 4){
      //console.log(xhr.status);
      //console.log(xhr.statusText);
      if(xhr.status == 200){
        //console.log(xhr.responseText);
        //console.log(JSON.parse(xhr.responseText));
        var obj = JSON.parse(xhr.responseText);
        if(obj.code){
          oDiv.innerHTML = obj.message;
        }
        else{
          oDiv.innerHTML = obj.message;
        }
      }
    }
    
  };
  xhr.send(null);
};
</script>
</body>
</html>

ajax3.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>

</head>

<body>
<form action="reg.php" method="post">
  //User name: <input id="input1" type="text" name="username"> <!--username=dada-->
    <input type="submit" value="register">
</form>
<div id="div1"></div>
<script>
var oInput = document.getElementById('input1');
var oDiv = document.getElementById('div1');

oInput.onblur = function(){
  var xhr = new XMLHttpRequest();
  xhr.open('POST','user.php',true);
  xhr.onreadystatechange = function(){
    
    if(xhr.readyState == 4){
      //console.log(xhr.status);
      //console.log(xhr.statusText);
      if(xhr.status == 200){
        //console.log(xhr.responseText);
        //console.log(JSON.parse(xhr.responseText));
        var obj = JSON.parse(xhr.responseText);
        if(obj.code){
          oDiv.innerHTML = obj.message;
        }
        else{
          oDiv.innerHTML = obj.message;
        }
      }
    }
    
  };
  //xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  //xhr.send('username='+encodeURIComponent(this.value));
  
  //'username=dada&age=12'
  
  //xhr.setRequestHeader('Content-Type', 'application/json');
  //xhr.send('{"username":"dada","age":12}');
  //xhr.send(JSON.stringify({"username":"dada","age":12}));
  
  //{"username":"dada","age":12} ->  $.param()  ->  'username=dada&age=12'
  
};
</script>
</body>
</html>

ajax4.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script src="jquery-2.1.3.min.js"></script>
<script>

$.ajax({
  url : 'jquery.php',
  type : 'POST',
  data : {username:"dada"},
  dataType : 'json',
  async : false,
  success : function(data){   //xhr.responseText
    console.log(data);
    //var obj = JSON.parse(data);
    //console.log(obj);
  },
  error : function(err){
    console.log(err.status);
    console.log(err.statusText);
  }
});
console.log(123);
</script>
</head>

<body>
</body>
</html>

ajax5.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script src="jquery-2.1.3.min.js"></script>
<script>

$.ajax({
  url : 'data.php',
  type : 'POST',
  data : {username:"dada"},
  dataType : 'json',
  async : false,
  success : function(data){   //xhr.responseText
    console.log(data);
    //var obj = JSON.parse(data);
    //console.log(obj);
  },
  error : function(err){
    console.log(err.status);
    console.log(err.statusText);
  }
});
console.log(123);
</script>
</head>

<body>
</body>
</html>

connect.php

<?PHP

  header("Content-type: text/html; charset=utf-8");
  $con = mysql_connect('localhost','root','');
  mysql_select_db('ajaxitem');
  mysql_query('set names utf8');

?

data.php

<?PHP

  require_once('connect.php');
  
  //$sql = "delete from reg where username = 'da1'";
  //$query = mysql_query($sql);
  
  $sql = "update reg set username = 'da1' where id = 4";
  $query = mysql_query($sql);
  
  $sql = "select * from reg limit 2";
  $query = mysql_query($sql);
  
  //print_r($query);
  //print_r(mysql_num_rows($query));
  
  //$row = mysql_fetch_row($query);
  //print_r($row);
  
  /*while($row = mysql_fetch_row($query)){    //Array Subscript Input
    print_r($row);
  }*/
  
  /*while($row = mysql_fetch_assoc($query)){    //Array key value input
    print_r($row);
  }*/
  
  /*while($row = mysql_fetch_array($query)){    //Enter the array as a whole
    print_r($row);
  }*/
  
  /*while($row = mysql_fetch_object($query)){    //Input of Object Key Values
    print_r($row);
  }*/
  /*while($row = mysql_fetch_assoc($query)){    //Array key value input
    print_r($row['username']);
  }*/
  /*while($row = mysql_fetch_object($query)){    //Input of Object Key Values
    print_r($row -> username);
  }*/
  while($row = mysql_fetch_assoc($query)){    //Array key value input
    $data[] = $row;
  }
  
  //print_r(json_encode($data));
  
  echo json_encode($data);
  
?>

user.php

<?PHP

  require_once('connect.php');
  
  $username = $_REQUEST['username'];
  
  $sql = "select * from reg where username = '$username'";
  $query = mysql_query($sql);
  
  if($query && mysql_num_rows($query)){
    echo '{"code":0 , "message" : "Already registered"}'; 
  }
  else{
    echo '{"code":1 , "message" : "Can be registered"}'; 
  }

?>

jquery.php

<?PHP

  //echo 'red';
  echo '{"color":"red","width":"200px"}';

?>

reg.php

<?PHP

  //username -> hello
  
  require_once('connect.php');

  $username = $_POST['username'];
  $sql = "select * from reg where username = '$username'";
  $query = mysql_query($sql);
    
  if($query && mysql_num_rows($query)){
    echo "<script>alert('Already registered')</script>";
    echo "<script>history.back()</script>";
  }
  else{
    $sql = "insert into reg(username) values('$username')";
    $query = mysql_query($sql);
    if($query){
      echo "<script>alert('login was successful')</script>";
      echo "<script>window.location = 'index.html'</script>";
    }
  }

?>

summary

In the blog platform, there is still a long way to go in the future, and I also hope that you can support, criticize and correct more articles in the future, so that we can make progress and take the road together.

Thank you very much to the reader for seeing this. If this article is well written, feels like I have something to do with Dada, feels like I can keep on learning, feels like this person can make friends, asks for compliments, asks for attention, asks for sharing, really for a warm man

Very useful!!!

Don't forget to leave a footprint of your study [compliment + collection + comment]

Author Info:

[Author]: Jeskson Original Public Number: Dada Front End Bistro. Welfare: Public Number replies to the big gift package for self-study materials (share in groups, just say anything you want, see if I have one)! [Reprint instructions]: Please explain the source of reprinting, thank you for your cooperation!~

Big Front End Development, Locate Front End Development Technology Stack Blog, PHP Background Knowledge Point, web Full Stack Technology Field, Data Structure and Algorithms, Network Principles and other understandable presentations to small partners.Thank you for your support and love!!!

If there are inadequacies in this number (e.g. copyright or other issues), please contact us in time to make corrections, which will be dealt with at the first time.

Please compliment!Because your approval/encouragement is my greatest motivation to write!

Welcome to your attention Dada CSDN!

This is a quality, attitudinal blog

Posted by ody on Sat, 28 Dec 2019 11:45:40 -0800