Home > Web Front-end > JS Tutorial > body text

How to submit a form using Ajax and receive json data in it

php中世界最好的语言
Release: 2018-03-31 13:43:49
Original
2130 people have browsed it

This time I will show you how to use Ajax to submit a form and receive the json data, and how to use Ajax to submit a form and receive the json data. What are the precautions? The following is a practical case, let's take a look. one time.

Requirements:

After clicking the button, the data is submitted to the server in the form of a form and the return data from the server is received. The page does not refresh during the process.

html code

<html xmlns="http://www.w3.org/1999/xhtml">
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
 <script src="./testajaxjs.js"></script>
 <head>
 </head>
 <body>
  <form id="form1">
   <p>xingming:<input type="text" name="xingming"/></p>
   <p>nianling:<input type="text" name="nianling"/></p>
  </form>
  <button type="button" id="mybt" onclick="mysubmmit()">
   ajax提交
  </button>
 </body>
</html>
Copy after login
js code

function mysubmmit(){
 $.ajax({
  type: "POST",
  url: "testajaxend.php",
  data: $('#form1').serialize(),
  async: false,
  success: function(databack){
   //console.log("chenggong");
   console.log(databack);
  },
  error: function(request){
   console.log("shibaile");
  }
 });
}
Copy after login
Backend

php code

<?php
  $name = $_POST[&#39;xingming&#39;];
  $age = $_POST[&#39;nianling&#39;];
  $myarray = array("name"=>$name, "age"=>$age);
  $myjson = json_encode($myarray);
  echo $myjson;
?>
Copy after login
I believe you have mastered it after reading the case in this article Method, for more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to use native ajax and encapsulated ajax (with code)

Ajax method to implement Form form Submission method

The above is the detailed content of How to submit a form using Ajax and receive json data in it. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!