Rohan Veer
Rohan Veer

Reputation: 1490

load specific div content using ajax

I am using $.ajax to load the page content. In response I am getting whole html document as a string but I want to get the only particular div content from the response by using id of the div. I can't change the response and I can't use $.load method. Thanks in advance.

$.ajax({ 
    url: ajax_url, 
    type: "GET", 
    dataType: "html" 
}).done(function(data) {
}).fail(function(jqXHR, textStatus, errorThrown) { 
});

Upvotes: 0

Views: 6688

Answers (4)

A. Wolff
A. Wolff

Reputation: 74420

What you want is basically what ajax shorthand method load() using page frament is doing:

$('#divToAddContent').load(ajax_url + ' #divToGetContent');

(note the space at starting fragment selector string)

Upvotes: 1

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

As AJAX returns a plain text, you can transform it to jQuery DOM element, modify it and append (or replace HTML) to your HTML.

For example, this way:

$.ajax({ 
    url: ajax_url, 
    type : "GET", 
    dataType : "html" 
}).done(function(data) { 
    var obj = $(data);
    $("#yourdiv").html(obj.find(".something").html());
}).fail(function(jqXHR, textStatus, errorThrown) { 

});

I have used .find(".something") because I do not know the format of received message. You can use any jQuery methods.

Upvotes: 1

Jai
Jai

Reputation: 74738

In your .done() method:

.done(function(data) { 
    $('#target').html($(data).find('#specificDivId'))
})

Upvotes: 1

Marcos Pérez Gude
Marcos Pérez Gude

Reputation: 22158

You can use DOM parser.

$.ajax().success(function(data) {

  var parser = new DOMParser();
  var doc = parser.parseFromString(data, "application/xml");

  // doc is a DOM now

});

More information:

https://developer.mozilla.org/es/docs/Web/API/DOMParser

Upvotes: 0

Related Questions