Tuesday, October 04, 2016

what is Ajax

well a jack stands for asynchronous javascript and xml but what does that
now when I was first learning web development I found the term ajax to be
particularly confusing
it seemed like some kind of library does it work with PHP how do i install a tax
on my server now it turns out Ajax is none of those things
Ajax is merely a web development technique used in order to send and
retrieve data in the background without refreshing a web page now to show you
what I mean let's start by taking a look at a real world ajax example and if we
had over to twitter.com and open up our timeline
after some time has passed you'll see a menu bar appear at the top of your
screen indicating that new tweets are available and if you wait even longer
you'll see that that number increases as more and more the people you follow post
something on Twitter
note that our page never fresh is entirely just that one menu bar
so to see what's going on in the background let's open up our chrome
developer tools and take a look at the network tab you can see that every 10
seconds Twitter's web page is making a new request to its servers and the
purpose of that request is to ask whether there are any new tweets in your
timeline again notice that the page never refreshes and that's because
rather than loading the data through the typical browser HTTP request initiated
view the URL bar
ajax request use JavaScript xmlhttprequest object in order to make
HTTP request behind the scenes to illustrate this if we open up the chrome
console and instantiate a new xmlhttprequest object saving it in the
variable X HR you can see that we have methods available such as open and send
and set headers and set response
everything that you would normally see in a traditional HTTP request
now as far as a service concerned these requests may be a JavaScript
xmlhttprequest are identical to normal request entered in the browser's URL bar
so with that primer on xhr request let's take a closer look at the request
Twitter's website is making and we can see that the request URL on the end .
was being sent to twitter.com / I / timeline and that the request contained
a query string with a set of parameters composed count equals 0 include
available features equals 1
these parameters tell the Twitter server what type of information were requesting
and the most relevant one for our purposes being the min
position value as this is the lowest twitter ID to return
now that we've analyzed the request let's take a closer look at the response
we select one of the request that contain new tweets we can see that
Twitter's in fact sending back Jason data
let's make it more readable but passing it through adjacent profire lot of this
isn't of much interest but the new tweets bar HTML key is what we want to
focus on it basically contains all the HTML of that new tweets bar that we saw
so basically what happens is the JavaScript running on Twitter's website
takes the Jason response grabs the content of the new tweets bar HTML key
and then uses javascript in order to replace existing new tweets bar with the
content just received in this entire process of making the request to the
server and updating the page with the response without reloading it is Ajax
now that we've taken a look at how Twitter uses Ajax and their web
let's go ahead and implement ajax in a practical example not a prior video i
made a really simple application called geo gram which uses google maps and
instagrams rest api is in order to display an Instagram image taken at your
specific location in its current state once you load the page that's it
in order to refresh the feed you need to reload the entire page
so let's add some ajax so that we can get that stream of images to update
automatically every five seconds
we'll begin by opening up the code from the last video and in order to simplify
our structure let's rename our geo Graham dot PHP file to index dot PHP now
when we launched pages built-in web server we can access our application at
the local host root of the port we specified which in this case was a
thousand turning out of the HTML markup since we renamed our PHP file
first let's go and update our form submissions action attribute in order to
point to the route instead of two are old geograph I'll next let's wrap the
image results of the diff container and give it an idea of images
this gives our JavaScript and easily accessible location to add our new
images as the images are pulled in from Instagram
we will insert them into this div let's also make things easier on ourselves by
adding the Instagram URL we're calling in PHP to a data attribute on our images
div and we'll call that URL as you can see in a minute we'll use javascript in
order to grab this URL and pass it on to our ajax request function looking at the
bigger picture for a minute
when making an AJAX request to the instagram api we'd ideally want to
request only those images that are new
since our previous request however looking at the documentation for the
instagram api is media search in . we can see that it does not support
pagination parameters the way that Twitter does
additionally there's no pagination details returned in the response body .
does support the undocumented parameters
max timestamp and min time stamp however those are not exact and they seem to
vary by blocks of up to 30 seconds
so what this means in practice is that there's no way to request only the new
data there for purposes of this demo will simply repeat our original request
and use JavaScript to identify which images are new and which images are
already on the page
so turning back to our HTML in order to make identifying new images easier on
let's say each image tags ID attribute equal to the idea instagram has assigned
it now that our markup is ready let's add the jquery library to our
jquery is an immensely popular JavaScript library which makes
manipulating HTML and making Ajax requests much simpler to keep things
simple will load jquery into your application by linking to the latest
copy on a content delivery network now when the browser's rendering the page
and reaches the script tag it will go out and download the jquery library and
loaded into memory so we can access its methods
finally let's add a script tag linking to a file where we'll put our custom
JavaScript code
so let's create that script file and open it up in our editor and we'll begin
by adding a function called it's ajax time and inside will first grab the URL
from the aforementioned data URL attribute and store it in the variable
URL then let's use jQuery is get Jason method in order to request that URL from
Instagram this get Jason method will make the xmlhttprequest and once
completed this callback function will be executed and the response to our API
request will be contained in the data variable to improve readability
let's just make a function call to a new function called add new images will
begin by looping through the response data using jquery each method if you
recall from the Instagram documentation the images fonts are contained under the
key data so will say for each data . data as index image then for each image
let's check and see if it's a new image will do that by making for the image ID
is not already
our dom by looking for a jquery object with an ID attribute that matches the
Instagram image ID if that object doesn't exist then its length will equal
0 therefore when its length equals 0 will add that images details to mark up
as a new image thing will create our markup for the new image by creating a
new jquery object which will fill the combination of HTML markup and the
results from our ajax request and then we'll use jQuery is prepared to method
to add it to our main images container for added style let's hide the image
first and then we'll fade it in the only thing left to do is set up our apt to
refresh the feed every five seconds to do that we use the set interval function
ok let's load
chanting we can see looking at the networking tab in our developer tools
that the xhr requests are firing every five seconds
great but wait a minute why isn't the page updating looking over at the
console we can see we're getting an error message indicating that our local
host isn't allowed access now that's because the xmlhttprequest protocol has
a same origin policy which restricts loading data from a different host here
because we're trying to load data from api instagram.com on HTTP / localhost we
violated that same origin policy
so here's the workaround we simply add a call back query parameter to our ajax
request URL and give it a value of ? and if we reload the page you can see that
it's now updating every five seconds
but what just happened to help you understand let's open up our API
requests in the browser and add a query parameter of callback equals test
now as you can see Instagram server sent back the same Jason response but this
time it was as a parameter of a function call
and as it should be no surprise that the function being called was test this
response format isn't what's known as Jason P and it's not subject to the same
origin policy but why is that the reason is because we're no longer making an xhr
request so the HR policies don't apply
looking at our application page again you can see nothing is coming up in our
xhr tab and instead if you look at the script tab you see the requests are now
coming up there instead
that's because when jquery see the callback parameter rather than making an
xhr requested ads our API request URL as the source of an HTML script tag
remember how we loaded the remote copy of the jquery library that was hosted on
jQuery is content delivery servers
that's exactly how these API requests are being sent as well illustrate this
further let's do exactly that and add our API URL as a script tag to our geo
grams HTML with a callback query parameter equal to test then we will
create a new function called test that takes a parameter of Jason and add that
to the console log
now we reload the page sure enough you can see that the JSONP response has been
loaded into our document scripts and heading over to console sure enough we
can see that our callback function test was executed by the JSONP response
opening up some of the nodes we can see our familiar instagram api response
so that's what a Jackson all about
and as you can see it can be a little confusing to beginners because
everything we did in this video is Ajax not just making the xhr jsonp request
but also the entire process of updating the page without refreshing in its
so if you have any questions hit me up in the comments below or on twitter at
the inverse from thank you so much for watching and I'll see you guys next time

No comments:

Post a Comment