Skip to content

Instantly share code, notes, and snippets.

@bablukpik
Last active June 13, 2017 20:59
Show Gist options
  • Save bablukpik/21235b4f2014d28b6093ac491828e02a to your computer and use it in GitHub Desktop.
Save bablukpik/21235b4f2014d28b6093ac491828e02a to your computer and use it in GitHub Desktop.
->XMLHttpRequest (XHR) is (an API) an object whose methods transfer data between a web browser and a web server. The object is provided by the browser's JavaScript environment.
i.e $.ajax(), $.get(), $.post()
->Syntax: $.ajax({name:value, name:value, ... })
->The parameters specifies one or more name/value pairs for the AJAX request.
->Possible names/values in the table below:
Name ->Value/Description
async ->A Boolean value indicating whether the request should be handled asynchronous or not. Default is true
beforeSend(xhr) ->A function to run before the request is sent
cache ->A Boolean value indicating whether the browser should cache the requested pages. Default is true
complete(xhr,status) ->A function to run when the request is finished (after success and error functions)
contentType ->The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
context ->Specifies the "this" value for all AJAX related callback functions
data ->Specifies data to be sent to the server
dataFilter(data,type) ->A function used to handle the raw response data of the XMLHttpRequest
dataType ->The data type expected of the server response.
error(xhr,status,error) ->A function to run if the request fails.
global ->A Boolean value specifying whether or not to trigger global AJAX event handles for the request. Default is true
ifModified ->A Boolean value specifying whether a request is only successful if the response has changed since the last request. Default is: false.
jsonp ->A string overriding the callback function in a jsonp request
jsonpCallback ->Specifies a name for the callback function in a jsonp request
password ->Specifies a password to be used in an HTTP access authentication request.
processData ->A Boolean value specifying whether or not data sent with the request should be transformed into a query string. Default is true
scriptCharset ->Specifies the charset for the request
success(result,status,xhr) ->A function to be run when the request succeeds
timeout ->The local timeout (in milliseconds) for the request
traditional ->A Boolean value specifying whether or not to use the traditional style of param serialization
type ->Specifies the type of request. (GET or POST)
url ->Specifies the URL to send the request to. Default is the current page
username ->Specifies a username to be used in an HTTP access authentication request
xhr ->A function used for creating the XMLHttpRequest object
->contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.
->dataType is what you're expecting back from the server: json, html, text, etc. And If none is specified, jQuery will try to infer it based on the MIME type of the response that can be text, xml, html, script, json, jsonp.
->Ajax Methods in details below:
$.ajax() ->Performs an async AJAX request
$.ajaxPrefilter() ->Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax()
$.ajaxSetup() ->Sets the default values for future AJAX requests
$.ajaxTransport() ->Creates an object that handles the actual transmission of Ajax data
$.get() ->Loads data from a server using an AJAX HTTP GET request
$.getJSON() ->Loads JSON-encoded data from a server using a HTTP GET request
$.getScript() ->Loads (and executes) a JavaScript from a server using an AJAX HTTP GET request
$.param() ->Creates a serialized representation of an array or object (can be used as URL query string for AJAX requests)
$.post() ->Loads data from a server using an AJAX HTTP POST request
ajaxComplete() ->Specifies a function to run when the AJAX request completes
ajaxError() ->Specifies a function to run when the AJAX request completes with an error
ajaxSend() ->Specifies a function to run before the AJAX request is sent
ajaxStart() ->Specifies a function to run when the first AJAX request begins
ajaxStop() ->Specifies a function to run when all AJAX requests have completed
ajaxSuccess() ->Specifies a function to run when an AJAX request completes successfully
load() ->Loads data from a server and puts the returned data into the selected element
serialize() ->Encodes a set of form elements as a string for submission
serializeArray() ->Encodes a set of form elements as an array of names and values
//Modal Form Submit
$(function() {
$("#submit").click(function(e){
e.preventDefault();
var email= ....; //get user entered email;
//validate email (pseudo code)
if(email is invalid) {
//display message to div#message
}
else {
//make ajax call
$.ajax({
type: "POST",
url: "send.php",
data: $('form').serialize(),
success: function(msg){
if(msg == 1) $("#modal").modal('hide');
else if(msg == 2) $("#message").html("Bad Email");
//etc...
},
error: function(){
alert("Failed to submit data");
}
});
}
});
});
//When jQuery can not select a selector
$("body").on("submit",".checkform", function(e){
e.preventDefault();
var request = $("#domein").val();
$.ajax({
...
});
});
//
$(document).on('submit', '.checkform', function(e){
});
//
echo "<script>
$(window).load(function(){
$('#thankyouModal').modal('show');
});
</script>";
//JSON Data add with HTML in a div
$("button").on('submit',function(){
$.ajax({
url: someurl,
_token : $("input[name='_token']").val(),//this requires in laravel for security
type: post,
dataType: 'json',
data: {
'skill_id' : $("select[name='jobSkillId']").val(),
'experience' : $("select[name='experience']").val()
},
success: function(json) {
$.each(json, function(key, value) {
$('.your_view_to_show ul').append($("<option</option>").attr("value", value.id).text(value.name));
});
}
});
//What is the difference between $.each(selector) and $(selector).each():
.each is an iterator that is used to iterate over only jQuery objects collection while jQuery.each ($.each) is a general function for iterating over javascript objects and arrays.
//How to see updated data quickly in ajax
we have to show data loop through on success using append() method
i.e,
var x = $("form").serializeArray();
$.each(x, function(i, field){
$("#results").append(field.name + ":" + field.value + " ");
});
//01
$.ajax({
type: 'POST',
url: _url,
data: {name: name, pass: pass},
dataType: 'jsonp',
beforeSend: function(){
if((!name) || (!pass)){
notify('error','Kérlek tölts ki minden adatot!');
return false;
}else{
$("#loginForm #loginBtn").prop("disabled", true);
}
},
success: function(data){
if(data[0].true == 'true'){
window.localStorage["username"] = name;
window.localStorage["password"] = pass;
$.mobile.changePage("#wall",{transition:"slide", reverse:false});
}else{
$('#loginForm #name').val("");
$('#loginForm #pass').val("");
notify('error','Hibás adatok!');
}
},
error: function(err){
//átírni ha a cordovajs be lesz szúrva!!!
alert('Hiba: '+err.message);
}
});
$("#loginForm #loginBtn").prop("disabled", false);
return false;
}
//02
function showMessageSuccess(message){
if(message=="") return;
$.ajax({
url: baseUrl+"Home/showMessage/SUCCESS",
type: "GET",
data: {message: message},
success: function(result){
$("#message").append(result);
},
error: function(error){
log("ERROR: showMessageSuccess error!");
}
});
}
//03
$(document).ready(function() {
$("#mobile").on("keyup change", function(){
var mobile = $(this).val();
var formURL = "http://www.nextadmission.com/form/mobile_check";
$.ajax({
url : formURL,
type : "POST",
data : { mobile_no : mobile},
success : function(data){
if(data == 1){
$(".chk").text("This user already Exists!!");
$(".submit").attr('disabled','disabled');
$(".chk").addClass("red");
}else {
$(".chk").text("");
$(".chk").removeClass("red");
$(".submit").removeAttr('disabled','disabled');
}
}
});
});
//alert("Hello! welcome");
});
//03// The difference between ‘return false;’ and ‘e.preventDefault();’
->prevents the browser from performing the default action for that link.
$("a").click(function() {
$("body").append($(this).attr("href"));
return false;
})
//or
$("a").click(function(e) {
$("body").append($(this).attr("href"));
e.preventDefault();
})
->So below code is almost same;
function() {
return false;
}
// IS EQUAL TO
function(e) {
e.preventDefault();
e.stopPropagation();
}
->Details about return false:
$('a').click(function () {
callFunction();
return false;
});
->The event.stopPropagation() stops the click event from bubbling (being affected the parent elements) to the parent elements.
->The return false will return false to the click-event. That tells the browser to stop following events, like follow a link. But the function will call. Javascript runs from top to bottom style.
->The main differece is return false works both e.stopPropagation(); and e.preventDefault();
//04//
If you're posting something like:
{"name":"John Doe"}
and expecting back:
{"success":true}
Then you should have:
var data = {"name":"John Doe"}
$.ajax({
dataType : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
success : function(result) {
alert(result.success); // result is an object which is created from the returned JSON
},
});
//05//
If you're expecting the following:
<div>SUCCESS!!!</div>
Then you should do:
var data = {"name":"John Doe"}
$.ajax({
dataType : "html",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
success : function(result) {
jQuery("#someContainer").html(result); // result is the HTML text
},
});
//06//
One more - if you want to post:
name=John&age=34
Then don't stringify the data, and do:
var data = {"name":"John", "age": 34}
$.ajax({
dataType : "html",
contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
data : data,
success : function(result) {
jQuery("#someContainer").html(result); // result is the HTML text
},
});
//07// Ajax Error and Success Msg
$('#lnkSuccess').click(function (e) {
e.preventDefault();
getSuccessOutput();
});
$('#lnkError').click(function (e) {
e.preventDefault();
getFailOutput();
});
// On click, get the ajax success output
function getSuccessOutput() {
$.ajax({
url: '/echo/js/?js=Hello%20World 2.0!',
complete: function (response) {
console.log(response);
$('#post').html(response.responseText);
},
error: function (jqXHR, exception) {
getErrorMessage(jqXHR, exception);
},
});
}
// On click, get the ajax error output
function getFailOutput() {
$.ajax({
url: 'some_unknown_page.html',
success: function (response) {
$('#post').html(response.responseText);
},
error: function (jqXHR, exception) {
console.log(jqXHR);
getErrorMessage(jqXHR, exception);
},
});
}
// This function is used to get error message for all ajax calls
function getErrorMessage(jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$('#post').html(msg);
}
//08// For sending files
var fd = new FormData();
fd.append( 'file', input.files[0] );
$.ajax({
url: 'http://example.com/script.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
//09// For sending files another process
$('form').submit(function (e) {
var data;
data = new FormData();
data.append('file', $('#file')[0].files[0]);
$.ajax({
url: 'http://hacheck.tel.fer.hr/xml.pl',
data: data,
processData: false,
type: 'POST',
// This will override the content type header,
// regardless of whether content is actually sent.
// Defaults to 'application/x-www-form-urlencoded'
contentType: 'multipart/form-data',
//Before 1.5.1 you had to do this:
beforeSend: function (x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("multipart/form-data");
}
},
// Now you should be able to do this:
mimeType: 'multipart/form-data', //Property added in 1.5.1
success: function (data) {
alert(data);
}
});
e.preventDefault();
});
//10// Ajax with short version
PHP + HTML
<?
print_r($_POST);
print_r($_FILES);
?>
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
jQuery + Ajax
$("form#data").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Short Version
$("form#data").submit(function() {
var formData = new FormData($(this)[0]);
$.post($(this).attr("action"), formData, function(data) {
alert(data);
});
return false;
});
//11// Difference between FormData($(this)[0]) and $(this).serialize()
var formData = new FormData($(this)[0]);
console.log(formData);
var formDataSerialized = $(this).serialize();
console.log(formDataSerialized);
//For file
var formData = new FormData();
var files = $(input)[0].files;
formData.append("quotation", document.getElementById("input_excel_file_buyer_quotation").files[0]);
->FormData types:
// Files
formData.append(name, file, filename);
// Blobs
formData.append(name, blob, filename);
// Strings
formData.append(name, value);
//12/Image upload with Ajax complete example
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form enctype="multipart/form-data">
<input type="file" id="image" name="image" accept="Image/*" />
<input type="submit" id="submit" name="" value="Upload" />
</form>
<script>
$('#submit').click(function (event) {
event.preventDefault()
var file = $('#image').get(0).files[0];
var formData = new FormData();
formData.append('file', file);
$.ajax({
url: '/test/file_capture',
//Ajax events
beforeSend: function (e) {
alert('Are you sure you want to upload document.');
},
success: function (e) {
alert('Upload completed');
},
error: function (e) {
alert('error ' + e.message);
},
// Form data
data: formData,
type: 'POST',
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
return false;
});
</script>
//Prevent Form submit or Stop form submit
$("form").submit(function(e) {
e.preventDefault();
var self = this, //DOM object
tray = $('select[name=tray_id]').val();
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false
}).done(function(result) {
if (result == "") self.submit();
}).fail(function() {
alert('error');
});
});
=====================
$("form").off('submit'function(){
});
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment