Handling xmlhttpResponse that contain html code, need to modify anchor element - javascript

`var responseText = xmlhttp.responseText;
$(reponseText).$('#products href').each(function(){
this.href = "http://www.example.com" + this.href;
})
`
reponseText contains html code.
Products is a Id of Div element.
I want to pre append all the anchor elements in this div ( products ) like http://www.example.com/ followed by current href attribute.

You need to only specify the required parts in ajax request page, otherwise xmlhttp.responseText will return all the HTML and print statements given in the request page.
for example, in the case of JSP
<html>
<%
out.print("something")
%>
</html>
ajax:
xmlhttp.responseText will return both html tag and the print text 'something'
actual result will be: "<html>something</html>"
so you need to remove unwanted html/printing statements from your request page.

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);
});

javascript - load html content from ajax call

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.

JQuery :first does not select first, but second

I have a JQuery script which sends a request using AJAX to the following url https://djjohal.video/video/671/index.html#gsc.tab=0 which contains information of a video song.
I actually want to parse and fetch all the details from the html content I received in the AJAX call.
The HTML page contains a total of 3 div's each having a class ".head", and among them the content of the first div is the title of the song that I want to fetch. So for that I tried using the :first selector of JQuery like this: $(PAGE).find("div.class:first").text(); where PAGE is the parsed HTML object.
What it does is that instead of selecting the actual first div, it selects the second div with the head class which contains useless information.
Here is my JavaScript Code
function action(){
let url = `https://djjohal.video/video/671/index.html#gsc.tab=0`;
LOG_INFO( "REQUEST SENT..." );
$.ajax({
url : url,
success : function(res){
LOG_INFO( "DATA RECEIVED..." );
let PAGE = $(res);
LOG_INFO( $(PAGE).find("div.head:first").text() );
}
});
}
function LOG_INFO( MSG ){
$("body").text( MSG );
console.log( MSG );
}
$(document).ready(function(){
action();
});
Here is the HTMLcontent that is received during the AJAX call
Cannot Paste the whole content in here
You can view the content via this link if supported.
view-source:https://djjohal.video/video/671/index.html#gsc.tab=0
here is the output of the code when executed.
REQUEST SENT...
DATA RECEIVED...
Select Format :
Where the text "Select Format :" is the content of the second div with the head class.
You can clearly see that the first div tag with the class "head" is the one containing the Title of the Song.
But why can't JQuery see this??
Why does the :first selector selects the second div.
What should I do ?? Please help!!
First you need to clean up your HTML
Why do you have a HEAD tag outside the HTML tags?
Also you shouldn't be putting body content inside the head section.
Try this:
$.ajax({
url : url,
success : function(data){
var responseHtml = $.parseHTML(data);
songTitle = $.trim(
$(responseHtml).filter('div.head:first').text());
alert(songTitle);
}
});
you have to use first()
$(PAGE).find("div.head").first().text();
for more information:https://api.jquery.com/first/

How do I render text on the page of other sites (once script planted)

I am learning javascript and trying to build a chat app like intercom.
How do i go about creating a popup on another page once my js script is planted??
I do it locally like so:
function Hide()
{
document.getElementById('div1').style.visibility="hidden";
}
There is many way to do it i'll explain the idea with some examples, let's go
Our code based on two functionalities:
1: innerHtml = "<YOUR CODE/>"; This property is for injecting the html in the element more info.
2: document.getElementById("IdName") This property is for selecting and element wich we will apply some functionalities, in our case is the property N°1 more info.
3: <div id="IdName"></div> Here where we will append our html or text more info.
Now we start with some examples:
1st example:
API File:
function function_name(argument) {
document.getElementById(argument).innerHTML = "<p>Paragraph example..</p>";
}
User File:
// first of all the user need to put a div with an attribute ID in his html where
//he want to append the html given by the API
<div id="IdName"></div>
//after that he must call the specified function wich is in our case function_name() and put the ID as argument
function_name("IdName"); // this will append the html in the div with the ID == IdName
Also you can use document.getElementsByClassName("className"); in place of ID
2nd example:
In this case the user don't need to put any additional html or any other things; in this example we will add our html into the body element wich is a necessary element in HTML page.
document.body.innerHTML += "<p>Paragraph example..</p>";

String Filtering.Need to remove the <style> tag and its contents and keep only the contents in <body>

In our project, we are getting a response from the DB. We are using the same string in two ways.
We have to display the text part alone in one line
We are putting the entire content as an HTML.
We are getting a response similar to this.
"<html><head><title>SomeTitle</title></head><style>a.hover{color:green}cc.a{color:red},pq.a{text-decoration:underline}</style> <body> Some content </body></html>"
I need to get the content only from the body using string manipulation.I need to filter out all the contents of the other tags as well.
For example
Final result should be
Some content
I used text() in some case but at times the content inside is also getting displayed. That is not allowed for me.
Note: There are times where I don't get so there should be a check for that as well.
any solution on this?
At times we are getting inside body as well. So is there any way to remove that part off?
for example
var str = "<html><head><title>SomeTitle</title></head><style>a.hover{color:green}cc.a{color:red},pq.a{text-decoration:underline}</style> <body> <style>.hello12{color:green}</style>Some content </body></html>";
and i should get just "some content"
Use DOMParser and get text content from body tag. Where querySelector can be used to get body element and get text content from textContent property.
var str = "<html><head><title>SomeTitle</title></head><style>a.hover{color:green}cc.a{color:red},pq.a{text-decoration:underline}</style> <body> Some content </body></html>";
var parser = new DOMParser();
var doc = parser.parseFromString(str, "text/html");
console.log(
doc.querySelector('body').textContent
)
FYI : To avoid script and style tag content use innerText property instead of textContent property.

Categories