0

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) { 
});
6
  • 1
    Just show a bit of the code? Commented Oct 19, 2015 at 9:08
  • $.ajax({ url : ajax_url, type : "GET", dataType : "html" }).done(function(data) { // here i want to fetch the specific div content from response. }).fail(function(jqXHR, textStatus, errorThrown) { }); Commented Oct 19, 2015 at 9:09
  • What about using load() with HTML fragment part? (this accepts any knid of CSS selector, not only ID) Commented Oct 19, 2015 at 9:13
  • try using $($.parseHTML(response)).filter("#success"); Commented Oct 19, 2015 at 9:16
  • @Antony should be find() not filter() Commented Oct 19, 2015 at 9:16

4 Answers 4

1

In your .done() method:

.done(function(data) { 
    $('#target').html($(data).find('#specificDivId'))
})
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.