How to check if string exists on external page with JavsScript? - javascript

I'm trying to check a page (on the same domain) for a specific string and then execute something accordingly. How can I go about this in JavaScript (with jQuery loaded)?
A (maybe too much) simplified schematic:
url = "pageToLoad.php"
if(StringOnPage(url) == TRUE){
// Do a bunch of stuff
}else{
// Do nothing
}
Now how would I construct StringOnPage() ideally? I made several attempts with jQuery's .load and .ajax, I even tried to load it into a hidden container. There must be a way to load the page into a string and check for an expression or something without all the html hacks.
The page is just an HTML populated file. Basically I need to find a text in a DOM element.

Load the page via AJAX as a plain string and then simply check if the string you are looking for is somewhere in the string you got from your AJAX call:
$.get(url, function(data) {
if(data.indexOf('whatever') != -1) {
// do a bunch of stuff
}
}, 'text');
Of course you could also use 'html' instead of 'text'; then data is a jQuery object containing the DOM of the page you just loaded.

Related

Get query string from URL with jQuery and do action based on that

I have a link in an e-mail that points the user to a webpage. On this webpage there is a pop-up that is hidden, unless a button is clicked; then jQuery displays that div.
I have searched for a way to grab the query string from the URL with jQuery to no avail. I know with PHP it would be a simple $query = $_GET['query'], but I'm not sure how to accomplish this with jQuery.
I need to check for a query string, say "?popUp=true", and display that div with jQuery if the query string is present.
Is there a way I can pass the PHP GET variable to jQuery?
I'm confused.
jQuery has nothing to do with it; it's just plain Javascript:
var query = window.location.search;
Or simply location.search. Do window.location from the Javascript console to see what all is there.
So:
$(document).ready(function(){
if (location.search.indexOf('popUp=true') > -1)) {
doPopUp(); // run your code.
}
});
MDN
Of course, we can get query parameter from url by split it, and it's pure java script. There's a general way to do it: http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html
But if you just need [popup=true] to use with jquery, you'd better to use hash.
URL:
http://.../yourscript.php#popup
And your jquery code:
if(window.location.hash) {
// Fragment exists, show popup
} else {
// Fragment doesn't exist, do nothing
}

how to load a file and parse tags using jquery

I have a file which contains lots of tags like follows
<script type="text/template" id="template-1">
</script>
<script type="text/template" id="template-2">
</script>
I want to load the file and than load all the content inside the script tags in memory.
I am trying the below code but its not working.
tpl = {
// Hash of preloaded templates for the app
templates : {},
loadTemplates : function(name) {
var that = this;
$.get(name, function(data) {
$(data).find('script').each(function (_, entry) {
that.templates[$(this).attr('id')] = $(this).text();
});
});
},
// Get template by name from hash of preloaded templates
get : function(name) {
return this.templates[name];
}
};
any help?
call is made like this
tpl.loadTemplates('/templates/templates-home.html');
In general you seem like you're on the right track. The browser will load (but ignore) script tags marked with type=text/template and you can later select the contents of those tags and process them with javascript.
I think your problem is likely with the order of your procedure.
You haven't posted the javascript that uses your templates so I can only assume. I suspect your trying to load the templates before the document is ready, thus, the script tags aren't actually on the page when you load them. To fix, your can move your javascripts below the templates in the document OR execute your code in a window.onLoad handler.
EDIT
Okay, now I have a better idea of what you're trying to do. You still haven't told me what part of this is broken, but my gut tells me that this bit is the problem: $(data).find('script'). jQuery expects to be traversing the DOM. At this point in time, data is just a string returned from the server, it's not actually loaded in the DOM. So jQuery won't actually find ANY script tags. Try appending your result to the body before querying the DOM for script elements. Maybe something like this:
$('body').append(data);
$('script[type="text/template"]').each ...
I'm not really thrilled about that though. Can you just inject them into the page on the server side? Why do you need to delay the loading?
EDIT 2
If you don't want your script tags to be visible in the html document, then I suggest you don't use them. Instead you can have your template endpoint just return a bundle of javascript and evaluate it directly. Something like:
$.get(name, function(data) {
// data is a string that sets up your window.template variable
eval(data);
});

Refresh Part of Page (div)

I have a basic html file which is attached to a java program. This java program updates the contents of part of the HTML file whenever the page is refreshed. I want to refresh only that part of the page after each interval of time. I can place the part I would like to refresh in a div, but I am not sure how to refresh only the contents of the div. Any help would be appreciated. Thank you.
Use Ajax for this.
Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.
Relevant function:
http://api.jquery.com/load/
e.g.
$('#thisdiv').load(document.URL + ' #thisdiv');
Note, load automatically replaces content. Be sure to include a space before the id selector.
Let's assume that you have 2 divs inside of your html file.
<div id="div1">some text</div>
<div id="div2">some other text</div>
The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.
You can, however, communicate between the server (the back-end) and the client.
What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.
Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.
setInterval(function()
{
alert("hi");
}, 30000);
You could also do it like this:
setTimeout(foo, 30000);
Whereea foo is a function.
Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.
A classic AJAX looks like this:
var fetch = true;
var url = 'someurl.java';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'fetch' : fetch // You might want to indicate what you're requesting.
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
$('#div1').html(res1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.
I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.
You need to do that on the client side for instance with jQuery.
Let's say you want to retrieve HTML into div with ID mydiv:
<h1>My page</h1>
<div id="mydiv">
<h2>This div is updated</h2>
</div>
You can update this part of the page with jQuery as follows:
$.get('/api/mydiv', function(data) {
$('#mydiv').html(data);
});
In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.
See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/
Usefetch and innerHTML to load div content
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"
async function refresh() {
btn.disabled = true;
dynamicPart.innerHTML = "Loading..."
dynamicPart.innerHTML = await(await fetch(url)).text();
setTimeout(refresh,2000);
}
<div id="staticPart">
Here is static part of page
<button id="btn" onclick="refresh()">
Click here to start refreshing every 2s
</button>
</div>
<div id="dynamicPart">Dynamic part</div>
$.ajax(), $.get(), $.post(), $.load() functions of jQuery internally send XML HTTP request.
among these the load() is only dedicated for a particular DOM Element. See jQuery Ajax Doc. A details Q.A. on these are Here .
I use the following to update data from include files in my divs, this requires jQuery, but is by far the best way I have seen and does not mess with focus. Full working code:
Include jQuery in your code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Create the following function:
<script type="text/javascript">
function loadcontent() {
$("#test").load("test.html");
//add more lines / divs
}
</script>
Load the function after the page has loaded; and refresh:
<script type="text/javascript">
$( document ).ready(function() {
loadcontent();
});
setInterval("loadcontent();",120000);
</script>
The interval is in ms, 120000 = 2 minutes.
Use the ID you set in the function in your divs, these must be unique:
<div id="test"></div><br>

Using jQuery on AJAX response data

I'm looking to use jQuery to determine if the current page has changed upstream, and if so, perform some action.
I want to do this by using jQuery selectors over the data returned by an AJAX call (for the purposes of this question, my "page has changed" metric will be "has the content of first <h1> changed").
Thus I find myself wanting to use jQuery selectors over the HTML returned by an AJAX get(). The "best" "solution" I've found thus far is appending the data to some hidden div, and using a selector over that, as below:
var old_title = $('h1').html();
$.get(url, function(data) {
$('#hidden_temporary_storage').append(data);
var new_title = $('#hidden_temporary_storage h1').html();
if (new_title !== old_title) {
do_something();
}
});
This feels so very wrong - I'd be nesting html / head / body tags, and there would be id collisions et cetera.
I have no control over the upstream page, so I can't just "get the data in a more convenient format" alas.
You can do:
var x = $('<div>'+data+'</div>').find('h1').html();
// use x as you like
i.e. you don't need to append the returned data to your page to be able to get properties and values from HTML elements defined within it. This way there would be no id collisions, multiple head/body tags etc.
I think your best bet here is to use an iFrame.
And then use jQuery on the content of that iFrame.
var old_title = $('h1').html();
$.get(url, function(data) {
$('<iframe id="tmpContent"></iframe>').appendTo("html");
$('#tmpContent').contents().find('html').html(data);
var new_title = $('#tmpContent').contents().find('h1').html();
if (new_title !== old_title) {
do_something();
}
$('#tmpContent').remove();
});

How do I apply events and effects to elements generated through Ajax request with no specific id?

I am making a forum and I want it to run like a desktop application, so I do not refresh the page. For lack of a better method without another complete Ajax request I receive the number of pages of data available in an Ajax request. I need to display this data (as I have at ethoma.com/testhome.php -- I set the page size to 1 for testing) but I also need to add event handlers to each individual number displayed to trigger an event that will change the color of the text and trigger an Ajax call to get the page number specified. The challenge for me is that there could be 500 pages (of course then I wouldn't be able to display every page number). For those who don't want to view the code via my site, here is the important parts of it:
function getPosts()
{
var queryString = "category=" + category + "&page=" + page + "&order=" + order;
$.ajax(
{
url: 'getposts.php',
data: queryString,
success: function(data)
{
var oldHtmlTemp;
var dataArray = data.split("%^&$;");
numpage = dataArray[0];
$('#postcontainer').html(dataArray[1]);
$('#enterpage').html('');
if (numpage != 0)
{
for(var i=1;i<=numpage;i++)
{
oldHtmlTemp = $('#enterpage').html();
$('#enterpage').html(oldHtmlTemp + " " + i);
}
oldHtmlTemp = $('#enterpage').html();
$('#enterpage').html(oldHtmlTemp + " ");
}
else
{
$('#enterpage').html('No results for this query');
}
}
});
}
If you are wondering what the .split() is doing, the php doc returns the number of pages seperated by that weird string that I designated. I decided it would be the easiest way to put the number of pages within the rest of the post text.
Anyway how would I add event handlers to these individual numbers?
I have a quick follow-up question, this code isn't working for some weird reason. It adds an event handler to the next page and previous page buttons, but also error checks to make sure you aren't trying to hit page -1.
$("#nextpage").click(function()
{
if (page < numpage -1)
{
page++;
getPosts();
alert(page);
}
});
$("#prevpage").click(function()
{
if (page >= 1);
{
page--;
getPosts();
alert(page);
}
});
Alerts are for debugging. Also worth noting is that when page = 0, you get page 1. What I mean is, I am counting from 0 1 2, but the user sees 1 2 3.
Thanks to anyone who views/answers this post.
I will refer to the last question first.
I didn't understand the followup question as you didn't specify what exactly is not working.
I am guessing you are overriding your "next","prev" while dynamically loading new HTML.
To resolve this, take a look in the "live" jquery method.
What it does is exactly like assigning "click" (like you did) but it re-evaluates the selector on each event. So the new elements will still be included.
I believe the "live" method will work on the first question as well.
Simply wrap each number with some "span" identified by a unique "class". and add something like this :
$(".pagination-number").live("click",function(){
$(".pagination-number").attr("color:black"); // remove previous click color
$(this).attr("color:red"); // mark currently clicked number
.... // load the content
})
When I write an HTML that loads dynamically, I always assign the Javascript to that HTML.
This way - I reevaluate the JS when the new HTML is loaded.
For example - my returned html looks something like
<div class="highlight"> some content here </div>
<script> $(".highlight").effect("highlight",{},300)</script>
The benefit it gives me is that I assign the behavior to the data. (just like in OOP).
I don't need to rewrite the behavior for each time I load the HTML. (in this example to highlight the text).
It will be highlighted each time I load the HTML because the script is evaluated.
You should consider using this design pattern as it will :
Concentrate all your code into a single place
This design pattern overcomes scenarios in which you override a dom object. ( for example, the old HTML has a #prev button, and the new html also has a #prev button. The code will always refer to the most recent dom element hence the behavior will be consistent.

Categories

Resources