Я пытаюсь отправить данные из формы в базу данных. Вот форма, которую я использую:
<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)?
Базовое использование .ajax
будет выглядеть примерно так:
HTML:
<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 ready, поэтому вы должны поместить его внутрь обработчика $(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;
Примечание: Всегда санируйте публикуемые данные, чтобы предотвратить инъекции и другой вредоносный код.
Вы также можете использовать сокращение .post
вместо .ajax
в приведенном выше коде JavaScript:
$.post('/form.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
Примечание: Приведенный выше код JavaScript предназначен для работы с jQuery 1.8 и более поздними версиями, но он должен работать с предыдущими версиями вплоть до jQuery 1.5..
Чтобы сделать Ajax-запрос с помощью jQuery, можно воспользоваться следующим кодом.
HTML:
<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-вызове мы делаем POST-запрос (type: "post"
), теперь мы можем получить данные, используя $_REQUEST
или $_POST
:
$bar = $_POST['bar']
Вы также можете посмотреть, что вы получаете в POST-запросе, просто используя любой из них. BTW, убедитесь, что $_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");
});
Я хотел бы поделиться подробным способом публикации с помощью PHP + Ajax вместе с ошибками, возникающими при сбое.
Прежде всего, создайте два файла, например form.php
и "process.php `.
Сначала мы создадим "форму", которая затем будет отправлена с помощью метода 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 .
Вы можете использовать сериализацию. Ниже приведен пример.
$("#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;
});
В формате HTML:
<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>
$(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" />
<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>
Обработка Аякс ошибки и загрузчик до отправки и после отправки успех показывает предупреждение загрузке окно с примером:
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):
<script type="text/javascript">
function ap(x,y) {$("#" + y).load(x);};
function af(x,y) {$("#" + x ).ajaxSubmit({target: '#' + y});return false;};
</script>
Здесь АП() означает страницу AJAX и АФ() означает форма AJAX. В такой форме, просто позвонив АФ() функция будет размещать формы на URL-адрес и загрузить ответ на нужный HTML-элемент.
<form>
...
<input type="button" onclick="af('http://example.com','load_response')"/>
</form>
<div id="load_response">this is where response will be loaded</div>
Пожалуйста, проверьте это. Это полный запрос 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();
});
С момента введения выборка по API нет никакой причины делать это с помощью jQuery AJAX и XMLHttpRequest-запросы. Для отправки данных формы на php-скрипт в ванили на JavaScript, вы можете сделать следующее:
в
function postData() {
const form = document.getElementById('form');
const data = new FormData();
data.append('name', form.name.value);
fetch('../php/contact.php', {method: 'POST', body: data}).then(response => {
if (!response.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 = "[email protected]";
$subject = "New name submitted";
$body = "You received the following name: $name";
mail($to, $subject, $body);
Это очень хорошая статья, который содержит все, что нужно знать о jQuery отправки формы.
Краткое изложение статьи:
Простая HTML-форма отправки
HTML-код:
<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);
});
});
HTML-код multipart/данные формы форма отправки
Чтобы загрузить файлы на сервер, мы можем использовать интерфейс виде FormData доступен для XMLHttpRequest2, который создает объект FormData и могут быть отправлены легко сервер с помощью jQuery Аякс.
HTML-код:
<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);
});
});
Я надеюсь, что это помогает.
В вашем 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 = $hash_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);
}
})
или оставить его как есть с форме-отправить. Вам нужно это только, если вы хотите отправить измененную запрос с вычисляемыми дополнительный контент и не только определенной формы-данные, введенные клиентом. Например, хэш, метка, идентификатор пользователя, sessionId и тому подобное.