0

I have a webpage with AJAX loaded content. If I click on "export" the content reloads and generate an HTML a-Element using PHP:

<a style=\"display:none;\" id=\"menue-export-link\" href=\"download/".$this->select->downloadcsv."\"></a>

Now I want to start the download automatically, so I wrote the following JavaScript code to start the download on a-Element load:

$(document).ready(function () {
    $(document).on('load', '#menue-export-link', function() {
        console.log('click export');
        $('#menue-export-link').click();
        $('#menue-export-link').remove();
    });
});

But nothing happens, does somebody have any idea?

Gargaroz
  • 313
  • 9
  • 28
Philipp Nies
  • 945
  • 4
  • 20
  • 38

3 Answers3

0
$(document).on("click", "#menue-export-link", function() {
  console.log("click export");
});
SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73
Paul Booblick
  • 363
  • 1
  • 7
0

Your js is triggered when your main page is loaded and #menue-export-link probably does not exist to that time. If using $.ajax to load that link, place your javascript inside the success callback to make sure that your link exists or is being loaded before triggering your code.

The F
  • 3,647
  • 1
  • 20
  • 28
  • Thanks, it was actually to easy :D – Philipp Nies Sep 07 '15 at 10:28
  • I resolved it like this: ` if($('#menue-export-link').length) { console.log('click export'); $('#menue-export-link').click(); } ` – Philipp Nies Sep 07 '15 at 10:31
  • Glad it works. However, next time try to solve it using the tools given by jQuery. We could help you more if you'd share your actual ajax call. Ashraf shared some nice recources as well. – The F Sep 07 '15 at 10:33
0

First of all there is no load or onload event for html anchor elements. So as @The F said you have to trigger the download in your ajax success callback. Remember to find and trigger it after you have appended the html in your DOM. For more on jQuery ajax http://api.jquery.com/jquery.ajax/

And now comes triggering the download part. Triggering the click event which causes the navigation is a bit trickier. The following question answers that very well jQuery: how to trigger anchor link's click event and How can I simulate an anchor click via jquery?

Community
  • 1
  • 1
Ashraf Purno
  • 1,065
  • 6
  • 11