Some days ago, i was try to load another page by ajax. I only want certain element to replace my existing element. Due to my site based on WordPress, i think jquery is best option.
So here is my code
$.ajax({ url: "login.html" }).done(function( data ) { var kontener = $('').html(data).find('.kontener'), content = kontener.find('#content'); $('body .kontener').html(content); });
First thing we need to convert the data to jQuery HTML version, by set it as variable for further need as on line
var kontener = $('').html(data).find('.kontener')
So, next we can find the element we want to use
content = kontener.find('#content');
And the last thing we need to do is replace it
$('body .kontener').html(content);
That’s how we get an element from ajax resppons by using jQuery. We can replace existing element with ajax, without loading page.
Or we can try this way also.
When working with Ajax, you may need to extract specific elements from the response data and use them in your web page. Here’s how you can find elements from an Ajax response using jQuery:
- Send an Ajax request: First, send an Ajax request to the server using jQuery’s
$.ajax()
method or one of its shorthand methods like$.get()
or$.post()
. Make sure to specify the data type as “html” or “xml”, depending on the type of data you expect to receive.$.ajax({ url: "ajax-page.php", dataType: "html", success: function(response) { // Code to find elements in the response } });
- Parse the response data: In the success callback function, the response data is passed as a parameter. Parse the response data using jQuery’s $() function to create a jQuery object from the response. This allows you to use jQuery methods to find and manipulate elements in the response.
- Find elements in the response: Once you have a jQuery object representing the response, you can use jQuery’s selector syntax to find elements within the response. For example, to find all elements with the class “my-class” in the response.
- Use the found elements: Once you have found the desired elements in the response, you can use them as you would any other jQuery object. For example, you can append them to an element on the page, update their text or attributes, or bind event handlers to them.
$.ajax({ url: "ajax-page.php", dataType: "html", success: function(response) { var $response = $(response); // Create jQuery object from response var $myElements = $response.find(".my-class"); // Find elements in the response $("#my-container").append($myElements); // Append elements to a container element } });
By following these steps, you can easily find and use elements from an Ajax response using jQuery.