How to add a JSP page dynamically on click - javascript

I have a link like follows :
<font size="2"><a class="pull-right" id="pageAdd" href="" title="add new page"><i
class="icon-plus-sign"></i></a></font>
and a jquery script as follows
<script type="text/javascript">
$(document).ready(function(){
$("#pageAdd").click(function() { .................(1)
$.get('WEB-INF/views/diary/createPage.jsp', function(data) {
$("#newPage").html(data);
});
});
});
I am trying to add the createPage.jsp to the following div
<div id="newPage">
</div>
I have debugged using firebug. The execution is going inside the jquery but jumping out after line 1. Any idea what is the problem.

Your JavaScript seems to be okay. At marker (1) you add a function to the onClick Event. When you debug in Firebug, you probably only see your function being added, not being called.
The Link WEB-INF/views/diary/createPage.jsp looks odd to me. Your war file will not serve anything to a browser from inside the WEB-INF directory.
Try moving the file outsite WEB-INF, rebuild your app and test in your browser, if you can manually browse to http://localhost:8080/YOUR_CONTEXT/views/diary/createPage.jsp
Open Firebugs Network view: Can you see a request to views/diary/createPage.jsp? Maybe your JavaScript sends the request to the wrong path due to how relative path are calculated

Your WEB-INF folder is not visible to HTTP calls, try to make the $.get() using /views/diary/createPage.jsp

I think you should also either change the href from "" to "#" or return false in the onclik, otherwise the browser could reload the page and break the script execution.

Related

Page reloads when clicking anchor element

I'm working on a web application which is a traditional aspx (asp.net) web forms app but has had some angular 6 apps incorporated into it.
I've been tasked with fixing a bug that causes the browser to refresh when clicking on an anchor element with a href="#".
I'm not sure what's causing the whole page to reload.
Strangely when I open dev tools in Chrome, choose the network tab and select disable cache the page only refreshes the first time I click a link and any other subsequent clicks work fine. This might be to do with the fact that after the first time I click it the browser url now contains the # at the end of it.
I know this seems a bit random but I wondered whether anyone had any theories on what may cause the reload in the first place.
It's hard to tell what could be causing this without seeing any code. The most common solution I've used when I get this behavior is a prevent default. You can do something like
<a href="#" (click)="$event.preventDefault()">
Or if you already have a click event then pass in $event as a parameter to your function then preventDefault in the function you are calling. This would look like:
Html
<a href="#" (click)="someFunc($event)">
and in your ts:
someFunc(event) {
event.preventDefault();
// rest of your code here
}
This answer is related to the question and it's the first one that comes up in Google so I hope this is useful.
I have some external web components that use regular anchor tags with hrefs that point to routes in my angular app. Clicking the href causes a full page reload. This is because I'm not using routerLink - but, in my case, I can't.
So, my work around is:
#HostListener('window:click', ['$event'])
onClick(e: any) {
const path = e.composedPath() as Array<any>;
const firstAnchor = path.find(p => p.tagName.toLowerCase() === 'a');
if (firstAnchor && !firstAnchor.hasAttribute('routerlink')) {
const href = firstAnchor.getAttribute('href');
this.router.navigateByUrl(href);
e.preventDefault();
}
}
Depending on your application, you might need to make some other checks e.g. is the target _blank, is it an external url etc.
change your a tag code as below
A Tag
this will invoke yourClickEvent(); without page reload
check the stackblitz here stackblitz
If you don't want to reload the page use $event.preventDefault()
<a href="#" (click)="$event.preventDefault()">
Try using debug tools to select the element, then click Event Listeners and then the Click event to see what is listening. Perhaps you can track it down that way.
You could also simply paste this into the console to trigger a break, and then click any of the offending elements:
['unload', 'beforeunload'].forEach(function (evName) {
window.addEventListener(evName, function () {
debugger; // Chance to check everything right before the redirect occurs
});
});
source: Break when window.location changes?
As you are using angular routes, try to use this notation:
<a [routerLink]="['./']" fragment="Test">
As explain by this comment: https://stackoverflow.com/a/38159597/4916355
use href="javascript:void(0);"
The reason you’d want to do this with the href of a link is that normally, a javascript: URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just a short and simple script that evaluates to undefined.
Use [routerLink] instead of using href = "", and use click event to call your calling method in the typescript file.
ex:
// downloading the file based on file name
<a [routerLink]="'file://' + 'path'" (click)="downloadFile(templateDocument.fileName)">{{downloadDocuments.fileName}}</a>
Since you have mentioned the web app is asp.net webforms, can you please let us know
Whether the link is asp.net hyperlink control. If so,
AutoEventWireUp could cause the link to be automatically submitted:
Please have a look at this link
If you do have asp.net server controls on the page, then you could disable by setting
#Page AutoEventWireup="false"
For the entire project, this can be disabled by setting in web.config:

insert image into html on demand via javaScript

I have a html5-document that contains this element:
<div id="imgContainer"></div>
The document loads, the user logs in, and some new text gets loaded and successfully displayed via Ajax (using jQuery). After a while (when the user makes a click) a new image should be inserted into the imgContainer-div.
I do this with this jQuery-command:
$("#imgContainer").html('<img src="newImage.png" alt="">');
The file newImage.png is located in the same directory as the html-file and the javaScript-file. But it does not appear in the browser-window. But it is correctly inserted into the source-code. I checked this with the developer-tools of my browser (safari). This tools don't report any error. But still the image is invisible. When I look into the list of resources I can see no newImage.png. Obviously the browser didn't load it. But why?
The image appears in the browser-window when I enter its URL. So the browser is able to load it. But it does not when I modify the html-document. Why?
Must I add some additional code to ma javaScript to tell the browser to load the image? If so: Can you tell me this code?
Edit:
try here: http://jsfiddle.net/YCs66/1/
http://jsfiddle.net/dwebexperts/ZCL2U/1/
Replace this
$("#imgContainer").html('<img scr="https://www.google.com/textinputassistant/tia.png" alt="">');
with this
$("#imgContainer").html('<img src="https://www.google.com/textinputassistant/tia.png" alt="">');
As I checked in your Fiddle, you have given source attribute as "scr".
The problem with your code is that the .html() method only puts in the HTML without actually parsing the attributes for the DOM element. Here is the solution
HTML
<form name="myForm" action="">
<input type="button" value="click me"
onclick="loadPic()">
</form>
<div id="imgContainer"></div>
Javascript
var loadPic = function () {
alert("loadPic started");
$("#imgContainer").html('<img/>');
$("img").attr("src", "https://www.google.com/textinputassistant/tia.png");
alert("loadPic finished");
};
PLAYGROUND
Note that the <img/> that is performing .attr("src", ...) is an asynchronous function. As a result, 2 alert()s will come out before the actual image is being loaded.

HTML onclick event not loading JavaScript function

So I'm having issues with my onclick function that I wasn't having before. When I originally implemented it on the page, it was working perfectly. Then, once I changed the location of the JS file to a subfolder in the directory, (and changed the location in my HTML) the onclick link I made stopped calling the JS function.
function namePrompt() {
var x=prompt("Enter your first and last name:");
if (x) {
window.location.href = "http://database.gchandel.com/app_edit.php?name="+x;
}
}
Above is the JS code I'm using, and below is the line that calls the function.
<a onclick="namePrompt()">click this link to view your entry.</a>
I've tried everything from moving the file back to its original location, to refreshing the page many times, to changing things like function name and file name and none of this has given me any luck.
Also, here's the link to the site I'm working on: database.gchandel.com
The problem is in your prompt syntax, check it here
Syntax of prompt is
prompt("", "");
While working one is here

How to reload a file via require.js triggered from the browsers js console

Having a text file (underscore templates) loaded by require.js on initial app start:
define(['text!templates/template.html'], function(Template){ ... };
When i am now making changes to this file and want require to reload that single file without me having to reload the whole page and restart the whole app, is this possible?
I'd like to trigger this from the javascript console in the browser.
Use case is a scenario with underscore templates loaded via require.js, when making changes to one of those template files i could easily "inject" the new file to the running app, trigger the views render method manually and see the changes without having to start from the very beginning by reloading everything.
Thanks for your ideas.
RequireJS is not designed for reloading modules, generally speaking.
However, if you design your application carefully you can get RequireJS to reload some modules. Here's an example:
<body>
<p id="contents">Nothing loaded.</p>
<button id="reload">Reload</button>
<script>
require.config({
baseUrl: "./js",
paths: {
jquery: '//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min',
}
});
require(["jquery"], function ($) {
var $contents = $("#contents");
function reload() {
require.undef("text!../file.html");
require(["text!../file.html"], function (file) {
$contents.empty();
$contents.append(file);
});
}
$("#reload").click(reload);
});
</script>
</body>
The key is to call require.undef to undefine the module before reloading it.
I've got a repo illustrating the whole thing. If you edit the file.html file and hit the "Reload" button, the text of the paragraph will be replaced with the contents of the file. To get a function you can invoke form the console just assign it to a field of window (e.g. window.reload).
The button should really be called Load/Reload (because it does the initial loading and the reloading) but I'm not going to fix it.
Object.keys(require.s.contexts._.defined).forEach(k => require.undef(k))
This will remove all cache

How can I log a hyperlink click?

I have a hyperlink which I need to log when it's clicked.
I created a small prototype, and the problem is repeatable by creating a new MVC 2 Web app project.
Add
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
to the Site.Master file.
And
public ActionResult LogSomething()
{
string doNothing = DateTime.Now.ToString();
return new EmptyResult();
}
to the HomeController.cs file
And
<p>
<a id="lnkTestPost" href="/home/about">Test Post</a>
<script type="text/javascript">
$("#lnkTestPost").click(function() {
$.post("/home/LogSomething");
});
</script>
</p>
in Home/Index.aspx
Put a break point in the LogSomething() action method in the HomeController.
But when I run it, sometimes the breakpoint is hit, other times it isn't.
I'm assuming it's not being hit due to the actual link sending the browser to another page, but shouldn't the post be made before the link is fired?
Is there anyway I can ensure the logging code is fired?
Please note; adding the logging functionality in the link target is not an option.
EDIT: The original hyperlink is actually to a custom protocol for an app installed on the user PC. So the link is to something like "myapp:myArgs". I didn't mention that in order to keep things simple, unfortunately, since none of the answers really apply to me, I now think it's necessary to mention.
If I were doing it, I would probably do what, eg, Google does and setup a URL which logs then redirects. For example:
stuff
<script>
$("a:href").each(function(){
this.attr("href", "/log?url=" + encodeURIComponent(this.attr("href")));
});
</script>
Then /log handler would do something like:
def log(request):
target_url = request.GET["url"]
log_link(target_url)
return HttpRedirect(target_url)
You'd need to put some thought into dealing with external links (eg, how you want to handle http://example.com/log?url=http://evil.com/)… But that's a solvable problem.
Also, for bonus points, you could swap the URL as the link is clicked (this is what Google does in their search results), so the mouse-over link-preview looks correct.
Alternatively, you could do what Google Reader does, and put a "from url" in each link:
<script>
$("a:href").each(function(){
this.attr("href", this.attr("href") + "?from=" + encodeURIComponent(window.location));
// (note: this exact code won't handle links which already have GET vars…)
});
</script>
Then use some middleware to log the "from" in inbound requests.
This has the disadvantage that it won't be able to log clicks going to another domain… But that might be alright.
I think the browser could easily navigate to the URL before logging the click. How about:
<p>
<a id="lnkTestPost" href="#">Test Post</a>
<script type="text/javascript">
$("#lnkTestPost").click(function() {
$.post("/home/LogSomething", function(data) {
// only tell the browse to navigate away once its logged
window.location = '/home/about';
});
});
</script>
</p>
An approach that I have seen used by many sites, including google, is to have a "redirector" page, so all the links go through that page/controller, you log it, then from there you can redirect them
How 'bout an optional "log" parm on each page that is included as part of the links so you don't have to have any Javascript at all? Granted, each page could be logging something from the referrer page, but it shouldn't care, since you could have it just pass off whatever's in the log parm to the logging infra and go on.

Categories