The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative, hypermedia information systems. This is the foundation for data communication for the World Wide Web (i.e. internet) since 1990. HTTP is a generic and stateless protocol which can be used for other purposes as well using extensions of
Posts in Category: snippets
Ajax getHTTPObject function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
/*Usage * var request = getHTTPObject(); * if(request){ * AJAX CODE HERE * } * * If getHTTPObject returns false, the browser isn't Ajax compatible. The if * statement checks to see if it exists, then runs the code. */ function getHTTPObject() { var xhr = false;//set to false, so if it fails, do nothing if(window.XMLHttpRequest) {//detect to see if browser allows this method var xhr = new XMLHttpRequest();//set var the new request } else if(window.ActiveXObject) {//detect to see if browser allows this method try { var xhr = new ActiveXObject("Msxml2.XMLHTTP");//try this method first } catch(e) {//if it fails move onto the next try { var xhr = new ActiveXObject("Microsoft.XMLHTTP");//try this method next } catch(e) {//if that also fails return false. xhr = false; } } } return xhr;//return the value of xhr } |
1 2 3 4 5 6 7 8 9 10 |
function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; } }; xhttp.open("GET", "ajax_info.txt", true); xhttp.send(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Get file function grabFile(file) { var request = getHTTPObject(); //GET if (request) { request.open('GET', file, true); request.send(null); request.onreadystatechange = function(){ if (request.readyState != 4) return false; if (request.status == 200 || request.status == 304) { console.log(request.responseText); } }; } } |
AJAX – Send a Request To a Server
The XMLHttpRequest object is used to exchange data with a server.
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:
1 2 |
xhttp.open("GET", "ajax_info.txt", true); xhttp.send(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<html> <head> <script> function showHint(str) { if (str.length == 0) { document.getElementById("txtHint").innerHTML = ""; return; } else { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("txtHint").innerHTML = this.responseText; } }; xmlhttp.open("GET", "gethint.php?q=" + str, true); xmlhttp.send(); } } </script> </head> <body> <p><b>Start typing a name in the input field below:</b></p> <form> First name: <input type="text" onkeyup="showHint(this.value)"> </form> <p>Suggestions: <span id="txtHint"></span></p> </body> </html> |
File Upload in Ajax
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$("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
1 2 3 4 5 6 7 |
$("form#data").submit(function() { var formData = new FormData($(this)[0]); $.post($(this).attr("action"), formData, function(data) { alert(data); }); return false; }); |
1 2 3 4 5 6 7 8 9 10 11 |
$.ajax({ url: 'php/upload.php', data: $('#file').attr('files'), cache: false, contentType: 'multipart/form-data', processData: false, type: 'POST', success: function(data){ alert(data); } }); |
Audio autoplay
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
window.addEventListener('load', () => { // noinspection JSUnresolvedVariable let audioCtx = new (window.AudioContext || window.webkitAudioContext)(); let xhr = new XMLHttpRequest(); xhr.open('GET', 'audio-autoplay.wav'); xhr.responseType = 'arraybuffer'; xhr.addEventListener('load', () => { let playsound = (audioBuffer) => { let source = audioCtx.createBufferSource(); source.buffer = audioBuffer; source.connect(audioCtx.destination); source.loop = false; source.start(); setTimeout(function () { let t = document.createElement('p'); t.appendChild(document.createTextNode((new Date()).toLocaleString() + ': Sound played')); document.querySelector('.output').appendChild(t); playsound(audioBuffer); }, 1000 + Math.random()*2500); }; audioCtx.decodeAudioData(xhr.response).then(playsound); }); xhr.send(); }); |
reCAPTCHA Responsive Scaling
HTML
1 2 3 4 5 6 |
<div class="container"> <p>This captcha will scale when the browser window is smaller than its current width (304 px)</p> <form action="" method="get"> <div class="g-recaptcha" data-sitekey="6SSSSSSBIgEAplK2EWsVFkaE5o0DWUpsIs"></div> </form> </div> |
CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
* { box-sizing: border-box; } .container { max-width: 300px; background: #ccc; padding: 20px; } .g-recaptcha { transform-origin: left top; -webkit-transform-origin: left top; } |
Script
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
// Resize reCAPTCHA to fit width of container // Since it has a fixed width, we're scaling // using CSS3 transforms // ------------------------------------------ // captchaScale = containerWidth / elementWidth function scaleCaptcha(elementWidth) { // Width of the reCAPTCHA element, in pixels var reCaptchaWidth = 304; // Get the containing element's width var containerWidth = $('.container').width(); // Only scale the reCAPTCHA if it won't fit // inside the container if(reCaptchaWidth > containerWidth) { // Calculate the scale var captchaScale = containerWidth / reCaptchaWidth; // Apply the transformation $('.g-recaptcha').css({ 'transform':'scale('+captchaScale+')' }); } } $(function() { // Initialize scaling scaleCaptcha(); // Update scaling on window resize // Uses jQuery throttle plugin to limit strain on the browser $(window).resize( $.throttle( 100, scaleCaptcha ) ); }); |
Sample Ajax call
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
function ajaxCall() { this.send = function(data, url, method, success, type) { type = type || 'json'; var successRes = function(data) { success(data); }; var errorRes = function(e) { console.log(e); alert("Error found \nError Code: " + e.status + " \nError Message: " + e.statusText); }; $.ajax({ url: url, type: method, data: data, success: successRes, error: errorRes, dataType: type, timeout: 60000 }); } } function locationInfo(rootUrl) { // TODO:: BASE URL //var rootUrl = "https://healthxe.com/home/dropdownapi"; var call = new ajaxCall(); this.getCities = function(id) { $(".cities option:gt(0)").remove(); var url = rootUrl + 'home/dropdownapi?type=getCities&stateId=' + id; var method = "post"; var data = {}; $('.cities').find("option:eq(0)").html("Please wait.."); call.send(data, url, method, function(data) { $('.cities').find("option:eq(0)").html("Select City"); if (data.tp == 1) { $.each(data['result'], function(key, val) { var option = $('<option />'); option.attr('value', key).text(val); $('.cities').append(option); $('.cities').trigger("chosen:updated"); }); $(".cities").prop("disabled", false); } else { alert(data.msg); } }); }; this.getStates = function(id) { $(".states option:gt(0)").remove(); $(".cities option:gt(0)").remove(); var url = rootUrl + 'home/dropdownapi?type=getStates&countryId=' + id; var method = "post"; var data = {}; $('.states').find("option:eq(0)").html("Please wait.."); call.send(data, url, method, function(data) { $('.states').find("option:eq(0)").html("Select State"); if (data.tp == 1) { $.each(data['result'], function(key, val) { var option = $('<option />'); option.attr('value', key).text(val); $('.states').append(option); $('.states').trigger("chosen:updated"); }); $(".states").prop("disabled", false); } else { alert(data.msg); } }); }; this.getCountries = function() { var url = rootUrl + 'home/dropdownapi?type=getCountries'; var method = "post"; var data = {}; $('.countries').find("option:eq(0)").html("Please wait.."); call.send(data, url, method, function(data) { $('.countries').find("option:eq(0)").html("Select Country"); // console.log(data); if (data.tp == 1) { $.each(data['result'], function(key, val) { var option = $('<option />'); option.attr('value', key).text(val); $('.countries').append(option); $('.countries').trigger("chosen:updated"); }); $(".countries").prop("disabled", false); } else { alert(data.msg); } }); }; } |
Serialize Form to JSON
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
(function ($) { $.fn.serializeFormJSON = function () { var o = {}; var a = this.serializeArray(); $.each(a, function () { if (o[this.name]) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; }; })(jQuery); $('form').submit(function (e) { e.preventDefault(); var data = $(this).serializeFormJSON(); console.log(data); /* Object email: "value" name: "value" password: "value" */ }); |
or another approach
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function jQFormSerializeArrToJson(formid) { var serializedArr = $("form#" + formid).serializeArray(); var jsonObj = {}; jQuery.map(formSerializeArr, function(n, i) { jsonObj[n.name] = n.value; }); return jsonObj; } $('#formidlogin').submit(function(e) { e.preventDefault(); var data = jQFormSerializeArrToJson('formidlogin'); data = JSON.stringify(data), console.log(data); /* Object email: "value" name: "value" password: "value" */ }); |