With AJAX, when we perform a JSON request, we first have to pass the response received through eval
:
var quote=eval("(" + xhr.responseText + ")");
Afterwards, to use some information from it, one has to do some old-school JavaScript:
document.getElementById("textarea").value=xhr.responseText;
...or to use a specific piece of information we use createTextNode
like this:
// price is retrieved from PHP.
var text=document.createTextNode(price + ":" + quote.price);
Coming to jQuery, the same thing is as simple as this:
$.get("file.php",function(data){
var text=data.price;
});
Why do I need to use AJAX at all when there are AJAX methods available in jQuery itself?
I have no idea about the advanced things as to what AJAX can and jQuery can't or vice-versa. What are AJAX and jQuery each good for and when should I use which?
Remember, jquery is ajax framework library. Ajax is a asynchronous communication mechanism which can be implemented using XMLHttpRequest (xhr) or jquery. jQuery is library supported by third party. One of these mechanisms is enough to implement Ajax functionality.
jQuery is a javascript library that makes writing javascript easy in terms of cross browser issues and provides several utilities method. Ajax is one of the techniques in javascript by which you access some server side code and manipulate your dom with the results you get from it. jQuery provides cross browser issues free wrapper methods in case of AJAX also to perform the same thing. So jQuery is just a helping library which helps you achieve several things in a easier manner one of which can be ajax too.
jquery's ajax method is a great and powerful it can handle everything as you need.
in jquery there are various methods available to perform AJAX calls according to your requirements, but all of these are synonyms of ajax
method of jquery.
for the json you can use $.getJSON(url,[data],function(response){});
for posting data you can use `$.post(url,[data],function(response){});
for get request you can use `$.get(url,[data],function(){});
and if you want to use ajax method for all of these things you have to pass various arguments according to your requirement
$.ajax({
'url':you url,
'type':request type,
'data':your data,
'success':success handler function,
'error':error handler function,
/*and many more*/
)}
read jquery documentation for full details