javascript - load html content from ajax call - javascript

I have HTML page that has Ajax call to load table content
<html>
....
<script sec:haspermission="VIEW_NOTE" th:inline='javascript'>
require(['app/agent/viewGlobalAgent'], function (){
var individualId= [[${model.agent.individual.id}]];
var agentId= [[${model.agent.id}]];
$.get("/notes/referenceTable.html?individualId="+individualId+"&agentId="+agentId, function(data){
console.log("theData " , data);
var noteList = $("#note-list-container2").value;
var fileList = $("#file-list-container2").value;
// document.getElementById("note-list-container").innerHTML = noteList;
// document.getElementById("note-file-form").innerHTML = fileList;
$("#note-list-container").html(noteList);
$("#note-file-form").html(fileList);
});
</script>
....
</html>
the html that Ajax call load
<div>
<div id="note-list-container2">
....
</div>
<div id="file-list-container2">
....
</div>
</div>
I need to access these two div on callback of Ajax call
$.get("/notes/referenceTable.html?individualId="+individualId+"&agentId="+agentId, function(data){
I tried to access them but its not working
$("#note-list-container2").value
is any way to access div in loaded html

Since you want content from within the new html returned as data you want to wrap that data in $() and query within that object
Then use text() or html() since value is only for form controls, not content elements
$.get(url, function(data) {
var $data = $(data);
var noteList = $data.find("#note-list-container2").text();// or html()
var fileList = $data.find("#file-list-container2").text();
$("#note-list-container").html(noteList);
$("#note-file-form").html(fileList);
});

jQuery.text(): Get the combined text contents of each element in
the set of matched elements, including their descendants, or set the
text contents of the matched elements
jQuery.val(): Get the current value of the first element in the
set of matched elements or set the value of every matched element.
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. When called on an empty
collection, it returns undefined.
A div element does not have a value....
An example:
console.log('text(): ' + $("#note-list-container2").text());
console.log('val(): ' + $("#note-list-container2").val());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="note-list-container2">
....
</div>

I’m guessing you’re using jQuery. The HTML contents can be accessed with .html() not with value. There is no value attribute on a div element. More importantly, you should attempt to get the contents of the element AFTER updating it, not before. Also, the selectors should match. From your example, it seems that you're attempting to get the contents for a #note-list-container2 but you're updating a #note-list-container element. One of those IDs is wrong, given your sample AJAX call output.

Related

Get only a paragraph from http response [duplicate]

I'm looking for a way to get a HTML element from a string that contains HTML. Is it possible to use a jQuery selector to do this?
I have a Javascript function that gets an entire page from the server, but I only need one element from that page.
Yes, you can turn the string into elements, and select elements from it. Example:
var elements = $(theHtmlString);
var found = $('.FindMe', elements);
Just wrap the html text in the $ function. Like
$("<div>I want this element</div>")
If you are loading a page dynamically from a server then you can target just one element from the loaded page using the following form with .load()
$(selectorWhereToShowNewData).load('pagePath selectorForElementFromNewData');
For example:
$('#result').load('ajax/test.html #container');
Where:
#result is where the loaded page part will be displayed on the current page
ajax/test.html is the URL to which the server request is sent
#container is the element on the response page you want to display. Only that will be loaded into the element #result. The rest of the response page will not be displayed.
Just use $.filter
var html = "<div><span class='im-here'></span></div>"
var found = $(html).filter(".im-here")
You can use $.find
$(document).ready(function() {
var htmlVal = "<div><span class='im-here'>Span Value</span></div>";
var spanElement = $(htmlVal).find("span");
var spanVal = spanElement.text();
alert(spanVal);
});

Remove "Form" tag with its content from string with javascript

I need to remove form tag from ajax response content. I have tried below code but it's not working. Any help would be appreciated.
new Ajax.Request(
url, {
method: "post",
onSuccess: function (b) {
var a = $("test");
a.update(b.responseText.replace("[<](/)?form[^>]*[>]", ""));
}
});
(Not using jQuery in this answer as the code in your question is clearly using PrototypeJS instead.)
The simplest way is to parse the HTML (the browser is happy to do that for you), remove the form element in the result, and then serialize that back to a string (if needed; the browser is happy to do that for you too).
For instance (not using jQuery):
var div = document.createElement("div");
// This parses it
div.innerHTML = b.responseText;
// Find and remove the first form; tweak the selector to target if necessary
var form = div.querySelector("form");
if (form) {
form.parentNode.removeChild(form);
}
// Convert back to string if needed
var str = div.innerHTML;
Remove “Form” tag with its content from string with javascript
Assuming that you meant Remove “Form” tag along with its content from string.
If you are using jquery, then can try
var $bResponseText = $( b.responseText );
$bResponseText.find( "form" ).remove();
b.responseText = $bResponseText[0].outerHTML;
Just before using the update function
Or another approach with jquery
$("test").append( b.responseText );
$("test").find( "form" ).last().remove();
You can simple replace the form content with the <form>
//detect the form, you can use id or class selector
var formContent = $('form');
// replace the form with its content so that form tag is removed
formContent.replaceWith(formContent.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='content'>
<form>
<div>Content inside Form</div>
</form>
</div>
You can use something like this :-
Create a temporary div :- var tempDiv = document.createElement("div");
Then assign response as its innerHTML :- tempDiv.innerHTML = b.responseText;
After that user querySelectorAll to get all form elements from above temp div :- var allForms = tempDiv.querySelectorAll("form");
Then iterate over allForms and user remove() method to remove form one by one.
After that use tempDiv's innerHTML to get string without form element :- a.update(tempDiv.innerHTML);

Find And Change Element In a Parsed HTML DOM

I am getting an HTML string in response to an ajax request. It is a large HTML string with a lot of hierarchical child nodes.
I parse it using
jQuery.parseHTML();
to convert it into a DOM. Now i want to change the content of a child node with a certain ID and then regenerate the HTML.
The Problem is when ever i use a jQuery method to select a dom element to make the changes, it returns that particular node and the
jQuery.html()
just changes that node to HTML.
I have tried following code samples
var parsedHTML = jQuery.parseHTML( 'htmlstring' );
jQuery(parsedHTML).find('#element-id').text('changed text').html();
or
jQuery(parsedHTML).filter('#element-id').text('changed text').html();
the problem is it only returns span#element-id and when html() is applied, the generated html has only span text.
How can i generate back the complete html and change the specific node?
Don't chain (or if you do, use end, but simpler really just not to). By chaining, you're saying you only want the HTML of the last set of elements in the chain:
var elements = jQuery(parsedHTML);
elements.filter('#element-id').text('changed text');
var html = elements.html();
But elements.html() will only give you the inner HTML of the first element. To get the full HTML string again, you need to get the outer HTML of each element and join them together:
var html = elements.map(function() {
return this.outerHTML;
}).get().join("");
Note that your use of filter assumes the element is at the top level of the HTML string. If it is, great, that's fine. If it isn't, you'll want find instead.
Example with filter:
var parsedHTML = jQuery.parseHTML(
"<span>no change</span>" +
"<span id='element-id'>change me</span>" +
"<span>no change</span>"
);
var elements = jQuery(parsedHTML);
elements.filter('#element-id').text('changed text');
console.log(elements.map(function() {
return this.outerHTML;
}).get().join(""));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Example with find:
var parsedHTML = jQuery.parseHTML(
"<span>no change</span>" +
"<div>the span is in here<span id='element-id'>change me</span></div>" +
"<span>no change</span>"
);
var elements = jQuery(parsedHTML);
elements.find('#element-id').text('changed text');
console.log(elements.map(function() {
return this.outerHTML;
}).get().join(""));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to add data to the anchor tag in HTML and access it using jQuery?

Following is my HTML code of an anchor tag:
<a delhref="http://localhost/eprime/entprm/web/control/modules/questions/manage_question_issue.php?op=fixed&question_id=21627&que_issue_status=0" title="Fixed" href="#fixedPopContent" class="fixed">Fixed</a>
Now I want to add a question id to the above anchor tag and access it back in jQuery when user clicks on this hyperlink. For it I tried below code but it didn't work out for me.
<a delhref="http://localhost/eprime/entprm/web/control/modules/questions/manage_question_issue.php?op=fixed&question_id=21627&que_issue_status=0" title="Fixed" href="#fixedPopContent" class="fixed" data="21627">Fixed</a>
The jQuery code for it is as follows:
$(document).ready(function() {
$(".fixed").click(function(e) {
var t2 = $(this).data();
alert(t2);
});
});
It's giving me the message [object Object] in alert box. Can anyone please help me in setting the value to a anchor tag and accessing it in jQuery?
try something like this
html
javascript
$(document).ready(function() {
$(".fixed").click(function(e) {
var t2 = $(this).data('q_id');
alert(t2);
});
});
you can add attribute data-sample_name on your html element.
In jquery use
$('your_element_id').data('sample_name');// to get value
$('your_element_id').data('sample_name','new value');// to set value
I assume you are trying to do something like this:
$(document).ready(function() {
// you can change the selector, `"key"` and its value below
$("a.fixed").data("key", 21627); // on document ready, store the necessary data
// ^-- Insert a dynamic value here if required
$(".fixed").click(function(e) {
alert($(this).data("key")); // 21627
});
});
.data() stores a key-value pair. So here, I made a key called 'key' and stored with it a value of 21627 and on click, alerted the value corresponding to the key 'key'.
You got a [object Object] because of the same reason that .data() stores data in an object and that by passing it zero arguments, you were essentially storing the object associated with .fixed into t2.
One more simple way is:
Use id attribute in anchor tag to write your data.
<a id="your-data" onclick="callfunction(this.id)">Fixed</a>
Create a function in js file like callfucntion(id).
function callfucntion(id)
{
var data = id; // if more than one data, you can se split()
}

Getting element by tag name after getting a page using jQuery $.get

I am requesting a full page using $.get in jQuery and would like to get the content of a specific element. Separately, here is how things look:
$.get( "/page.html").done(function( data ) {
// get textArea.
});
and I want to get:
document.getElementByTagName("textArea")[0].value;
but I can't do getElementByTagName on data so what is the best way to do this?
I tried using find but that did not work so I ended up using filter and that returned the value of textArea that I needed:
$.get( "/page.html").done(function( data ) {
var textArea = $(data).filter("textarea")[0].innerText;
});
It's slightly different of what you are doing but i think it can help. You can call .load instead of get and add the whole page to a div say <div id="mydiv"></div>
var value;
$('#mydiv').load('xyz.html',function(){value=$('#mydiv').find('#mytextarea').val()})
however if you do not want mydiv to show you can hide at the beginning once the main page gets loaded and if you also don't want this div on your page you can remove it after the above task is performed.
$(document).ready(function(){
$('#mydiv').hide();
var value;
$('#mydiv').load('xyz.html',function(){value=$('#mydiv').find('#mytextarea').val()});
$('#mydiv').remove();
})
//str represents page.html
var str = 'gibberish gibberish <textarea class="test">hello world</textarea>gibberish';
$.each( $.parseHTML(str), function( i, el ) {
if(el.firstChild) console.log(el.firstChild);
});
Fiddle: http://jsfiddle.net/ez666/7DKDk/
You could try jquery load() function.
It will load from remote server and insert document into selected element.
It also allow us to specify a portion of remote document to be inserted.
Assume your remote textarea's id is "remote" and you want to fetch the remote content into a textarea which id is "local"
var result="";
$("#local").load("/page.html #remote", function(response, status, xhr){
result=$(this).find("#remote").val();
});
I'm not sure if you want to get the remote textarea and insert into the element of the current document.
If you just want to get the value of the remote textarea, you could just hide the load function invoking element
Hope this is helpful for you.
Since you're using jQuery anyway… have you tried $(data).find('textarea').first().val() yet?
This is assuming that data is a fragment. If it is not you will want to wrap it in a div or something first.

Categories