I'm very new at this. I've read books to learn javascript and HTML, so unfortunately I haven't learn much about this.
I never used AJAX before, so not sure how it works, searched online, but find all examples too complicated.
Basically what I want to do is save a playlist (although not with cookies). Something everyone can see and add-on to it (similarly to a comments section).
This is just an example, I'm doing something else, but the html + js would be a bit big. Just want to know how I would do it on this, so that I could understand it (hopefully) and apply it elsewhere.
This would be the body and below it the code I have (currently all my code is in [head]):
<body>
<form>
<input type="text" id="songInput" size="40" placeholder="Song Name">
<img id="addButton" src="button.png">
</form>
<ul id="playlist"></ul>
</body>
<script>
window.onload = load;
function load() {
var button = document.getElementById("addButton");
button.onclick = buttonClick;
}
function buttonClick() {
var text = document.getElementById("songInput");
var song = text.value;
var button = document.getElementById("addButton");
var add = document.createElement("li");
add.innerHTML = song;
var ul = document.getElementById("playlist");
ul.appendChild(add);
}
</script>
First you have to understand what AJAX is. AJAX is not a "tool" that you can use, instead, it's a name for the techniques (asynchronous JavaScript + XML). Basically it means "getting/posting data from/to server."
In vallina JavaScript, XMLHttpRequest lets you send and receive data to and from a server:
var xhr = new XMLHttpRequest(); //Create an XMLHttpRequest object
xhr.open('get', url); //Set the type and URL
xhr.onreadystatechange = function(){ //Tell it what to do with the data when state
// changes
if(xhr.readyState === 4){ //4 is the code for "finished"
if(xhr.status === 200){ //Code 200 means "OK"
//success
var data = xhr.responseText; //Your data
}else{
//error //Deal with errors here
}
}
};
xhr.send(null); //After finished setting everything, send the
// request. null here means we are not send-
// ing anything to the server
It might look complicated, and xhr is repeated quite a lot. Not to mention the problems that we have to deal with when executing in IE.
There is solution for that. We will use libraries to simplify the process and let it do the hard works for us.
In jQuery, this is what you have to do to for a basic XMLHttpRequest:
$.ajax({
url: url,
data: { /*data here*/ },
type: /*"GET" or "POST"*/
}).done(function(data){
//success
}).fail(function(){
//error
});
//Not complicated at all with jQuery
Since AJAX is a group of techniques to send/receive data, there're more ways to do the "same" thing. You might realize the code above only works for URL that has the same domain (pages on your server). To bypass that limitation, there's another technique called JSONP. Sounds fancy, but what it means is simply "using the <script> tag to get pass that limitation". And of course, jQuery got you covered:
$.ajax({
url: url,
data: { /*data here*/ },
type: /*"GET" or "POST"*/,
dataType: "JSONP" //specifying dataType to be JSONP
}).done(function(data){
//success
});
Here is a simple example of getting content off Wikipedia using JSONP: http://jsfiddle.net/DerekL/dp8vtjvt/
With a normal XMLHttpRequest call to Wikipedia's server would not work. However by exploiting the fact that script tags are not restricted by the Same-Origin Policy we can achieve the same thing. Note that for JSONP to work, the server must be programmed internally to allow returning a JSON with wrapped callback call.
Related
I have a website where I need to update a status.
Like for a flight, you are departing, cruise or landed.
I want to be able to refresh the status without having my viewers to have and reload the whole page. I know there is a way to do it with AJAX and jQuery, but I don't have any understanding of how that works. I also don't want them to have and click a button.
If anybody knows how that would be done I much appreciate it!
This is typically achieved with a technique called AJAX. This technique loads data asynchronously (in the background) so it can update your content without needing to reload the page.
The easiest way to implement AJAX is with the jQuery load() method. This method provides a simple way to load data asynchronous from a web server and place the returned HTML into the selected element. The basic syntax of this method is: $(selector).load(url, data, complete); where the arguments are:
selector the existing HTML element you want to load the data into
url a string containing the URL to which the request is sent
data (optional) a plain object or string that is sent to the server with the request
complete (optional) a callback function that is executed when the request completes
The required URL parameter specifies the URL of the file you want to load.
The optional data parameter allows you to specify data (i.e. key/value pairs) that is sent to the web server along with the request. The optional complete parameter can be used to reference a callback function. The callback is fired once for each selected element.
A visualisation:
A simple example of using load(), where we load data dynamically when a button is pressed:
DEMO
// no need to specify document ready
$(function(){
// optional: don't cache ajax to force the content to be fresh
$.ajaxSetup ({
cache: false
});
// specify loading spinner
var spinner = "<img src='http://i.imgur.com/pKopwXp.gif' alt='loading...' />";
// specify the server/url you want to load data from
var url = "http://fiddle.jshell.net/dvb0wpLs/show/";
// on click, load the data dynamically into the #result div
$("#loadbasic").click(function(){
$("#result").html(spinner).load(url);
});
});
If you don't want to use the jQuery library, you can also use plain Javascript. Loading content is slightly more difficult that way. Here is an example of how to do it with javascript only.
To learn more about AJAX, you can take a look at https://www.w3schools.com/xml/ajax_intro.asp
Suppose you want to display some live feed content (say livefeed.txt) on you web page without any page refresh then the following simplified example is for you.
In the below html file, the live data gets updated on the div element of id "liveData"
index.html
<!DOCTYPE html>
<html>
<head>
<title>Live Update</title>
<meta charset="UTF-8">
<script type="text/javascript" src="autoUpdate.js"></script>
</head>
<div id="liveData">
<p>Loading Data...</p>
</div>
</body>
</html>
Below autoUpdate.js reads the live data using XMLHttpRequest object and updates the html div element on every 1 second. I have given comments on most part of the code for better understanding.
autoUpdate.js
window.addEventListener('load', function()
{
var xhr = null;
getXmlHttpRequestObject = function()
{
if(!xhr)
{
// Create a new XMLHttpRequest object
xhr = new XMLHttpRequest();
}
return xhr;
};
updateLiveData = function()
{
var now = new Date();
// Date string is appended as a query with live data
// for not to use the cached version
var url = 'livefeed.txt?' + now.getTime();
xhr = getXmlHttpRequestObject();
xhr.onreadystatechange = evenHandler;
// asynchronous requests
xhr.open("GET", url, true);
// Send the request over the network
xhr.send(null);
};
updateLiveData();
function evenHandler()
{
// Check response is ready or not
if(xhr.readyState == 4 && xhr.status == 200)
{
dataDiv = document.getElementById('liveData');
// Set current data text
dataDiv.innerHTML = xhr.responseText;
// Update the live data every 1 sec
setTimeout(updateLiveData(), 1000);
}
}
});
For testing purpose: Just write some thing in the livefeed.txt - You will get updated the same in index.html without any refresh.
livefeed.txt
Hello
World
blah..
blah..
Note: You need to run the above code on the web server (ex: http://localhost:1234/index.html) not as a client html file (ex: file:///C:/index.html).
You can read about jQuery Ajax from official jQuery Site:
https://api.jquery.com/jQuery.ajax/
If you don't want to use any click event then you can set timer for periodically update.
Below code may be help you just example.
function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
window.setTimeout(update, 10000);
});
}
Above function will call after every 10 seconds and get content from response.php and update in #some_div.
If you want to know how ajax works, it is not a good way to use jQuery directly. I support to learn the native way to send a ajax request to the server, see something about XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://some.com");
xhr.onreadystatechange = function () {}; // do something here...
xhr.send();
I'm kind of new to using ajax but I've been largely successful. Most of my ajax calls look very similar to this:
function saveQueryProf(){
var currentDate = new Date();
var date=currentDate.getDate()+'/'+(currentDate.getMonth()+1)+'/'+currentDate.getFullYear();
$.ajax({
type: "POST",
url: "API.php",
data: { method: "createQueryProfile",
prof_name: $('#nameTxt').val(),
prof_SQL: $('#sqlTxt').val(),
date: date
},
datatype: "json"
}).done(function(returnresult) {
})
}
Using the $.ajax({ method. However, any time I see someone using "ajax" on youtube or other sites, their code looks more like this:
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();
}
I realize that these are doing different things, but what is the difference in these 2? And when I'm looking for answers online how could I find an answer that is more along the lines of the first style?
The first example, using $.ajax(), is specific to jQuery. It's a lot simpler than the built-in Javascript API, XMLHttpRequest. XMLHttpRequest doesn't require any external libraries to use, though it's more difficult. $.ajax() relies on XMLHttpRequest.
Your code requires the jQuery library to work (that's where $ and $.ajax come from). Their code is using XMLHttpRequest directly, which is built in to JavaScript, so it doesn't need any libraries. If you want your AJAX code to depend on jQuery, then just include it as a search term.
I saw that the question was already answered, but I think that more information can be added.
In your first example you are using jQuery ($.ajax call). You will need to add this library to your website in order to make it work. The easiest way is to add a tag with jQuery CND to your website.
The second example is using vanilla JavaScript, the XMLHttpRequest. It has more complex syntax (a strange mixture of upper and lowercase characters), but you don't need to add anything to the site. It will do the work, and once you are used to the syntax it might be all you need.
Third option that I have used for AJAX request is the fetch() method. Like XMLHttpRequest it is build in in the JavaScript language. fetch() has very simple syntax and allows easy use of promises. You might need promises if you will be making requests that will not return data immediately. Here's more information on fetch:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Fourth option that I've used for AJAX is Axios library. If you are including jQuery only for AJAX requests Axios is probably better choice. More read on Axios: https://github.com/axios/axios
If you want to dig a bit more on the differences and pros/cons between fetch() and XMLHttpRequest take a look on this thread:
Fetch API vs XMLHttpRequest
Shortly Ajax is an extension method which defined in JQuery for factory class XmlHttpRequest.
I am working on a scenario, where i need to cancel third party library request based on some condition and then unblock if condition evaluates to false. Let us assume that third party URL is being loaded with following URL:
https://cdn-thirdparty.com/...
Now, once it is loaded, it captures user clicks on the application and sends data as another URL:
https://cdn-info-thirdpart.com/...
Now, say i want to block all the requests to URL which contains thirdparty in it.. How do i achieve this in Vanilla Javascript...
P.S: I do not have access to remove the library from code, instead i have to do some engineering that requests are getting blocked based on some conditions(we can assume any) and then getting unblocked on falsy condition.
The code i tried to intercept all XMLHttpRequest is as below and i do get URL, method of call but i need to block it now and then unblock.
let oldXHROpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
// do something with the method, url and etc.
this.addEventListener('load', function() {
// do something with the response text
console.log('load: ' + url, method);
});
return oldXHROpen.apply(this, arguments);
}
Source of above code: https://medium.com/#gilfink/quick-tip-creating-an-xmlhttprequest-interceptor-1da23cf90b76
I've tried to search it through but not getting a starting point of how to approach AJAX in WordPress (or as a concept in whole), how is it different from jQuery, or is it a different/same module?
Why do we use it when we have jQuery (what circumstances forces us to use it?).
Should I learn jQuery basics first, then AJAX, or other way around?
You cannot really compare jQuery, AJAX and WordPress in this way:
jQuery is a JavaScript library designed to simplify the client-side scripting of HTML
AJAX is a technique to send data to, and retrieve data from, a server asynchronously
Wordpress is a blogging platform
To illustrate the point (with a very simple example), say you had a JavaScript event handler that was triggered when a form was submitted:
var f = document.getElementById("myForm");
f.onsubmit = doSomething;
You could have the event handler prevent the default submit action, instead making an AJAX request to a PHP script, optionally passing it some data (form values etc), then doing something with the response.
This has the advantage that the page is not refreshed, giving it a snappier, more responsive feel and generally making for a better user experience.
Here's how you'd implement it in plain JS:
var f = document.getElementById("myForm");
f.onsubmit = function(e){
e.preventDefault();
var r = new XMLHttpRequest();
r.open("POST", "submit.php", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
console.log(r.responseText);
};
r.send("a=1&b=2&c=3");
}
Now, as mentioned, jQuery is a JavaScript library, that just adds a layer of syntactic sugar and smooths out browser incompatibilities.
The same code using jQuery:
var f = $("#myForm");
f.on("submit", function(e){
e.preventDefault();
$.ajax({
url: "submit.php",
type: "POST",
data: "a=1&b=2&c=3",
success: function(d) {
console.log(d);
}
});
});
I'm not a very experience programmer and have been learning HTML/CSS/JS on the fly. I've been trying to parse XML using jQuery AJAX methods with absolutely no luck.
Here is my code in use: http://jsfiddle.net/Kb5qj/1/
And here is my code in plain sight:
$(document).ready(function() {
var divid = "#xmlcontent"
function parseXML(xml) {
$(divid).empty();
$(xml).find("CD").each(function() {
var artist = $(this).find("ARTIST").text();
var title = $(this).find("TITLE").text();
$(divid).append("<li>" + artist + " - " + title + "</li>");
});
}
function printError() {
$(divid).html("An error occurred");
}
$.ajax({
type: "GET",
url: "www.w3schools.com/ajax/cd_catalog.xml",
dataType: "xml",
success: parseXML,
error: printError
});
});
I don't know what the problem could be. I have written and re-written and copy/pasted that $.ajax call many many times, but no matter what I do nothing ever happens. Help me please?
like I mentioned it will fail on jsfiddle as they dnt actually send the get request. here is the api on how to achieve the same: http://doc.jsfiddle.net/use/echo.html
If you try the same on your local system it will fail probably cos you are making a cross domain request and your browser natively blocks such requests. That is where jsonp comes it to play its to retrieve json data over cross domains..
You can hack it a little to do the same for js.. here is a SO post about the same: Is there an existing tool for jsonp like fetching of xml in jquery?
With a little bit of fudging, everything in the parsing seems to work fine. Check out this JSFiddle.
You can't use get requests from JSFiddle, but I mocked up the XML into HTML. You may want to try placing your XML document into the DOM to help suss your issue.