How to display an HTML Element from an external site - javascript

Let's say I know a class id, is it possible to read the HTML data and write as a string the HTML that contacts that class id?
Doesn't have to be concrete code for this, any resources are appreciated that may make this possible. I'm unsure if there are any javascript functions that allow this.

If you are accessing this from another site and assuming you have CORS setup to allow the request, you can use jQuery's get() to fetch the item:
$.get('https://example.com/path/to/page.html')
.then(function(data){
var elem = $(data).find('yourSelector');
/*
Do something with the element
*/
});
This also assuming that the element is always on the page and the page always resolves.

Related

Is there a way in jQuery to modify .html() so that it adds code rather than overwriting?

I'm doing work to retrieve data from APIs. I'm designing my code to make multiple queries to the API and then adding them to the running list of results in my HTML. Due to the data returned by the API, there isn't a way to get it all in one shot and then slice it up, I need to get it in multiple shots.
Look at this code:
function renderResults(results) {
return $('#results-section').html(genResults(results));
}
The function renderResults() is being called inside my API call
.fetch(URL)
.then([code that is working properly])
.then(call renderResults() here)
I've console logged my API results and tested the API call in Postman so I know it's constructed correctly- just trying to give proper context.
To review, results is the data from the API, results-section is how the results container in my HTML is marked, and the function genResults(results) creates the template HTML with values from results stuck into it.
When you use .html it overwrites everything in the section indicated immediately prior. I'm looking for a way to add the template HTML generated by genResults(results) to any HTML already in the container I have ID'd results-section, not replace what's there. I've tried chaining on .append() but can't seem to find a way to do so successfully.
The obvious solution is to have a for loop create as many results sub-sections as I need, but the problem is that I don't know how many sections I need until I get the results from the API.
Any ideas?
Update:
Answer from Souvik Ghosh worked. I was trying to chain .append() on to .html(), I didn't realize it actually replaces it.
$( "#results-section" ).append( "Your data from the last API call" );
You could use jQuery append.
$( "#results-section" ).append( "Your data from the last API call" );
Read more: https://api.jquery.com/append/

Google Tag Manager Virtual Page View

I have a little problem setting up a virtualPageView which should override the URL which is sent to google when no result is present.
Heres what I have as JavaScript code:
function returnNoSearchResultsGoogleTagManagerCode($searchterm){
if ($searchterm == "") return "";
$requestUri = $_SERVER['REQUEST_URI'] . "&no_result=".$searchterm;
$js = "<script>
$(document).ready(function(){
dataLayer.push({
'event':'empty_result',
'virtualPageURL':'".$requestUri."'
});
});
</script>";
return $js;
}
As you can see, I want to use an event trigger (empty_result).
In google, I use a Trigger to determine if the Page is a no result Page. First i created a custom Variable with custom JS
function(){
if (document.getElementsByClassName('ga-no-result').length > 0){
return true;
}else{
return false
}
}
The class is set, if the SearchEngine can't find a result. So far so good.
I also created a dataLayer variable to hold the virtualPageURL
Now I need an event which is triggered if the variable is true.
Finally I created a Tag with type PageView which is fired when the event occurs:
Until now it seems okay, the Tag is properly configured (i guess) but if I do a search which has no result, the Page URL is not overridden
The Tag is properly fired and the variables are filled. The overview of the dataLayer shows a correct dataLayer event.
But the PageURL is not overridden... Even if I wait a whole day, the category isn't sent to google.
What am I doing wrong?
I would be very thankful if someone would have an idea or even a solution :)
Thanks in advance
exa.byte
UPDATE:
Hey, I forgot to mention, that I want to use the new page variable as the string which google should use to determine the searchterm and the searchcategory
In Google Analytics I configuered the search as the "q" parameter and the "no_result" as the category.
Is it even possible to change the string which google will parse in the end?
To send a virtual pageview to Google Analytics, the field you need to change is page not {{Page Url}} , also the title field is often used.
That's really the only two things you need to do to send a simple virtual pageview.
Extra: I always start my pagepath with /virtual/ to be able to recognize which ones are virtual pageviews easily in GA
For virtual page view you have to change Field "page" - in your GTM-OnSearchEmptyResult you are changing "{{Page URL}}" - I don't think that's correct way to send virutal pageview. Also if you need to change hostname use Fieldname "hostname".
In preview mode you will not see Page URL changed in Variables Tab, you have to go to the actual GA tag that is fired and check it's values. You can either do this in GTM's preview tool or you can use standard developer tools - Network Tab and see what values are being sent to GA:
You can see "dl" parameter is the current page, if you set up virtual page you should also see parameter called "dp" this is going to be the new value of page in your GA.
If you want to setup virtual pageview you have to use page instead of {{Page URL}} in your fieldname and for Document title use title in you fieldname.
for more field reference of google analytics follow below link
https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#hitType.
If you don't want to mess around with custom Tag Manager events it's still possible to use the good old ga method, even if you don't include the Analytics code on the page. You just need to fetch the right tracker dynamically, as explained by Simo Ahava in this thread.
if (typeof ga === "function") {
ga.getAll().forEach((tracker) => {
tracker.set('page', '/my/path'); // <- change here
tracker.send('pageview');
});
}
I also put it in a gist here.
thanks for your help. I think I got rid of the Problem and have solved it now. I will describe my solution below:
The solution is quite simple.
I had an error/ spelling error # google backend. I set the search_category parameter to "no_results", but used "no_result" for implementation...
Pretty dumb, but sometimes you just won't see the wood for the trees...
I created a new Trigger as helper "HelperDomReady" to trigger the only if DOM is ready and the variable "isEmptySearch" equals "(bool)true"
Now I can see the searchterms which have no result in google backend in the "sitesearch categories" summary. Since I won't set the parameter at all, if the search had at least one hit, the site-search category shows "not-set" for successful results. Therfore the category-section will only show searches without a hit. Problem solved :)
Disadvantage: The searchterm is also listed in the normal list. But I think this is negligible

What is the REST style for getSomethingByAnother() method

I have a Node.js REST API service and I have a resouce - Link for example.
To get all links I use GET /links
To submit new link I use POST /links
To get one link by linkid I use GET /links:id
Each link have an array of Tags and I need a REST style URI to get the links by tag value. What will be REST style URI in this case ?
For getting the links of a certain tag you can define the following route:
/tags/:tagID/links
And for getting tags of a certain link:
/links/:linkID/tags
I think it should be:
GET /links/:id/tags
that should return all the tags related to the link with id ":id"
If you like to work with your tags as a separated thing you could do it like this:
GET /tags ==> retrieve all tags.
GET /tags/:id ==> retrieve tag with id..
GET /tags/links/:id
Also resftull is not strict, and some times, the resource, or action that you need to execute does not fit in that schema, and you can create a custom method:
GET /tags/get-for-link-id/:id => retrieve tags related to a link
That example is pointless, but consider that you are having a complicated route with so much params eg:
GET /tags?q=return&state=active&sort=date if this request is repeated so much times, for your api customer it would be pleasant to have a custom alias like GET /tags/activeByDate
It depends. TYou can do something like /blah:{tagId}/ (which is perfectly valid URI as well). Or you can do /links/?tagID={id} and so on. I don't prefer the already mentioned hierarchical URI /tags/{id}/links, I think a flat URI is much better. If the relationship has attributes as well, then you can use /tag-link-relationships/{relationshipId} or /tag-link-relationships/tag:{tagId}/ or /tag-link-relationships/?tag={tagId} etc...
From client perspective the URI structure does not matter, because the client follows the hyperlinks the service responds with (aka. uniform interface / HATEOAS constraint).
off: Almost every day we got this question, at least try to search next time.

Use of Tealium's utag.view and/or utag.link for dynamically loaded elements

This may be a long shot but I'm looking for someone who has worked with the Tealium UDO (Universal Data Object). I have a search page with a Google Search Appliance, my utag_data object in the data layer that looks like this:
var utag_data = {
"country":"US",
"language":"EN",
"search_keywords": "blahblah",
"search_results": "0"
}
The problem here is the search_results property has not had enough time to wait for the real results number to load so it is defaulting to 0 instead of the real number 1200. I've read Tealium's documentation around the utag.view() and utag.link() and want to use one of these to update the search_results tag. I tried:
utag.link({'search_results':'1200'});
and
utag.view(utag_data,null,[12]);
where 12 is the UID of the tag in Tealium but when using Omnibug in firefox I'm not seeing any updated values, but it is sending the click event to AT Internet.
Does anyone have any experience with this? Thank you in advance
You can either wait to call the main utag.js Tealium script, or send along another data point using utag.link or utag.view. It is not possible to "update" the initial utag_data object once sent.
These methods are used to handle sending dynamic events/data. See additional discussion on the Tealium blog at ajax tracking.. when urls no longer change
From utag.link() and utag.view() on Tealium Learning
Syntax
The link and view methods allow you to pass three different parameters:
parameter 1: a JSON object
utag.view({'search_results':'1200'});
parameter 2: a callback function (optional, may be set to null)
parameter 3: an array of Tags (optional: if used, these are the only Tags that will fire)
utag.link(
{'search_results':'1200'},
function(){alert("Only fired tag 12 with this call");},
[12]
);
Notes:
The utag_data object declared on initial page landing is not re-purposed with these calls. If data from the initial page landing needs to be used it will need to be re-declared and passed again in the method call. For example, if language:"en" was passed on page landing, if language is needed for a tag fired by a utag method call then language will need to be passed again.
utag.view() calls should not be called on initial page load - they should only exist in the dynamic content loaded within the page.
Global and Tag-scoped Extensions are executed during these calls. Pre-loader and DOM Ready extensions will not executed during these calls.

JQuery ()load in a specific page?id=# number

I have the following problem: I need to have multiple private chatrooms per user.
I managed it to make it work but if there is more than one private chat ongoing on the same moment, the appended content of these chats are broadcasted to all private chatrooms.
function RefreshPrivate(userid)
{
var string_url = "./functions/ShowMessagePrivate.php?id=" + userid;
var page_url = "private.php?id=" + userid ;
$("#chatPrivateBody").append($("<div>").load(string_url));
}
The problem happens because of the $("#chatPrivateBody"),every private.php has that <div>, what I was thinking was that if I can append the string_url to page_url specific <div>
e.g $(page_url,"#chatPrivateBody") but there's nothing for this in the documantation of jQuery.
You mention "every private.php". So I assume you have multiple instances of this page loaded up on the same page at the same time, which either means that each one is loaded into some container via AJAX, or each one is in an iframe. You haven't really specified what you do with page_url.
I assume you're loading the pages via AJAX. If that's the case, each private chatroom gets loaded into a separate container (probably a <div>).
And each container will probably have a unique id (probably something like chatroom-<userid>).
If this is true, then you can target the #chatPrivateBody within the specific chatroom you're looking for:
$('#chatroom-'+ userid)
.find('#chatPrivateBody')
.append($("<div>").load(string_url));

Categories

Resources