- Key Takeaways
- Concepts
- Figure 1: Full Movies Page
- Figure 2: The home page displaying only action films. (index.html)
- Listing 1: Movies page (movies.html)
- Movies
- Listing 2: Home page (index.html)
- Listing 3: Style Sheet (styles.css)
- Conclusion
- Frequently Asked Questions on Selecting Elements Returned by jQuery AJAX Response Strings
Key Takeaways
- The jQuery selection engine can select elements from both DOM elements and in-memory markup strings, providing a versatile tool for reusing content in web applications.
- When making an Ajax call to a static HTML page, the response will include the full HTML markup of the page. To make this response select-able, it must be manually wrapped in a root element, such as a DIV element.
- The jQuery find API can be used to extract only the necessary markup from the response string. This allows for selective rendering of elements from one page on another, providing a solution for working with static or “black box” systems.
Concepts
Consider an application which includes content on one page that you want to display on another page. Reasons for an approach like this vary, but common scenarios include working with legacy or “black box” systems where you have no control over the server implementation or where you are working with static content. In the end both “black box” and static content circumstances afford you no opportunity to prepare data on the server into typical Ajax response messages (i.e., JSON or XML). The example demonstrated in this article works to fetch content fragments from static HTML files and display them on another page in the site. The Figure 1 displays a static HTML page that lists movies from multiple categories in the system.Figure 1: Full Movies Page
While the Movies page has all the films in the system, the home page will only display a subset of the movies to users. Figure 2 shows how the home page renders only the Action films on the page.Figure 2: The home page displaying only action films. (index.html)
In order to make this scenario work, an Ajax call against the static HTML page is required. Once the response from the Ajax call is recognized by the browser, then a fragment of the page is extracted from the full response by using jQuery selectors on the markup returned from the static page. The jQuery selection engine is flexible enough to work on DOM elements as well as selecting against an in-memory string of markup – but there’s a catch. The response from the Ajax call includes the markup of the full HTML of the page, which includes the DOCTYPE element as well as the root HTML element of the document. A response with two root-level elements is not immediately select-able as the jQuery selection engine requires that query targets must have a single root element. This issue is resolved by manually adding a root element to the response string which is done by wrapping it in a logical container like a DIV element.Code
The code for the movies page is available in Listing 1 which shows how each category of movie is logically contained by a SECTION element with a corresponding ID value.Listing 1: Movies page (movies.html)
Movies
Action
Die Hard
The Matrix
Raiders of the Lost Ark
Drama
A Few Good Men
The Shawshank Redemption
Legends of the Fall
The home page is comprised of the code found in Listing 2
which by default includes only a single structural element found in a DIV tag which acts as a shell for the content rendered on the page.
Listing 2: Home page (index.html)
$(function () {
$.get('movies.html', function (response) {
var source = $('
' + response + '
');
$('#movies').html(source.find('#action-container').html());
});
});
The JavaScript on this page begins by registering the jQuery load handler. Once the page loads, a call to the $.get API fetches the movies.html page. The response from this request is the full HTML markup of the movies.html page (including DOCTYPE). Since the raw markup is not initially select-able the string is wrapped with a root DIV element and is then instantiated as a jQuery object, making it ready for processing by the selection engine.
To locate the desired fragment of HTML in the Movies page, the find API is used to query the descendants of the full markup and return only the elements needed for the home page (i.e., the element with the ID of action-container). Once the fragment is found, it’s then injected into the innerHTML of the content host element by using the jQuery html function against the DIV with the ID of movies.
Finally, Listing 3 includes the common styles used in each page to apply some minimal styling to the pages.
Listing 3: Style Sheet (styles.css)
body, html
{
padding:4px;
margin:0px;
}
body
{
font-family:Arial, Helvetica, sans-serif;
font-size:1em;
}
Conclusion
While the need for this approach may be relatively rare, you may encounter times when you want to make an Ajax call to an existing page on your site and only render a targeted part of the elements on the page. The secrets to making this approach work are to wrap the response string in a single logical root element and then use the jQuery find API to extract out only the markup required for the host page.BIO:
Craig Shoemaker (Twitter | Google+) is a software developer, podcaster, writer and Technical Evangelist for Infragistics. As host of the Polymorphic Podcast, Craig does what he loves most – making contributions to the community and drawing the best out of industry luminaries. Craig is a Microsoft ASP.NET MVP, ASP Insider and guest speaker at various developer user groups and tradeshows. Craig is co-author of the Wrox books “Beginning ASP.NET 2.0 AJAX“, “Beginning ASP.NET Ajax“, and CODE Magazine and Pluralsight author. In his spare time Craig enjoys looking for a haystack to hide his prize needle collection.Frequently Asked Questions on Selecting Elements Returned by jQuery AJAX Response Strings
What is a jQuery AJAX response string and how does it work?
A jQuery AJAX response string is a data format that is returned from a server after an AJAX request is made. AJAX, which stands for Asynchronous JavaScript and XML, is a technique used in web development to create asynchronous web applications. With AJAX, web applications can send and retrieve data from a server asynchronously without interfering with the display and behavior of the existing page. In jQuery, the $.ajax() method is used to perform an AJAX request, and the data returned from the server can be in various formats such as XML, HTML, JSON, or a string.
How can I select elements from a jQuery AJAX response string?
To select elements from a jQuery AJAX response string, you can use the jQuery function $() along with the response string as its argument. This will create a jQuery object that you can then use to select elements. For example, if your AJAX response string contains HTML code, you can select elements from it like this: var $response = $(responseString); var $element = $response.find(‘.my-element’);
Why am I getting a full HTML page as a response to my AJAX POST request?
If you’re getting a full HTML page as a response to your AJAX POST request, it’s likely that the server is returning an error page. This can happen if there’s an error in your server-side code, or if the URL you’re requesting doesn’t exist. To debug this, you can check the status code and the response text of the AJAX request. If the status code is anything other than 200, it means there’s an error.
How can I retrieve a portion of HTML with jQuery?
To retrieve a portion of HTML with jQuery, you can use the .load() method. This method loads data from the server and places the returned HTML into the matched elements. You can specify a portion of the HTML document to be inserted by using a string after a space in the URL parameter. For example, $(‘#result’).load(‘ajax/test.html #container’) will load the content of the element with the ID of ‘container’ from the ‘test.html’ file into the element with the ID of ‘result’.
How can I convert a jQuery object into a string?
To convert a jQuery object into a string, you can use the .html() method. This method gets the HTML contents of the first element in the set of matched elements. It returns a string representing the HTML content. For example, var htmlString = $(‘#my-element’).html(); will get the HTML content of the element with the ID of ‘my-element’ and store it in the ‘htmlString’ variable.
Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.