I have been working with AJAX, JSON and JSONP for the last few months, and now I am trying to revisit and build my basics. AJAX is Asynchronous JavaScript And XML, assuming that XML is the data format in which the server returns the data. If no data type is specified, it actually comes back as plain text. So if I am ingesting a JSON feed using the XMLHttpRequest object, can I still call it an AJAX call or should I call it an asynchronous JavaScript call??
ex: $.getJSON("data.json", function(data){
console.log(data);
})
Just a random question to make sure that I know what I am talking about, mainly when I talk to developers who are specific about the terms that I use and the context that I use them in.
The term AJAX has come to represent any networking call made from within a page using javascript (other than a websocket), whether the returned data is XML or not. In fact, it's now common to get JSON as the returned data type (a format that wasn't even standard back when the term AJAX was coined).
So ... it works perfectly fine to refer to a call as an AJAX call even though the returned data type is something other than XML.
Related
I'm want to (or think I need to) use AJAX to accomplish what I intend.
When clicking on a specific link in a list of links, I want to fill the HTML markup below with content of specific subpages. The data is naturally somewhere in the database and actually easily accessible with the CMS's API (I'm using Processwire).
I'm quite new to coding and especially AJAX and all documentation I find online only mention it in combination with a JSON file that would be loaded via AJAX.
However, I don't have a JSON file on the server, that means, according to my understanding, I would need to
store the data I need in a multidimensional php array,
use json_decode to create and then save that JSON-file on the server,
load that file via AJAX and process through more JS.
Let alone keep that JSON-file updated (or create a new one and delete the old one?) since new content will arrive periodically. It seems unnecessarily complicated to me, but what do I know.
There's got to be a better way…
Any help is appreciated.
AJAX is simply a way to make a request to the web server for information.
When you make an AJAX request you ask for a response from a file on a server. So, you can send an AJAX request to a PHP script for-instance.
The PHP script could return anything, JSON is common and very widely used response format, but XML might be another one you've encountered.
So, your request for information is made using AJAX, and the response you get back is JSON.
You don't need to store a JSON file on your server. You just need to make an AJAX request that returns current data in JSON format.
AJAX allows you to do asynchronous HTTP requests.
You can of course ask for a json file, but you can also (for example) call an API.
I suggest you start by reading the the getting started guide for AJAX in MDN:
https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started
If all I want to do is submit a form to a PHP processor with POST data and get the result, is there any reason to use the ajax method over the jQuery load method?
Using Ajax requires a bunch of code versus something very simple on one line in jQuery like this:
$("#myDIV").load("myProcessor.php", {field1: target.value});
Hmmm, maybe this only works well with one field? Sorry, just getting back into JS.
$(element).load(...) will automatically insert the server response into the selected element as html (jQuery documentation for .load()). This might result in your server exposing information about the request directly to the user, which is probably not what you're looking to do.
$.ajax() also allows very fine control over what happens during the request. You can accurately intercept exceptions and produce a callback when the request finishes succesfully. These are all reasons to use $.ajax() over $(element).load(...). However, if your only concern is sending the data in the POST header and working with the response, then using $.post with a callback function will probably be the simplest approach. http://api.jquery.com/jQuery.post/
The .load method is is roughly equivalent to $.get(url, data,
success) (src).
The .get method is a shorthand Ajax
function (src).
For a simple ajax call, .load is appropriate. Use .ajax if you want to deal with specials parameters.
PS: If you don't want a fat framework like jQuery, look here : http://microjs.com/#ajax
From jQuery website about load
This method is the simplest way to fetch data from the server. It is
roughly equivalent to $.get(url, data, success) except that it is a
method rather than global function and it has an implicit callback
function. When a successful response is detected (i.e. when textStatus
is "success" or "notmodified"), .load() sets the HTML contents of the
matched element to the returned data.
you can read difference between load ajax on StackOverflow.
But, load is not for submitting a form using post method. Both POST and GET are different methods and works differently, data submitted using GET method will be available in the $_GET array but not in the $_POST.
I'm trying to understand AJAX and JSON and I'm not sure I get it, there are methods and functions that are doing the same stuff...
You've got $.getJSON to retrieve JSON format data from server, and you have $.ajax + $.post + $.get + load() to send data data to the server?
Can I use all of those methods to send JSON data?
Really I'm confused! Help me figure this out.
All those are just shorthands for calling the $.ajax function.
load is for retrieving HTML and writing it to the DOM in one go. You want to load JSON.
get and getJSON use GET requests which are not well-suited for sending JSON data.
post does a POST request, but doesn't allow you to choose the contentType of the sent data
For sending JSON you should use the $.ajax function with its many options, see Send JSON data with jQuery.
An AJAX request is, at heart, an HTTP request. This is the same protocol which is used for all content on the Web (arguably, if it's not HTTP, it's not the Web) - loading a page, the images on the page, the CSS and JS includes, a submitted form, etc, etc.
As such, it inherits pretty much all of the flexibility of HTTP, meaning a generic function like jQuery.ajax ends up quite complex, with lots of options you don't normally need to worry about. This leads to the Shorthand Methods you mentioned, which bundle up common sets of options and functionality.
Among the things you might want to vary:
The "method" of the request: GET or POST (or less common ones like HEAD, PUT, DELETE...). A GET request is the simplest: request this URL, give me its contents; parameters to a GET request are shoved onto the "query string" of the URL. A POST request is how larger forms would be submitted on a normal page: the parameters are passed as a body of data separate from the URL and control headers; for an AJAX request this is often helpful to send a block of XML or JSON to a URL. This is a very broad overview, and there are many more distinctions in behaviour and meaning between the two.
The "content type" you want in the response (and, for a POST request, of the data you're sending). Not only does this tell both the server and the browser what data it is handling, ensuring it will pass it successfully, it can give jQuery (or whatever library) a hint of what to do next: if a call returns XML, you'll probably want to manipulate it as a DOM straight away; if it's JSON, you'll want to parse it as a JS object.
What you want to do once the data comes back. I've already mentioned parsing JSON or XML, but what if your response is actually a block of HTML that you want to inject straight into the parent page? Obviously you could do that yourself in the callback function, but again jQuery includes a shorthand form in the shape of .load().
All of the above are possible with jQuery.ajax, but you'd have to remember the parameters, even though you're falling into the same cases again and again, so chances are most of the time you'll be using whichever of the shorthands suits your needs at that moment.
My browser makes an ajax/json request to the server, which then calls out of several services to get data (taking various lengths of time) and then displays this data in the browser.
I could, wait for the server to complete and return all the data in one big go.
Ideally I would like it to return the data (json) whenever each of the individual calls completes. This way I can display them in the UI and if one of the service calls takes a long time, then the user can still look at the data, without looking at a blank screen.
I think its possible to get an ASP.NET web page or handler to send data back to the requesting client without buffering it.
But clientside, how can I process ajax response before its completed? Is this even possible?
I'm wondering if multipart MIME data type may be useful as well...?
Make a separate controller/function (depending on what backend you're using), and then make separate requests in your javascript. Since Javascript is asynchronous, results will display on your page as each function completes.
.NET pseudocode
public string Foo() {
string returnedJson = getFoo();
return returnedJson;
}
//Same thing for Bar and Bah
Then, in your Javascript (assuming you're using jQuery)
function onFooComplete() {
//In this function, display the data you get back from the server
}
$.get('/foo', function(res) {
onFooComplete(res);
});
For a more robust implantation, look into using a publish/subscribe methodology in your javascript. https://github.com/cowboy/jquery-tiny-pubsub is a very small but useful pub/sub implementation for jquery.
I want to show a list of options to the user when he/she clicks on an inputText component. I need to call a bean method by JavaScript using onclick attribute in IceFaces.
<ice:inputText id="inputText1" partialSubmit="true" value="" onclick="" />
How can I achieve this?
As #Neall said, you need to initiate an XMLHttpRequest and return the data to the client. There are many ways to do this and I don't know the framework you are referring to, but in general, you initiate the XMLHttpRequest passing some parameters -if needed- to a web method, for example, and then return the data in JSON format. When you issue the request it usually has a callback function for success and one for error. On the sucess event, you parse the JSON response and do whatever you need to do with it.
Look at here, for example:
http://elegantcode.com/2009/02/21/javascript-arrays-via-jquery-ajax-to-an-aspnet-webmethod/
It looks like you are trying to run server-side code when the user takes some action on the client side. You probably want to initiate an XMLHttpRequest.
The XMLHttpRequest basically just hits a URL, optionally returning some data to the browser. This is what people usually call AJAX. (For Asynchronous Javascript And XML - although people usually use JSON instead of XML.)