Poskušam poslati podatke iz obrazca v zbirko podatkov. Tukaj je obrazec, ki ga uporabljam:
<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>
Običajen pristop bi bil, da obrazec pošljete, vendar to povzroči preusmeritev brskalnika. Ali je mogoče z uporabo jQueryja in Ajaxa zajeti vse podatke iz obrazca in jih poslati skripti PHP (na primer form.php)?
Osnovna uporaba .ajax
bi bila videti nekako takole:
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);
});
});
Opomba: Od različice jQuery 1.8 so .success()
, .error()
in .complete()
zapravljeni v korist .done()
, .fail()
in .always()
.
Pomnilnik: Ne pozabite, da mora biti zgornji odlomek izveden po tem, ko je DOM pripravljen, zato ga morate vstaviti znotraj izvajalca $(document).ready()
(ali uporabiti okrajšavo $()
).
Tip: Obdelovalnike povratnih klicev lahko verižite na naslednji način: $.ajax().done().fail().always();
PHP (tj. 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;
Pomnilo: Vedno uredite objavljene podatke, da preprečite vbrizgavanje in drugo zlonamerno kodo.
V zgornji kodi JavaScript lahko namesto .ajax
uporabite tudi okrajšavo .post
:
$.post('/form.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
Opomba: Zgornja koda JavaScript je narejena za delovanje z jQueryjem 1.8 in novejšim, vendar bi morala delovati tudi s prejšnjimi različicami do jQueryja 1.5.
Za izvedbo zahteve Ajax z uporabo jQuery lahko to storite z naslednjo kodo.
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:
Metoda 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);
}
});
Metoda 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');
});
Povratni klici .success()
, .error()
in .complete()
so od različice jQuery 1.8 zastareli. Če želite svojo kodo pripraviti na njihovo morebitno odstranitev, namesto njih uporabite .done()
, .fail()
in .always()
.
MDN: abort()
. Če je bila zahteva že poslana, ta metoda prekine zahtevo.
Tako smo uspešno poslali zahtevo Ajax, zdaj pa je čas, da podatke prenesemo v strežnik.
PHP
Ker smo v klicu Ajax poslali zahtevo POST (type: "post"
), lahko zdaj podatke zajamemo z uporabo $_REQUEST
ali $_POST
:
$bar = $_POST['bar']
Prav tako lahko vidite, kaj dobite v zahtevi POST, in sicer tako, da preprosto. Mimogrede, prepričajte se, da je nastavljena vrednost $_POST
. V nasprotnem primeru boste dobili napako.
var_dump($_POST);
// Or
print_r($_POST);
V podatkovno zbirko vstavljate vrednost. Pred izvedbo poizvedbe se prepričajte, da ste pravilno izbrisali ali izbrisali Vse zahteve (ne glede na to, ali ste izvedli GET ali POST). Najbolje bi bilo uporabiti pripravljene stavke.
In če želite vrniti kakršne koli podatke nazaj na stran, lahko to storite tako, da te podatke samo ponovite, kot je navedeno spodaj.
// 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'));
In potem ga lahko prejmete, kot je:
ajaxRequest.done(function (response){
alert(response);
});
Obstaja nekaj kratkih metod. Uporabite lahko spodnjo kodo. Opravi enako delo.
var ajaxRequest= $.post("test.php", values, function(data) {
alert(data);
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});
Uporabite lahko serialize. Spodaj je primer.
$("#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;
});