Inject GET parameter to target URL of a button, on click - javascript

I have multiple buttons with the class myButton. Each button has a value which is send to a server on click. The target URL of the button does look like this:
http://mysite/test/test.html?cid=15
After I click on the button, the following GET parameter should be added to the URL and then the button should be submitted:
mySessionVar=1
So the new URL should look like this:
http://mysite/test/test.html?cHash=d009eb3f9f4e1020435b96a8f7251ad5&mySessionVar=1
Why I have to inject it?
I am working with fluid. AFAIK it is not possible to manipulate fluid tags with JavaScript. However, I need to add a sessionStorage item value to the fluid tags arguments attribute.
My fluid code:
<f:link.action controller="Download" action="download" arguments="{cid: category.uid}" class="myButton">Download</f:link.action>
So my attempt is to append my sessionStorage item as GET parameter to the target URL of the button and then send it, e.g.:
$(".myButton").on
(
"click",
function(event)
{
//First prevent the default event
event.preventDefault();
...inject the sessionStorage item as GET parameter to the target URL of the button, then do whatever the button would do normally...
//Go to new URL
window.location.replace(NEW URL);
}
);
Is this possible?
EDIT: This is how the rendered HTML of the buttons looks like:
<a class="myButton" href="/de/mysite/test/test.html?tx_mydownloads_myfilelist%5Bcid%5D=15&&tx_mydownloads_myfilelist%5Baction%5D=download&tx_mydownloads_myfilelist%5Bcontroller%5D=Download&cHash=d009eb3f9f4e1020435b96a8f7150ad5">Download</a>
EDIT: I have another idea, maybe I could just read the target URL somehow, then add my new GET param to it and then load that URL with window.location.replace?

You can indeed just use the href from the button and use it to feed window.location.href, like so:
$('.myButton').on('click', function(e) {
e.preventDefault();
var href = $(this).attr('href'),
queryString = 'mySessionVar='+sessionStorage.getItem("myItem"),
newHref;
if (href.indexOf('?') !== -1) {
newHref = href + '&' + queryString;
} else {
newHref = href + '?' + queryString;
}
window.location.href = newHref;
});
This also handles the case when there is no previous query string present on the link and appends it with ? instead of &, but that part can be omitted if that won't happen in your app.

The following snippet should be enough to add your mySessionVar=1 parameter to the href attribute:
$('.myButton').on('click', function(e) {
$(this).attr('href', $(this).attr('href') + "&mySessionVar="+ sessionStorage.getItem('myVar');
});
You don't have to prevent the default, because your click handler function is called before the default event handler (who does roughly speaking: read the href attribute and load it).

You can use .serialize function in jquery which is simple and modern function to get all the selected buttons/filters into a url param format with amberson simple. I can't explain more clear than what is said in Jquery website. Please refer the link below to find how to use the function. https://api.jquery.com/serialize/#serialize

Related

Add "#" hash correctly to url with jquery

I am a bit confused, because I just want to add a hash to an existing url via varibale and open it via a href.
Example:
$( ".MyLink" ).each( function(){
var href = $(this).attr('href');
$(this).attr("href", "https://website.com/subpage#" + href);
});
Result (browser url) after clicking on this link:
https://website.com/subpage/#test
If I am right, a correct hash link should look like this ...
https://website.com/subpage#test
... without the "/" after subpage.
So, I am correct or it doesn't matter? If yes, how can I change it?
I also realized that my browser(s) change my url from https://website.com/subpage#test to https://website.com/subpage/#test if I just add it in the browser bar and press enter. Is that new?
Maybe it is important to know that I use wordpress?
OK, it seemes to be a php/browser/wordpress rule that # become /#, because this script creates an endless refresh-loop for me:
var urlupdate = window.location.href.replace("/#", "#");
window.location.href = urlupdate;
Update: As described in this answer, it shouldn't make a difference if your Javascript was written properly, it seems to be even considered as a best practice. If you want to get rid of it anyways you may want to check your wordpress settings, maybe the second answer of the given question may give you a hint!
In case that the trailing slash comes from the a tag, you could check whether the string in the href attribute starts with a slash and remove it then:
$( ".MyLink" ).each( function(){
var href = $(this).attr('href');
if (href.charAt(0) === '/') {
href = href.substring(1, href.length);
}
$(this).attr("href", "https://website.com/subpage#" + href);
});

Change url using jquery

Сan you explain please.
Why returned, only the first data attribute - "link-1.html", even if I click on the second link
<a class="project-link" href="link-1.html" data-url="link-1.html">
<a class="project-link" href="link-2.html" data-url="link-2.html">
var toUrl = $('.project-link').attr('data-url');
$('a').click(function() {
window.location.hash = toUrl;
});
The meaning of such action - my links open through Ajax, but I want to URL displayed in the browser.
I want to make it as behance, if you click on the cards portfolio, they displayed through Ajax in the same window, but it also left open the possibility of direct appeal to the links. That's why I want to URL displayed in the browser address bar
You have to get current target url by this
$('a').click(function() {
var toUrl = $(this).data('url'); // use this as current target
window.location.hash = toUrl;
});
I recommend you to use .data() when you're retrieving data attributes (only) instead of .attr()
Demo
.attr( attributeName )
Returns: String
Description: Get the value
of an attribute for the first element in the set of matched elements.
$('.project-link') matches more than one element. Therefore, $('.project-link').attr('data-url') will return the value of the data-url attribute for the first element in the set.
To solve this you have maintain the context of the clicked element as you get the attribute, and you do this by using the this keyword.
And if you have other event listeners attached to the element already and you do not want them to fire -- although ajax calls will abort when the user is redirected -- you can use event.stopImmediatePropagation():
$('a').on('click', function( event ) {
event.stopImmediatePropagation();
window.location.hash = $(this).data('url'); //this here refers to the element that was clicked.
});
$('a[data-url]').click(function() {
window.location.href = $(this).data("url");
});
You might want to try this:
$('.project-link').click(function(){
window.location.hash = $(this).data('url');
});

Trying To Add Onclick To Links, But Can't With .onclick

So I'm trying to use ajax to put content into a div, and trying to have it change all internal links before it adds the content so that they will use the funciton and load with ajax instead of navigating to another page. My function is supposed to get the data with ajax, change the href and onclick attributes of the link, then put it into the div... However, all it's doing is changing the href and not adding an onclick attribute at all. Here's what I was using so far:
function loadHTML(url, destination) {
$.get(url, function(data){
html = $(data);
$('a', html).each(function(){
if ( $.isUrlInternal( this.href )){
this.onclick = loadHTML(this.href,"forum_frame"); // I've tried using both a string and just putting the function here, neither seem to work.
this.href = "javascript:void(0)";
}
});
$(destination).html(html);
});
};
Also, I'm using jquery-urlinternal. Just thought that was relevant.
You can get the effect you want with less effort by doing this on your destination element ahead of time:
$(destination).on("click", "A", function(e) {
if ($.isUrlInternal(this.href)) {
e.preventDefault();
loadHTML(this.href, "forum_frame");
}
});
Now any <a> that ends up inside the destination container will be handled automatically, even content added in the future by DOM manipulations.
When setting a function to onclick through js it will not show on the markup as an attribute. However in this case it is not working because the function is not being set correctly. Easy approach to make it work,
....
var theHref=this.href;
this.onclick = function(){loadHTML(theHref,"forum_frame");}
....
simple demo http://jsbin.com/culoviro/1/edit

How do I use a javascript injection to click on links of a specific class?

I have a page with many links that execute certain actions on click. Example:
<a class="x" onclick="somefunction(does_something)" href="javascript:void(0)">x</a>
I want to use a javascript injection to click all of them on the page. So far, I tried:
javascript:document.getElementsByClassName("x")[0].click();
But that doesn't seem to work. What am I doing wrong?
If your JS is inline, you can simply call what you need right in the href...
<a href="javascript:functionName('parameter1','parameter1','parameter1')">
Click to execute JS</a>
...but not wise if the parameters aren't predefined by you. Definitely don't do this if your parameters take user input and update/execute against your database, but it does work.
First of all, I'd suggest using jQuery, it's a lot easier to understand. Next, you can't really 'click' links dynamically and run it's function. You need to simply run a function on all the links and use it's address.
window.open( $('.x').attr( 'href' ), '_blank' );
Iterating through all links and opening them inside a container...
jQuery
$('#some_link_container').find('a').each(function() {
var link = $(this); // This is the current link in the iteration
window.open( link.attr( 'href' ), '_blank' ); // Prepare for mass computer lag
});
HTML
<div id="some_link_container">
A link
A link
A link
A link
</div>
If you are trying to run a function onclick, it's best to use a event listener rather then onclick. Something like the following
Event Listener Demo
Here we listen to a click on any link inside our container, then we run a function.
$('#some_link_container').find('a').each(function() { // Each link inside our div container
var link = $(this); // The current link
link.on('click', function(e) { // When the link is clicked
e.preventDefault(); // Stop the link from forwarding to that page
goodbye( link.attr('href') ); // Run our function onclick
});
});
var goodbye = function(link) {
alert( 'Goodbye guest! Forwarding you to: ' + link );
window.open( link, '_self' );
}

Disable href property using jquery

I want to disable the a link from refreshing the page (i.e. going to the href link). But I want to the url to be modified, as per the href value.
Currently, I am trying this
$('.advertPP').click(function() {
event.preventDefault();
location.href = link.attr("href");
});
HTML Link
Link
Since both are on the same page, so I don't want the page to be refreshed but i want the url to be modified as in the href value.
Your code is full of(logical) errors.
$('.advertPP').click(function(event) {
event.preventDefault();
location.href = this.href; //or $(this).attr("href"), is the same thing, jQuery is not needed in this case
});
Maybe you want your page to change contents without refreshing, so you need AJAX, here is an example:
$('.advertPP').click(function(event) {
event.preventDefault();
$.ajax({
url: this.href,
success: function(data) {
//if the loaded page is a full html page, replace the HTML with the data you requested
$("body").html(data); //make sure your data has only body contents, either you can replace the full HTML even if it is a bad practice $("html").html(data);
}
});
});
Check whether document.URL and $(this).attr('href') are same then set new url and return false.
If both are different them redirect to the page.
$('a').click(function() {
var currentUrl = document.URL
if ($(this).attr('href') == currentUrl) {
$(this).attr('href', 'http://www.google.com');
return false;
}
})
I noticed that you are not passing event object to your function. You should pass the object like this:
$('.advertPP').click(function(event) {
//^^^^^ pass the event object
event.preventDefault();
$(this).attr("href", "http://...");
});

Categories

Resources