php - Javascript - href action executes on linked page

947

We're using a custom built eCommerce CMS that uses:

<a href="javascript:AddToBasket(3471412104801);">Add to Cart</a>

...to add a product to the cart (let's call it Site A). We're building a seperate site (Site B) for one of our products, and I need to come up with a way to link the 'Order' button on Site B so that it calls the above javascript function once Site A loads, using that product ID.

Something along the lines of the following psuedo-code:

<a href="http://example.com/success#javascript:AddToBasket(3471412104801);">
    Add To Cart
</a>

I'm basing that on how HTML anchor links work, but I'm sure it can't be as easy as that.... Right?

I've come across solutions that relate to 'injections', which I don't have much experience in, but the general sentiment seems to be negative, citing security issues and hacking as the main problems. This may sound silly, but both websites are ours, and we control them. If we need to add something the Success page on Site A, that's possible.

943

Answer

Solution:

One method would be to openhttp://example.com/success within yourAddToBasket() function:

function AddToBasket(id) {
    window.open('http://example.com/success', '_blank');

    ...
}

The downside of this is that the JavaScript isn't executed after your other page opens, but rather your page opens during the execution of your JavaScript.

60

Answer

Solution:

Not sure if this helps but you can use the onclick attribute on the anchor.

     <a href="fallbackurl" onclick="AddToBasket(3471412104801);">Add to Cart</a>

When you click the anchor it will trigger the function.

People are also looking for solutions to the problem: php - Laravel 4 large Route count increases booting time

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.