Timblebop
Timblebop

Reputation: 47

Javascript on click - two parts to the function but only one works at a time

I have two server side php scripts: 1: /addit.php - which creates a pdf file on server based on current ID given 2: /viewit.php - which downloads the pdf file to the browser window.

Both these scripts work fine btw. However I want to combine a single onclick function to run "addit.php" and then view the file by opening the file "view.php". So I am using the original code that was creating the file ok and then adding in a window.location but they won't work together. If I remove the window.location the first part of code works fine, If I include it, the first part stops working and only the window.location works.

Sorry for being stupid, thanks.

function download_invoice() {
    $(document).on('click','.downloadit',function(id){
        var current_element = $(this);
        var id = $(this).attr('id');
        var ida = $(this).attr('id')+"A";
        var idicon = $(this).attr('id')+"icon";

        $.post('myaddress/addit.php',
           { list_entry_id: id },
            $("#infobox_data_button2").fadeTo(1001,.33)
        );
    });

    window.location="myaddress/viewit.php";
};

Upvotes: 1

Views: 63

Answers (2)

RPichioli
RPichioli

Reputation: 3345

The window.location is out of the event. While you run the ajax (asynchronous) to 'myaddress/addit.php' the redirect will occur killing the process.

You need to put the window.location in a success callback, therefore in the event.

function download_invoice() {
    $(document).on('click','.downloadit',function(id){
        var current_element = $(this);
        var id = $(this).attr('id');
        var ida = $(this).attr('id')+"A";
        var idicon = $(this).attr('id')+"icon";

        $.post('myaddress/addit.php', { list_entry_id: id }, function(data){
            $("#infobox_data_button2").fadeTo(1001,.33);
          
            // Here!
            window.location="myaddress/viewit.php";
        });
    });
    // Abandoned
    //window.location="myaddress/viewit.php";
};

Upvotes: 2

Nikolay Ermakov
Nikolay Ermakov

Reputation: 5061

You should move window.location="myaddress/viewit.php"; to ajax callback as below. Otherwise it fires before you get response from server.

$.post('myaddress/addit.php',
     { list_entry_id: id },
     function() {
        $("#infobox_data_button2").fadeTo(1001,.33);
        window.location="myaddress/viewit.php";
     }
);

Upvotes: 3

Related Questions