使用PHP的jQuery Ajax POST示例

我正在尝试将数据从表单发送到数据库。这是我使用的表单:

<form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>

典型的方法是提交表单,但这会导致浏览器重定向。使用jQuery和Ajax,是否可以捕获表单的所有数据并将其提交到PHP脚本(示例form.php)?

1761325 次浏览

.ajax的基本用法看起来像这样:

超文本标记语言:

<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />


<input type="submit" value="Send" />
</form>

jQuery:

// Variable to hold request
var request;


// Bind to the submit event of our form
$("#foo").submit(function(event){


// Prevent default posting of form - put here to work in case of errors
event.preventDefault();


// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);


// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");


// Serialize the data in the form
var serializedData = $form.serialize();


// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);


// Fire off the request to /form.php
request = $.ajax({
url: "/form.php",
type: "post",
data: serializedData
});


// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
});


// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});


// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});


});

注意:从jQuery 1.8开始,.success().error().complete()被弃用,支持.done().fail().always()

注意:请记住,上面的代码片段必须在DOM就绪后完成,因此您应该将其放入$(document).ready()处理程序(或使用$()简写)中。

提示:您可以链接回调处理程序,如下所示:$.ajax().done().fail().always();

PHP(即form.php):

// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$bar = isset($_POST['bar']) ? $_POST['bar'] : null;

注意:始终清理发布的数据,以防止注入和其他恶意代码。

您还可以在上面的JavaScript代码中使用简写.post代替.ajax

$.post('/form.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
});

注意:上述JavaScript代码适用于jQuery 1.8及更高版本,但它应该适用于以前的jQuery 1.5版本。

要使用jQuery发出Ajax请求,您可以通过以下代码执行此操作。

超文本标记语言:

<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>


<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>

JavaScript:

方法1

 /* Get from elements values */
var values = $(this).serialize();


$.ajax({
url: "test.php",
type: "post",
data: values ,
success: function (response) {


// You will get response from your PHP page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});

方法2

/* Attach a submit handler to the form */
$("#foo").submit(function(event) {
var ajaxRequest;


/* Stop form from submitting normally */
event.preventDefault();


/* Clear result div*/
$("#result").html('');


/* Get from elements values */
var values = $(this).serialize();


/* Send the data using post and put the results in a div. */
/* I am not aborting the previous request, because it's an
asynchronous request, meaning once it's sent it's out
there. But in case you want to abort it you can do it
by abort(). jQuery Ajax methods return an XMLHttpRequest
object, so you can just use abort(). */
ajaxRequest= $.ajax({
url: "test.php",
type: "post",
data: values
});


/*  Request can be aborted by ajaxRequest.abort() */


ajaxRequest.done(function (response, textStatus, jqXHR){


// Show successfully for submit message
$("#result").html('Submitted successfully');
});


/* On failure of request this function will be called  */
ajaxRequest.fail(function (){


// Show error
$("#result").html('There is error while submit');
});

.success().error().complete()回调自jQuery 1.8起已弃用。要准备最终删除它们的代码,请改用.done().fail().always()

MDN: abort()。如果请求已经发送,此方法将中止请求。

所以我们已经成功发送了一个Ajax请求,现在是时候将数据获取到服务器了。

php

当我们在Ajax调用(type: "post")中发出POST请求时,我们现在可以使用$_REQUEST$_POST获取数据:

  $bar = $_POST['bar']

您还可以通过简单地查看POST请求中的内容。顺便说一句,确保设置了$_POST。否则您将收到错误。

var_dump($_POST);
// Or
print_r($_POST);

您正在向数据库中插入一个值。在进行查询之前,请确保您是宣传逃离所有请求(无论您是发出GET还是POST)正确。最好使用准备好的声明

如果您想将任何数据返回到页面,您可以通过如下所示的数据来实现。

// 1. Without JSON
echo "Hello, this is one"


// 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below
echo json_encode(array('returned_val' => 'yoho'));

然后你可以像这样得到它:

 ajaxRequest.done(function (response){
alert(response);
});

有几个速记法。您可以使用下面的代码。它做同样的工作。

var ajaxRequest= $.post("test.php", values, function(data) {
alert(data);
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});

您可以使用序列化。下面是一个示例。

$("#submit_btn").click(function(){
$('.error_status').html();
if($("form#frm_message_board").valid())
{
$.ajax({
type: "POST",
url: "<?php echo site_url('message_board/add');?>",
data: $('#frm_message_board').serialize(),
success: function(msg) {
var msg = $.parseJSON(msg);
if(msg.success=='yes')
{
return true;
}
else
{
alert('Server error');
return false;
}
}
});
}
return false;
});

我想分享如何使用PHP+Ajax发布以及失败时抛回的错误的详细方法。

首先,创建两个文件,例如form.phpprocess.php

我们将首先创建一个form,然后使用jQuery.ajax()方法提交。其余的将在注释中解释。


form.php

<form method="post" name="postForm">
<ul>
<li>
<label>Name</label>
<input type="text" name="name" id="name" placeholder="Bruce Wayne">
<span class="throw_error"></span>
<span id="success"></span>
</li>
</ul>
<input type="submit" value="Send" />
</form>


使用jQuery客户端验证验证表单并将数据传递给process.php

$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
$('#success').empty();


//Validate fields if required using jQuery


var postForm = { //Fetch form data
'name'     : $('input[name=name]').val() //Store name fields value
};


$.ajax({ //Process the form using $.ajax()
type      : 'POST', //Method type
url       : 'process.php', //Your form processing file URL
data      : postForm, //Forms name
dataType  : 'json',
success   : function(data) {
if (!data.success) { //If fails
if (data.errors.name) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
}
}
else {
$('#success').fadeIn(1000).append('<p>' + data.posted + '</p>'); //If successful, than throw a success message
}
}
});
event.preventDefault(); //Prevent the default submit
});
});

现在我们来看看process.php

$errors = array(); //To store errors
$form_data = array(); //Pass back the data to `form.php`


/* Validate the form on the server side */
if (empty($_POST['name'])) { //Name cannot be empty
$errors['name'] = 'Name cannot be blank';
}


if (!empty($errors)) { //If errors in validation
$form_data['success'] = false;
$form_data['errors']  = $errors;
}
else { //If not, process the form, and return true on success
$form_data['success'] = true;
$form_data['posted'] = 'Data Was Posted Successfully';
}


//Return the data back to form.php
echo json_encode($form_data);

项目文件可以从http://projects.decodingweb.com/simple_ajax_form.zip下载。

<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<form method="post" id="form_content" action="Javascript:void(0);">
<button id="desc" name="desc" value="desc" style="display:none;">desc</button>
<button id="asc" name="asc"  value="asc">asc</button>
<input type='hidden' id='check' value=''/>
</form>


<div id="demoajax"></div>


<script>
numbers = '';
$('#form_content button').click(function(){
$('#form_content button').toggle();
numbers = this.id;
function_two(numbers);
});


function function_two(numbers){
if (numbers === '')
{
$('#check').val("asc");
}
else
{
$('#check').val(numbers);
}
//alert(sort_var);


$.ajax({
url: 'test.php',
type: 'POST',
data: $('#form_content').serialize(),
success: function(data){
$('#demoajax').show();
$('#demoajax').html(data);
}
});


return false;
}
$(document).ready(function_two());
</script>

超文本标记语言

    <form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" class="inputs" name="bar" type="text" value="" />
<input type="submit" value="Send" onclick="submitform(); return false;" />
</form>

javascript

   function submitform()
{
var inputs = document.getElementsByClassName("inputs");
var formdata = new FormData();
for(var i=0; i<inputs.length; i++)
{
formdata.append(inputs[i].name, inputs[i].value);
}
var xmlhttp;
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest;
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{


}
}
xmlhttp.open("POST", "insert.php");
xmlhttp.send(formdata);
}

我使用如下所示的方式。它像文件一样提交所有内容。

$(document).on("submit", "form", function(event)
{
event.preventDefault();


var url  = $(this).attr("action");
$.ajax({
url: url,
type: 'POST',
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{


},
error: function (xhr, desc, err)
{
console.log("error");
}
});
});

我使用这个简单的一行代码多年没有问题(它需要jQuery):

<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
function ap(x,y) {$("#" + y).load(x);};
function af(x,y) {$("#" + x ).ajaxSubmit({target: '#' + y});return false;};
</script>

这里ap()表示Ajax页面,af()表示Ajax表单。在表单中,只需调用af()函数即可将表单发布到URL并将响应加载到所需的超文本标记语言元素上。

<form id="form_id">
...
<input type="button" onclick="af('form_id','load_response_id')"/>
</form>
<div id="load_response_id">this is where response will be loaded</div>

在提交之前和提交成功之后处理Ajax错误和加载程序显示了一个带有示例的警报引导框:

var formData = formData;


$.ajax({
type: "POST",
url: url,
async: false,
data: formData, // Only input
processData: false,
contentType: false,
xhr: function ()
{
$("#load_consulting").show();
var xhr = new window.XMLHttpRequest();


// Upload progress
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
$('#addLoad .progress-bar').css('width', percentComplete + '%');
}
}, false);


// Download progress
xhr.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
}
}, false);
return xhr;
},
beforeSend: function (xhr) {
qyuraLoader.startLoader();
},
success: function (response, textStatus, jqXHR) {
qyuraLoader.stopLoader();
try {
$("#load_consulting").hide();


var data = $.parseJSON(response);
if (data.status == 0)
{
if (data.isAlive)
{
$('#addLoad .progress-bar').css('width', '00%');
console.log(data.errors);
$.each(data.errors, function (index, value) {
if (typeof data.custom == 'undefined') {
$('#err_' + index).html(value);
}
else
{
$('#err_' + index).addClass('error');


if (index == 'TopError')
{
$('#er_' + index).html(value);
}
else {
$('#er_TopError').append('<p>' + value + '</p>');
}
}
});
if (data.errors.TopError) {
$('#er_TopError').show();
$('#er_TopError').html(data.errors.TopError);
setTimeout(function () {
$('#er_TopError').hide(5000);
$('#er_TopError').html('');
}, 5000);
}
}
else
{
$('#headLogin').html(data.loginMod);
}
} else {
//document.getElementById("setData").reset();
$('#myModal').modal('hide');
$('#successTop').show();
$('#successTop').html(data.msg);
if (data.msg != '' && data.msg != "undefined") {


bootbox.alert({closeButton: false, message: data.msg, callback: function () {
if (data.url) {
window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
} else {
location.reload(true);
}
}});
} else {
bootbox.alert({closeButton: false, message: "Success", callback: function () {
if (data.url) {
window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
} else {
location.reload(true);
}
}});
}


}
}
catch (e) {
if (e) {
$('#er_TopError').show();
$('#er_TopError').html(e);
setTimeout(function () {
$('#er_TopError').hide(5000);
$('#er_TopError').html('');
}, 5000);
}
}
}
});

如果你想使用jQuery Ajax发送数据,那么就不需要表单标签和提交按钮

示例:

<script>
$(document).ready(function () {
$("#btnSend").click(function () {
$.ajax({
url: 'process.php',
type: 'POST',
data: {bar: $("#bar").val()},
success: function (result) {
alert('success');
}
});
});
});
</script>


<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input id="btnSend" type="button" value="Send" />

请检查这个。这是完整的Ajax请求代码。

$('#foo').submit(function(event) {
// Get the form data
// There are many ways to get this data using jQuery (you
// can use the class or id also)
var formData = $('#foo').serialize();
var url = 'URL of the request';


// Process the form.
$.ajax({
type        : 'POST',   // Define the type of HTTP verb we want to use
url         : 'url/',   // The URL where we want to POST
data        : formData, // Our data object
dataType    : 'json',   // What type of data do we expect back.
beforeSend : function() {


// This will run before sending an Ajax request.
// Do whatever activity you want, like show loaded.
},
success:function(response){
var obj = eval(response);
if(obj)
{
if(obj.error==0){
alert('success');
}
else{
alert('error');
}
}
},
complete : function() {
// This will run after sending an Ajax complete
},
error:function (xhr, ajaxOptions, thrownError){
alert('error occured');
// If any error occurs in request
}
});


// Stop the form from submitting the normal way
// and refreshing the page
event.preventDefault();
});

这是一篇很好的文章,其中包含您需要了解的有关jQuery表单提交的所有信息。

文章摘要:

简单的超文本标记语言表单提交

超文本标记语言:

<form action="path/to/server/script" method="post" id="my_form">
<label>Name</label>
<input type="text" name="name" />
<label>Email</label>
<input type="email" name="email" />
<label>Website</label>
<input type="url" name="website" />
<input type="submit" name="submit" value="Submit Form" />
<div id="server-results"><!-- For server results --></div>
</form>

JavaScript:

$("#my_form").submit(function(event){
event.preventDefault(); // Prevent default action
var post_url = $(this).attr("action"); // Get the form action URL
var request_method = $(this).attr("method"); // Get form GET/POST method
var form_data = $(this).serialize(); // Encode form elements for submission


$.ajax({
url : post_url,
type: request_method,
data : form_data
}).done(function(response){ //
$("#server-results").html(response);
});
});

超文本标记语言Multipart/form-data表单提交

要将文件上传到服务器,我们可以使用XMLHttpRequest est2可用的FormData接口,它构造了一个FormData对象,可以使用jQuery Ajax轻松发送到服务器。

超文本标记语言:

<form action="path/to/server/script" method="post" id="my_form">
<label>Name</label>
<input type="text" name="name" />
<label>Email</label>
<input type="email" name="email" />
<label>Website</label>
<input type="url" name="website" />
<input type="file" name="my_file[]" /> <!-- File Field Added -->
<input type="submit" name="submit" value="Submit Form" />
<div id="server-results"><!-- For server results --></div>
</form>

JavaScript:

$("#my_form").submit(function(event){
event.preventDefault(); // Prevent default action
var post_url = $(this).attr("action"); // Get form action URL
var request_method = $(this).attr("method"); // Get form GET/POST method
var form_data = new FormData(this); // Creates new FormData object
$.ajax({
url : post_url,
type: request_method,
data : form_data,
contentType: false,
cache: false,
processData: false
}).done(function(response){ //
$("#server-results").html(response);
});
});

我希望这能有所帮助。

自从获取API引入以来,真的没有理由再使用jQuery Ajax或XMLHttpRequest来做到这一点。要将表单数据发布到香草JavaScript中的PHP脚本,您可以执行以下操作:

async function postData() {
try {
const res = await fetch('../php/contact.php', {
method: 'POST',
body: new FormData(document.getElementById('form'))
})
if (!res.ok) throw new Error('Network response was not ok.');
} catch (err) {
console.log(err)
}
}
<form id="form" action="javascript:postData()">
<input id="name" name="name" placeholder="Name" type="text" required>
<input type="submit" value="Submit">
</form>

这是一个非常基本的PHP脚本示例,它接收数据并发送电子邮件:

<?php
header('Content-type: text/html; charset=utf-8');


if (isset($_POST['name'])) {
$name = $_POST['name'];
}


$to = "test@example.com";
$subject = "New name submitted";
$body = "You received the following name: $name";
    

mail($to, $subject, $body);

在您的php文件中输入:

$content_raw = file_get_contents("php://input"); // THIS IS WHAT YOU NEED
$decoded_data = json_decode($content_raw, true); // THIS IS WHAT YOU NEED
$bar = $decoded_data['bar']; // THIS IS WHAT YOU NEED
$time = $decoded_data['time'];
$hash = $decoded_data['hash'];
echo "You have sent a POST request containing the bar variable with the value $bar";

并在您的js文件中发送带有数据对象的ajax

var data = {
bar : 'bar value',
time: calculatedTimeStamp,
hash: calculatedHash,
uid: userID,
sid: sessionID,
iid: itemID
};


$.ajax({
method: 'POST',
crossDomain: true,
dataType: 'json',
crossOrigin: true,
async: true,
contentType: 'application/json',
data: data,
headers: {
'Access-Control-Allow-Methods': '*',
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Headers" : "Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization",
"Access-Control-Allow-Origin": "*",
"Control-Allow-Origin": "*",
"cache-control": "no-cache",
'Content-Type': 'application/json'
},
url: 'https://yoururl.com/somephpfile.php',
success: function(response){
console.log("Respond was: ", response);
},
error: function (request, status, error) {
console.log("There was an error: ", request.responseText);
}
})

或者保持表单提交的原样。您只需要这样做,如果您想发送修改后的请求,其中包含计算的附加内容,而不仅仅是客户端输入的一些表单数据。例如哈希、时间戳、用户ID、会话ID等。

纯js

在纯JS中,它会简单得多

foo.onsubmit = e=> {
e.preventDefault();
fetch(foo.action,{method:'post', body: new FormData(foo)});
}

foo.onsubmit = e=> {
e.preventDefault();
fetch(foo.action,{method:'post', body: new FormData(foo)});
}
<form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>

我有另一个想法。

其中提供下载文件的PHP文件的URL。 然后你必须通过ajax触发相同的URL,我检查了第二个请求只有在你的第一个请求完成下载文件后才会给出响应。所以你可以得到它的事件。

它通过ajax使用相同的第二个请求工作。}

这是使用ajaxXMLHttpRequestHTML中填充selectoption标签的代码,API是用PHPPDO编写的

conn.php

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$database = "db_event";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>

category.php

<?php
include 'conn.php';
try {
$data = json_decode(file_get_contents("php://input"));
$stmt = $conn->prepare("SELECT *  FROM events ");
http_response_code(200);
$stmt->execute();
    

header('Content-Type: application/json');


$arr=[];
while($value=$stmt->fetch(PDO::FETCH_ASSOC)){
array_push($arr,$value);
}
echo json_encode($arr);
   

} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}

script.js

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
data = JSON.parse(this.responseText);


for (let i in data) {




$("#cars").append(
'<option value="' + data[i].category + '">' + data[i].category + '</option>'


)
}
}
};
xhttp.open("GET", "http://127.0.0.1:8000/category.php", true);
xhttp.send();

index.html


<!DOCTYPE html>
<html lang="en">


<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<title>Document</title>
</head>


<body>
<label for="cars">Choose a Category:</label>


<select name="option" id="option">
        

</select>
    

<script src="script.js"></script>
</body>


</html>