Get the text inside <h2> element from an ajax jquery post response - javascript

Is there any way to get the text inside an element which is a response from an ajax jquery load. I need to get the text inside element which is present inside the response text from ajax page. Following is my ajax code:
var url = '...';
var saveData = $.ajax({
type: 'POST',
url: url,
data: {data : data},
dataType: "text",
success: function (resultData) {
callback(resultData); // need to get the <h2> text here..
}
});
saveData.error(function () {
console.log("Request to API not send");
});

You can pass HTML to jQuery and use it in the same way as if the element was on the DOM, for example with find():
console.log( $(resultData).find('h2').text() );
If your HTML doesn't have a root element then you can wrap it like so:
resultData = '<div>' + resultData + '</div>';
console.log( $(resultData).find('h2').text() );

How about:
$(resultData).find('h2').text()

Related

jQuery .html(someHTML) is not working

I have a script that makes an ajax request to the server. Then the server returns HTML code. After the request finish, I want to take the HTML code and put it on my site.
The problem that I am having is that the function .html() will display the html as text instead of making it an html.
Here is what I have done
var postData =
{
'campaign_id': 1,
'page_role': 'intro'
};
$.ajax({
type: 'POST',
url: 'url/to/get/html',
data: postData,
dataType: "text",
beforeSend: function(jqXHR, settings){
$('#MasterContentViewer').html('<div class="well innerwell">' +
'<h3>Please wait while loading the next page</h3>'+
'</div>');
},
error: function( jqXHR, textStatus, errorThrown ){
alert('Loading content failed! Error Code: ' + jqXHR.status);
},
success: function(page){
$('#MasterTable').removeClass('heightForIFrame');
$('#MasterContent').removeClass('heightForIFrame');
$('#MasterContentViewer').html(page);
}
}).done(function(page) {
var tags = $("meta[name^='is_system_'],meta[name^='is_attr_']" );
$.each(tags, function(index, tag){
var value = $(tag).attr('value');
var name = $(tag).attr('name').replace('is_attr_', '').replace('is_system_', '');
$('#attr_' + name + ':input').val( value );
$('#attr_' + name).not('input').text( value );
$('.attr_' + name + ':input').val( value );
$('.attr_' + name ).not('input').text( value );
});
I tried to change the following like
$('#MasterContentViewer').html(page);
to
$('#MasterContentViewer').empty().append(page);
which also did not work.
I also tried to change the dataType from "text" to "html" which also did not work.
How can I make the force the page to display html code instead of text?
UPDATED
Here is sample of what the user sees on the screen
<strong>Store Name: </strong><span class="attr_storename"></span> </div> <div class="scripter_header_label"> <strong>Store Number: </strong><span class="attr_alt_id_1"></span>
If .html(string) is appending elements as text, then that means that the elements are already HTML Encoded (e.g., <'s are in the string as >'s). jQuery will only encode html if you tell it to by using .text(string) instead of html(string).
Two possible solutions are:
Modify your server-side code to send non-encoded HTML
HTML Decode the string using Javascript (I would not recommend this method, however, because it caters to HTML Injection attacks).

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) {
});
In your .done() method:
.done(function(data) {
$('#target').html($(data).find('#specificDivId'))
})
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.
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)
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

(this).parent().find not working for getting response in ajax call

$(".content-short").click(function() {
$(".content-full").empty();
var contentid=$(this).parent().find(".content-full").attr('data-id');
var content=$(this).parent().find(".content-full");
alert(contentid);
var collegename = $(this).attr('data-id');
$.ajax({
type: "post",
url: "contenthome.php",
data: 'collegename=' + collegename,
dataType: "text",
success: function(response) {
$content.html(response);
}
});
});
here the alert displays the specific data-id but
content=$(this).parent().find(".content-full");
this didn't displays data in content-full div with that specific data-id
anything wrong in the code or something else?
the query displays data if i use(."content-full"); instead of
$(this).parent().find(".content-full");
Inside the ajax callback you are using $content, but you declare your variable as content. May that be the problem?
Your question is not clear. What are you trying to achieve?

why jquery done() showing success result multiple time instead of one?

I am processing my html form with jquery / ajax request. It's calling by jquery 'change()'. So when request is success it's showing me success result which is
Successfully Updated
Well, but if it again request it's showing
Successfully UpdatedSuccessfully Updated
It's just added last success result text to new one. I want to show only onnce. Can you tell me why it's happening ?
my code:
$("#corp_www_eng, #domestic_www_japaness").change(function(){
var cid = $("#cid").val();
var corp_www_eng = $("#corp_www_eng").val();
var domestic_www_japaness = $("#domestic_www_japaness").val();
$.ajax({
url: 'edit_companyinfo.php',
type: 'POST',
dataType: 'html',
data: {
"cid" : cid,
"corp_www_eng" : corp_www_eng,
"domestic_www_japaness" : domestic_www_japaness,
},
}).done(function ( data ) {
$('#result').append(data);
$('#result').show();
$('#result').delay(3000).fadeOut('slow');
});
});
Try substituting .html() for .append()
$("#result").html(data);
I believe it is because your are appending the data to the #result div. You could try adding
document.getElementById('result').innerHTML = '';
This would clear that div of any content before appending the new content.

jQuery AJAX onclick get DOM of a specified URL

I would like to make an AJAX pagination withot php and mysql, so when I click a link than I would like to get the next page DOM without reloading page and than in that DOM find the elements I need to append to the current page.
I now that jQuery IAS does this but I have a three col design and I need only one next button which onclick appends the data into the aproppriate col based on its parent class and IAS can't handle tree col layout.
So basicly something like this:
$('a.button').click(function(){
var url = $('a.next').attr('href');
$.ajax({
type: 'GET', //or POST i don't know which one
data: url, //or should this be the url: ?
success: function(data){
//data should be the DOM of the second page
$html = $(data);
$html.find('.col1 .child').appendTo('.col1');
$html.find('.col2 .child').appendTo('.col3');
$html.find('.col3 .child').appendTo('.col3');
}
});
return false;
});
Obviously this doesn't work I just put it here to make my question undersandable.
How can I do this?
yes it would be variable url such as
$('a.button').onclick(function(){
var url = $('a.next').attr('href');
$.ajax({
type: 'GET', //or POST i don't know which one
url: url, //or should this be the url: ?
success: function(data){
//data should be the DOM of the second page
$html = $(data);
$html.find('.col1 .child').appendTo('.col1');
$html.find('.col2 .child').appendTo('.col3');
$html.find('.col3 .child').appendTo('.col3');
}
});
return false;
});
you use data parameter to pass an object of key value pairs to the receiving end.
data: {key1: value1 , key2: value2}

Categories