jQuery Get Complete Guide for Beginners and Experts

jQuery Get Complete Guide for Beginners and Experts

The jQuery Get function is used to make AJAX calls and can be helpful to update a web page with no page reloading. It uses HTTP GET method to initiate an AJAX request and fetch data from the external pages.

Let us understand all about this method in details.

Syntax of jQuery Get Method

jQuery.get( url [, data ] [, success ] [, dataType ] )
Parameters:
Name Value
url The URL to where AJAX request is made using HTTP GET. It’s the Required parameter.
Data Optional parameter – it’s the key-value pairs that will be send with the AJAX request. Eg {sport: “football”,player: “Cristiano Ronaldo”}
success(result,status,xhr) Optional Parameter – the function to call when the AJAX request is successful. All 3 parameters are optional. The result parameter will get the return value from the AJAX request.
dataType The Optional Parameter – the type of data returned from the AJAX request. Can be xml, json, script, or html

jQuery Get Method to Fetch Contents of a Text File

Let’s fetch a ‘text file’s’ content with jQuery Get:

<button id="loadTextFile">Try</button>
<div id="textData"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $.get("file.txt", function (result, status, xhr) {
            $("#textData").html(result);
        });    
    });
</script>

The jQuery Get makes the AJAX call to the ‘file.txt’ and shows its contents inside ‘textData’ div.

DEMO

Not just a text file but the above code can be use to fetch contents of other file types like HTML, JSON, XML, etc.
Capturing jQuery Get Error

Use .fail() to capture any errors that come during the AJAX request.

See the below code:

<button id="loadNoTextFile">Try</button>
<div id="textNoData"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#loadNoTextFile").click(function (e) {
            $.get("no-file.txt", function (result, status, xhr) {
                $("#textNoData").html(result);
            }).fail(function (xhr, status, error) {
            $("#textNoData").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
        });
    }); 
</script>

In the above code when trying to access a non-existing file .fail() function is called and it shows the message – “Result: error Not Found 404 Not Found”.

DEMO

jQuery Get method to Fetch Data from Database

With jQuery Get you can make AJAX calls to a server page which in turn fetches data from the Database and returns it back to the Get function.

Let us create a small demo application to understand this feature.

jQuery Get Demo Application

There are 2 pages – one is HTML and other is .ASPX. The HTML page has two dropdowns and a button. On clicking the button the dropdown, selected values are passed to the .ASPX page by the jQuery Get method.

The HTML page code:

<div id="message"></div>
<select id="sportSelect">
    <option value="Select">Select Sports</option>
    <option value="Tennis">Tennis</option>
    <option value="Football">Football</option>
    <option value="Cricket">Cricket</option>
</select>
<select id="playerSelect">
    <option value="Select">Select Sports Person</option>
    <option value="Maria Sharapova">Maria Sharapova</option>
    <option value="Cristiano Ronaldo">Cristiano Ronaldo</option>
    <option value="Sachin Tendulkar">Sachin Tendulkar</option>
</select>
<button id="loadDatabase">Try</button>
<div id="dbData"></div>

The jQuery Code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
    $("#loadDatabase").click(function (e) {
        $.get("result.aspx",
            {
                sport: $("#sportSelect").val(),
                player: $("#playerSelect").val()
            },
            function (result, status, xhr) {
                $("#dbData").html(result);
            }).fail(function (xhr, status, error) {
                $("#dbData").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
        });
    });
</script>

In the .ASPX page, you have to get the 2 dropdown values using Request.QueryString method, then fetch the respective data from the database.

Once you have the data from the DB use the Response.Write method to send it to the jQuery Get method.

The .ASPX page code:

List<MyDataBase> myDataBase;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        LoadData();
        SearchDatabase();
    }
}
void SearchDatabase()
{
    string sport = Request.QueryString["sport"];
    string player = Request.QueryString["player"];
    try
    {
        string information = myDataBase.FirstOrDefault(x => x.sport == sport & x.player == player).information;
        Response.Write(information);
        Response.End();
    }
    catch (Exception ex)
    {
        Response.Write("NO DATA");
        Response.End();
    }
}
void LoadData()
{
    myDataBase = new List<MyDataBase>();
    myDataBase.Add(new MyDataBase() { sport = "Tennis", player = "Maria Sharapova", information = "Maria Sharapova is a...});
    myDataBase.Add(new MyDataBase() { sport = "Football", player = "Cristiano Ronaldo", information = "Cristiano Ronaldo is a..." });
    myDataBase.Add(new MyDataBase() { sport = "Cricket", player = "Sachin Tendulkar", information = "Sachin Tendulkar is a..." });
}

class MyDataBase
{
    public string sport { get; set; }
    public string player { get; set; }
    public string information { get; set; }
}
Instead of DB we have used a list which contains some dummy data. The “LoadData()” function adds these dummy data to the list.

DEMO DOWNLOAD

Other similar topics in jQuery AJAX are –

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on “WordPress, SEO, jQuery, HTML” and more.