1

I want to have both href and onclick working and I found a solution here: HTML tag <a> want to add both href and onclick working

In myFunction, I make an AJAX Request calling a perl component.

It works fine when I put the Javascript call in href, but not when in onclick. Unfortunately, I'm not allowed this solution neither jQuery, so can you please help.

// AJAX Request doesn't work
<a href="www.mysite.com" onclick="myFunction();">Item</a>

<script type="text/javascript">
    function myFunction () {
        var xmlHttp = getXMLHttpObject();
        xmlHttp.open('GET', 'perl.m', true);                
        return true;
    }
</script>

// AJAX Request ok
<a href="javascript: myFunction('www.mysite.com')">Item</a>

<script type="text/javascript">
    function myFunction (url) {
        var xmlHttp = getXMLHttpObject();
        xmlHttp.open('GET', 'perl.m', true);
        window.location.href = goto_url;                
    }
</script>

perl.m:
<%init>
    warn "perl.m";
    ... update ...
</%init>
Community
  • 1
  • 1
Karin Suel
  • 103
  • 2
  • 3
  • 9

2 Answers2

2

Please carefully follow the tutorial. It states that you must enter the javascript like this (with return keyword).

<a href="www.mysite.com" onclick="return theFunction();">Item</a>

Besides that you should always type in a URL (like http://stackoverflow.com).

Please let me know if this supports you.

Markus
  • 763
  • 7
  • 24
  • Thank you, it works now. The new site can be called by click but although by clicking on "New Tab" in the context menue, and then without my Ajax Request. I googled a lot but didn't find a solution yet. It would be great if you could help again. – Karin Suel Aug 08 '14 at 10:30
  • I am happy that my first answer helped you. Do you mind explaining your further question more detailed? Does the opening via context menu (I assume FireFox) work? – Markus Aug 08 '14 at 12:15
0

Try with:

<a href="www.mysite.com" onclick="myFunction(event);">Item</a>

<script type="text/javascript">
    function myFunction (e) {
        e.preventDefault();
        var xmlHttp = getXMLHttpObject();
        xmlHttp.open('GET', 'perl.m', true);                
        return true;
    }
</script>

Because you have href attr with url, so it will go to url and your ajax is not affected. e.preventDefault() is your solution here.

fanfan1609
  • 179
  • 2
  • 8
  • Thank you. I tried e.preventDefault(), the AJAX call works with it. But the URL in href isn't called any more, although the function returns true. – Karin Suel Aug 08 '14 at 08:00
  • Of course that the Url in Href will not access, because you have called Ajax. If you want to access with href attr , please use window.location.href = ; – fanfan1609 Aug 08 '14 at 08:36