-
Notifications
You must be signed in to change notification settings - Fork 83
AJAX
jeff1evesque edited this page Jan 3, 2015
·
15 revisions
##Overview
Asynchronous Javascript, and XML (AJAX), is an approach that allows client-side code to interact with server side logic, without changing the layout and design of webpage (i.e. reloading the page).
Though, the X in AJAX generally stands for XML, JSON is most often preferred. JSON has the advantage of being both lighter, and an existing component of javascript.
###Example #1
$(document).ready(function() {
$('form').on('submit', function(event) {
event.preventDefault();
// Serialize Form
var data_formatted = $('form').serializeArray();
// AJAX Request
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data : data_formatted,
dataType : 'json',
beforeSend: function() {
// Add AJAX overlay, and Form Validation
[...]
}
}).done(function(data) {
// Server Response
[...]
// Remove AJAX overlay
[...]
}).fail(function(jqXHR, textStatus, errorThrown) {
// Error Message
[...]
});
});
});###Example #2
$(document).ready(function() {
$('form').on('submit', function(event) {
event.preventDefault();
// local variables
var form_data = new FormData();
var dataset = $('input[name="svm_dataset[]"]');
var flag_ajax = true;
// store 'file upload(s)' in array
if ( dataset.length > 0 && dataset.attr('type') == 'file' ) {
$( dataset ).each(function( index ) {
var file_data = dataset[index].files[0];
form_data.append('file_upload_' + index, file_data);
});
}
// undefined 'file upload(s)' sets 'flag_ajax = false'
dataset.each(function() {
if ( typeof $(this).val() === 'undefined' ) {
flag_ajax = false;
return false
}
});
// ajax request: 'svm_dataset[]' file upload(s)
if ( flag_ajax ) {
$.ajax({
url: '../../php/load_dataset.php',
type: 'POST',
data: form_data,
dataType: 'json',
contentType: false,
processData: false,
}).done(function(data) {
// Server Response
[...]
}).fail(function(jqXHR, textStatus, errorThrown) {
// Error Message
[...]
});
}
});
});