Video tutorial illustrates fetching of JSON data using jQuery AJAX method, getJSON Since its an AJAX method, the data is fetched without the need for refresh of the browser.
Here we have a unordered list, without any list items in it. We’ll be fetching the list items from the JSON file using jQuery. A button, clicking upon which we would fetch the Data inside jSON file.
Starts with a opening brace and ends with a opening brace. In our example, we have taken two objects. p1 and p2 are keys. It’s values are present inside opening and closing brace. Each object has name, age and company info.
Once the user clicks on the button, we invoke $.getJSON method. First parameter we are passing is the URL of the json file. Next the call back function.
The call back function receives the jSON data which we have called as obj in our example. Using $.each() method we iterate through all the objects present in our json file and then split them into key => value pair.
Now using the value we fetch the name present inside each objects value.
Video Tutorial: Fetch JSON Data Using jQuery AJAX Method: getJSON
jSON & Database We can generate jSON data out of a database and then fetch it using jQuery and display it on our web browser without the need for the modification of any code. Whenever the json file or the database table data gets updated/modified, it instantly reflects on our web application.
Note: You must open the file from a server. localhost works file too. If you access the files directly from your computer folder, this application doesn’t work. So the files MUST be on a server.
Video tutorial illustrates insertion of data into MySQL database using jQuery and PHP, using AJAX method i.e., $.post() method of jQuery.
There are 5 shortcuts for AJAX in jQuery, ultimately calling ajax method, and by default configured to have different parameters. $.get $.post $.getJSON $.getScript $.load
Tutorial Theme: Insert Data Into Database Without Refreshing Webpage
In this tutorial we’ll illustrate $.post method of jQuery.
Here we have a form with an id called myForm, which has 2 input box. A button with id sub. And a span tag with an id of result.
Once the user enters his/her name, age and hits Save button, the information will be sent to userInfo.php file present in the action field, via post method.
Using AJAX technique, we would make sure the form doesn’t redirect to userInfo.php file after the submission, and we’ll display appropriate message to the user on index.html file itself after the user entered values has been processed by userInfo.php file.
We connect our application to mysql server using the user name root( and we leave password field empty, as we haven’t set any password to it on our machine ). Also select the database called test.
Create Database called test. A table user inside the database test. user table has 2 fields called name and age.
Once the user hits the Save button of our form in index.html, the information is being sent to userInfo.php
Where the user entered values are being copied to local variables $name and $age. Next a simple MySQL query is formed to insert the data into the tableuser.
Using mysql_query() standard php function, the MySQL query is being processed. Using if else conditional statements, we check if the process was successful or failed. Based on which we echo the result.
Once the user clicks on the button with the id sub, $.post() method is invoked. $.post() is a shortcut to $.ajax() method.
General Syntax: $.post( ‘pass_data_to_this_url’, ‘data’, ‘callback_function’ );
We fetch the URL from myForm form, from its action attribute. Serialize all the user entered input’s. SerializeArray makes the input into property: value pair. After the data is passed to the url and is being processed, the result will be returned back to the callback function and is caught in info variable, and is inserted inside the span tag using html() method – which is similar to innerHTML() method of JavaScript.
jQuery code: Disable Form Redirection my_script.js
Select the form and make sure to return false upon submission.
jQuery code: Clear Input Fields my_script.js
1
2
3
4
5
function clearInput() {
$("#myForm :input").each( function() {
$(this).val('');
});
}
function clearInput() {
$("#myForm :input").each( function() { $(this).val('');
});
}
Write a custom function. Select the input fields and set each of its value to none or empty. Call this function once the user clicks the submit button.
Video tutorial to read XML file using jQuery ajax method.
AJAX full form: Asynchronous JavaScript and XML We’ll also see the use of setTimeout() function.
Using AJAX technique, we fetch only the required data from the server without reloading the entire page.
In this video tutorial, we fetch the data present in XML format and display fetched content on the webpage and update it in real time, without reloading the html page.
HTML code index.html
1
2
3
4
5
6
7
8
9
10
<html>
<head><title>Reading an XML file using jQuery</title></head>
<body>
<ul></ul>
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>
<html>
<head><title>Reading an XML file using jQuery</title></head>
<body> <ul></ul>
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>
Here we have 1 ul tag. We’ll load the list items dynamically using jQuery, from XML file.
Here we have a base tag called corporate. Inside that we have employee details like name, age and company which is bound inside employee tag. Each employee will have his/her details inside separate/individual employee tag.
function corporateData() {
$.ajax({
url: "corporateData.xml",
dataType: "xml",
success: function(data) {
$("ul").children().remove();
$(data).find("employee").each( function() {
var info = '<li>Name: '+$(this).find("name").text()+'</li>
<li>Age: '+$(this).find("age").text()+'</li>
<li>Company: '+$(this).find("company").text()+'</li>';
$("ul").append(info);
});
},
error: function() { $("ul").children().remove();
$("ul").append("<li>There was an error baby!</li>"); }
});
}
function corporateData() {
$.ajax({ url: "corporateData.xml", dataType: "xml", success: function(data) { $("ul").children().remove(); $(data).find("employee").each( function() { var info = '<li>Name: '+$(this).find("name").text()+'</li> <li>Age: '+$(this).find("age").text()+'</li> <li>Company: '+$(this).find("company").text()+'</li>'; $("ul").append(info); }); }, error: function() { $("ul").children().remove(); $("ul").append("<li>There was an error baby!</li>"); } });
}
Here we write a custom jQuery function called corporateData. $.ajax() is a jQuery static method and it has a lot of properties. In this tutorial, we illustrate url, dataType, success and error properties. Specify the url from which the data has to be fetched, along with its data type. If the file gets parsed successfully, the function inside the success property gets executed. If there is an error, the error property function gets triggered.
Once the xml file gets parsed successfully, $.ajax method throws an object which contains xml file data. We catch this data with anonymous function present in success property. Next, we clear any previous data got attached to the unordered list of html document.
Using the object, we find each employee tags present inside the XML file, fetch individual name, age and company names and then append it to the unordered list.
Inorder to make sure our application fetches the fresh data from the XML file, we check the XML file after certain period of time. Using setTimeout() method of jQuery: setTimeout() takes two parameters, first one being the function names to be called and the second one being the time interval after which those functions has to be called.
using setTimeout() we have called itself( fetch() ) and corporateData() function. This makes sure, whenever the XML file gets updated, our application fetches the data and displays on our webpage, without refreshing the page.
jQuery File: call the functions to make it work my_script.js
Make sure to call both corporateData and fetch method once the page loads. This makes sure the XML data is fetched before fetch functions tries to re-fetch the things.
Note: Make sure you open the html file from a server(even from localhost), and not directly from a folder. XML and the files which are fetching XML data must be on the same server, otherwise XML data won’t be fetched.
Testing The Application To test this small application, open the index.html file from the server, and then add / modify / delete any entry. Once you save the XML file, the content of XML file must get updated on the html file immediately without the page(index.html) being reloaded.