jquery's $. ajax() and php background interaction

Keywords: PHP JQuery Javascript


Look at it. A series of tutorials on novice ajax : I have a preliminary understanding of Ajax, but I mainly want to use ajax to interact with php in front and back, so I want to realize this idea step by step, because I am not particularly familiar with Ajax, so I write rookie like code, sorry..

After reading the series of novice ajax tutorials, I didn't talk about how to use the $. ajax() method of JQuery. I hope that I can add it if I have a chance to let more readers know.

But W3School has this tutorial: http://www.w3school.com.cn/jquery/ajax_ajax.asp

JS library and CSS library suggest using domestic cdn directly, which saves a lot of effort, http://www.bootcdn.cn/

Let's start with a simple interaction, but pay attention to the fact that when using ajax to interact with php in the background, you must open the server, or there will be errors in many cases. I mean to open the server, directly input in the browser: localhost is the meaning that can be accessed effectively.

OK, let's take a look at a simple example of the interaction between JQuery's ajax() and php:

index.html code

<!DOCTYPE html>
<meta charset="utf-8">
  <!--utilize cdn Add to js and css library  -->
  <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>

<body style="text-align: center; padding: 100px;">

 //Name: < input type = "text" name = "username" id = "yourname" / >

<button id="send">Submission</button>

<div id="result">result:</div>

<script type="text/javascript">

  $(function () {
      $("#send").click(function () {

          var name = $("#yourName").val();
          var data = "name="+name; //If the background is to get data by $\POST method, it is necessary to index (for example: index name)

             type: "POST",
             url: "server.php",  //php files in the same directory
             data:"name="+name,  // No spaces before and after equal sign
            success: function(msg){  //Callback function after successful request
                $("#result").append(" your name is "+ msg);




server.php code


	$username = $_POST['name'];//Get index value
	echo  $username;


Posted by Dm7 on Sun, 03 May 2020 01:32:16 -0700