Submitting a form to the database on a static page is very simple.
<form action="test.php" method="post"> </form>
The disadvantage is that the page will be refreshed and the page will jump. The technology I bring to you today is the ajax form submission. The advantage is that it does not refresh the page, does not jump to the page, and is submitted silently.
First we have to have a form submission page:
index.html
This page consists of two parts
1. Form control
2.jQuery+ajax Processing script
The jQuery script will obtain the form form data and submit it to api.php through post
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>login test</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript"> function insert() { $.ajax({ type: "POST",//方法 url: "api.php" ,//表单接收url data: $('#form1').serialize(), success: function () { //提交成功的提示词或者其他反馈代码 var result=document.getElementById("success"); result.innerHTML="成功!"; }, error : function() { //提交失败的提示词或者其他反馈代码 var result=document.getElementById("success"); result.innerHTML="失败!"; } }); } </script> </head> <body> <p id="form-p"> <form id="form1" onsubmit="return false" action="##" method="post"> <p><input name="title" id="title" type="text" value="title"/></p> <p><input name="url" id="url" type="text" value="url"/></p> <p><input type="button" value="插入" onclick="insert()"></p> <p><p id="success"></p></p> </form> </p> </body> </html>
The following is the form receiving page
api.php
This page is actually very simple
Just connect to the database
Then insert into the database
The two values inserted into the database are
title and url
<?php $title = $_POST['title']; $url = $_POST['url']; $con = mysql_connect("localhost","root","root"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("test", $con); mysql_query("INSERT INTO testdata (title, url) VALUES ('$title', '$url')"); mysql_close($con); ?>
Then we need to create a database
The database is named test, and the table Named testdata
The following is a screenshot of the database
At this point, this case is completed.
Of course, the above code simply implements the ajax form submission.
But there are still many details that need to be optimized, such as form verification, data encryption, etc. You can expand, learn and improve by yourself.
Related recommendations:
Ajax submission Form form page will still refresh j solution
js submit form form, and Implementation method of passing parameters
js Implementation method of submitting form form and setting form form request path
The above is the detailed content of ajax submit form to database instance. For more information, please follow other related articles on the PHP Chinese website!