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 )에 제출할 수 있습니까?
의 기본 사용법은 .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이 준비된 후에 수행되어야하므로 $(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 요청을 만들려면 다음 코드를 사용하면됩니다.
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>
자바 스크립트 :
방법 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 요청에서 얻은 내용을 볼 수 있습니다. 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
.
먼저 메서드를 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 에서 다운로드 할 수 있습니다 .
직렬화를 사용할 수 있습니다. 아래는 예입니다.
$("#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>
자바 스크립트 :
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");
}
});
});
<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>
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 오류 및 로더를 처리하면 다음 예제와 함께 경고 부팅 상자가 표시됩니다.
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>
여기서 ap ()는 Ajax 페이지를 의미하고 af ()는 Ajax 형식을 의미합니다. 양식에서 단순히 af () 함수를 호출하면 양식이 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();
});
Fetch API 가 도입 된 이후로 더 이상 jQuery Ajax 또는 XMLHttpRequests로이 작업을 수행 할 이유가 없습니다. vanilla JavaScript의 PHP 스크립트에 양식 데이터를 POST하려면 다음을 수행하십시오.
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 = "test@example.com";
$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>
자바 스크립트 :
$("#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 멀티 파트 / 양식 데이터 양식 제출
서버에 파일을 업로드하기 위해 XMLHttpRequest2에서 사용할 수있는 FormData 인터페이스를 사용할 수 있습니다.이 인터페이스는 FormData 객체를 구성하고 jQuery Ajax를 사용하여 쉽게 서버로 보낼 수 있습니다.
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>
자바 스크립트 :
$("#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);
});
});
이게 도움이 되길 바란다.
참고 URL : https://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php
'IT박스' 카테고리의 다른 글
os / path 형식에 관계없이 경로에서 파일 이름 추출 (0) | 2020.10.02 |
---|---|
Spring Framework에서 @Inject와 @Autowired의 차이점은 무엇입니까? (0) | 2020.10.02 |
메소드 이름이 문자열로 주어 졌을 때 Java 메소드를 어떻게 호출합니까? (0) | 2020.10.02 |
N 일보다 오래된 파일을 삭제하는 배치 파일 (0) | 2020.10.02 |
폴더가없는 경우 새로 만듭니다. (0) | 2020.10.02 |