Last active
April 28, 2021 16:04
-
-
Save josanua/391067721fe84415f50c5b56f8e81304 to your computer and use it in GitHub Desktop.
ajax jquery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://www.w3schools.com/jquery/jquery_ref_ajax.asp | |
Method Description | |
// jQuery | |
$.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 | |
$.parseJSON() - ! Deprecated in version 3.0, use JSON.parse() instead, it's Vanilla JS. Takes a well-formed JSON string and returns the resulting JavaScript value | |
$.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 | |
// vanilla JS | |
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 | |
// description | |
$.ajax({ | |
// The 'type' property sets the HTTP method | |
// Any value other than GET, POST, HEAD (eg. PUT or DELETE methods) will initiate a preflight request | |
type: 'GET', | |
// The Target Domain URL to make the request to | |
url: 'http://targetdomain.com', | |
// The 'contentType' property sets the 'Content-Type' header | |
// The JQuery default for this property is | |
// 'application/x-www-form-urlencoded; charset=UTF-8' | |
// If you set this value to anything other than | |
// application/x-www-form-urlencoded, multipart/form-data, or text/plain, | |
// you will trigger a preflight request | |
contentType: 'text/plain', | |
xhrFields: { | |
// The 'xhrFields' property sets additional fields on the XMLHttpRequest | |
// This can be used to set the 'withCredentials' property | |
// Set the value to 'true' to pass cookies to the server | |
// If this is enabled, your server must respond with the header | |
// 'Access-Control-Allow-Credentials: true' | |
// Remember that IE <= 9 does not support the 'withCredentials' property | |
withCredentials: false | |
}, | |
headers: { | |
// Set custom headers | |
// If you set any non-simple headers, your server response must include | |
// the headers in the 'Access-Control-Allow-Headers' response header | |
}, | |
success: function() { | |
// Handler for a successful response, do something with the response.Text | |
}, | |
error: function() { | |
// Error handler | |
// Note that if the error was due to an issue with CORS, | |
// this function will still be triggered, but there won't be any additional information about the error. | |
} | |
}); | |
// Standard JS functions | |
window.onload = function(){ | |
var inp_mail = document.querySelector('input[id=email]'); | |
var inp_pass = document.querySelector('input[id=pwd]'); | |
document.querySelector('#button').onclick = function(){ | |
var params = 'mail=' + inp_mail.value + '&pwd=' + inp_pass.value; | |
ajaxPost(params); | |
} | |
} | |
function ajaxPost(params){ | |
var request = new XMLHttpRequest(); | |
request.onreadystatechange = function(){ | |
if(request.readyState == 4 && request.status == 200){ | |
document.querySelector('#response').innerHTML = request.responseText; | |
} | |
} | |
request.open('POST', 'ajax.php '); | |
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); | |
request.send(params); | |
} | |
// ********************************************************* // | |
// Some functions | |
$.getJSON('data.json', function (data) { | |
console.log(data); | |
}) | |
// Tested and implemented | |
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" id="ns-form-guestbook"> | |
<span>*</span> | |
<input type="text" placeholder="Subiect" name="subject" ><br> | |
<input type="text" placeholder="E-mail" name="email"><br> | |
<textarea name="message" id="mesage" cols="6" rows="1" placeholder="Mesajul"></textarea> | |
<input type="button" value="Trimite" class="upper" id="ns-form-gestbook-button"> | |
</form> | |
<div id="response"></div> | |
</div> | |
// jQuery library | |
$(document).ready(function(){ | |
$("#ns-form-gestbook-button").click(function(){ | |
var formValues = $("#ns-form-guestbook").serialize(); | |
$.ajax({ | |
cache: false, | |
type:"POST", | |
url: "<?php echo (get_template_directory_uri()) ?>/inc/ns-guestbook/worker.php", | |
data: formValues, | |
dataType: 'html', | |
error: function (xhr){ | |
console.log ("Error - XHR Status:" + xhr.status + "; " + xhr.statusText); | |
$('#response').text("Error - generated by JS Script"); | |
}, | |
success: function(html){$('#response').html(html);} | |
//success: function(data){console.log(data);}, | |
complete: function(xhr) { | |
console.log(xhr.responseText); | |
$("#confirm-subscribe-modal").modal("show"); | |
$("#subscribe-form")[0].reset(); | |
} | |
}); | |
return false; | |
}); | |
}); | |
// reload page after AJAX result | |
location.reload(); | |
// Download result. from dompdf | |
https://github.com/barryvdh/laravel-dompdf/issues/404 | |
$.ajax({ | |
cache: false, | |
type: 'POST', | |
url: 'yourURL' | |
contentType: false, | |
processData: false, | |
data: yourdata, | |
//xhrFields is what did the trick to read the blob to pdf | |
xhrFields: { | |
responseType: 'blob' | |
}, | |
success: function (response, status, xhr) { | |
var filename = ""; | |
var disposition = xhr.getResponseHeader('Content-Disposition'); | |
if (disposition) { | |
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; | |
var matches = filenameRegex.exec(disposition); | |
if (matches !== null && matches[1]) filename = matches[1].replace(/['"]/g, ''); | |
} | |
var linkelem = document.createElement('a'); | |
try { | |
var blob = new Blob([response], { type: 'application/octet-stream' }); | |
if (typeof window.navigator.msSaveBlob !== 'undefined') { | |
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed." | |
window.navigator.msSaveBlob(blob, filename); | |
} else { | |
var URL = window.URL || window.webkitURL; | |
var downloadUrl = URL.createObjectURL(blob); | |
if (filename) { | |
// use HTML5 a[download] attribute to specify filename | |
var a = document.createElement("a"); | |
// safari doesn't support this yet | |
if (typeof a.download === 'undefined') { | |
window.location = downloadUrl; | |
} else { | |
a.href = downloadUrl; | |
a.download = filename; | |
document.body.appendChild(a); | |
a.target = "_blank"; | |
a.click(); | |
} | |
} else { | |
window.location = downloadUrl; | |
} | |
} | |
} catch (ex) { | |
console.log(ex); | |
} | |
} | |
}); | |
// JSON - Using JSON with PHP and JavaScript | |
// --- Define AJAX Filter Func. --- // | |
function AjaxFilterWorker (arr_of_cards = []) { | |
let checked_inputs_json_terms = JSON.stringify(arr_of_cards); | |
// let checked_inputs_json_terms = [[56, 58]]; | |
// checked_inputs_json_terms = JSON.stringify(checked_inputs_json_terms); | |
let data = { | |
action: 'filter', | |
terms_ids: checked_inputs_json_terms, | |
tax_name: tax_name, | |
post_type_name: post_type_name | |
} | |
console.log(data.terms_ids) | |
$.ajax({ | |
url: wpAjax.ajaxUrl, | |
data: data, | |
dataType: 'json', | |
type: 'get', | |
beforeSend: function() { | |
$('#filter-loading-spiner').addClass("d-flex"); | |
}, | |
success: function (xhr) { | |
// hide default html | |
tag_default_products.hide() | |
// show generated html search results | |
tag_search_results.show().html(xhr.postsHtml) | |
// write post number | |
tag_posts_number.text(xhr.foundPosts) | |
// console.log(xhr.postsHtml); | |
}, | |
error: function (xhr) { | |
console.log('Server error filter func: ' + xhr) | |
} | |
}).done(function(xhr){ // hide spinner | |
$('#filter-loading-spiner').removeClass("d-flex").addClass("d-none"); | |
}); // end ajax | |
} | |
{/* AJAX function on button click */} | |
// Check if Document is loaded | |
document.addEventListener("DOMContentLoaded", function(event) { | |
jQuery(document).ready(function ($) { | |
console.log('jQuery Loaded'); | |
$('#btn-synchronize-hapigood').on('click', function (e) { | |
let $this = $(e.currentTarget); | |
e.preventDefault($this); | |
console.log('clicked'); | |
$.ajax({ | |
url: "", | |
cache: false, | |
type: 'POST', | |
data: { | |
generatePdf: JSON.stringify(), | |
}, | |
// dataType: 'html', | |
complete: function (xhr) { | |
// console.log('Complete Response: ' + xhr.responseText); | |
}, | |
}); // end AJAX | |
}); | |
}); // end jQuery document ready | |
}); // end main wrapp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment