0

how can I make sure that my AJAX post ($.ajax) runs (sends a variable to my PHP file, and then AFTER that it runs the PHP file?

HTML/JS:

<script>
    $(document).ready(function() {
        $("#savebutton").click(function(e) {
            var jsonString = localStorage.getItem("jsonData");
            console.log(jsonString)
            $.ajax({
                type: "POST",
                url: 'savefile.php',
                async: false,
                data: {
                    jsondata: jsonString,
                    name: 'test',
                    "test": "test2.."
                },
                success: function(data) {
                    alert(data);
                },
                fail: function() {
                    alert("error")
                }
            });
        })
    })
</script>

PHP:

<?php
header('Content-type: text/plain');
header('Content-disposition: attachment; filename="cookieclicker-save.txt"');
print_r($_POST);
?>

HTML Input Button:

<form method="post" action="savefile.php">
    <input class="buttonred" id="savebutton" type="submit" name="submit" value="Backup Savefile" style="float:left">
</form>

A few notes: The data variable in the alert(data) function, shows the exact response I'm expecting, however, the file that is being downloaded in the PHP file, shows an empty array. I'm guessing this is because the PHP file is being ran before the AJAX call. Could someone help me out here? I really need that Javascript variable in my PHP file. Thanks!

WoJo
  • 500
  • 1
  • 3
  • 20
  • 2
    PHP code doesn't certainly do anything before the request is sent. Then the server handles the request, and sends the response, which the client receives and `success` function is executed. – Teemu Feb 09 '21 at 21:01
  • That's odd though. Because the success response should essentially be the same as the contents of the file downloaded then, right? – WoJo Feb 09 '21 at 21:02
  • 3
    You're guessing wrong. How could the PHP script run before the AJAX request -- how would it know that there's an AJAX request coming? – Barmar Feb 09 '21 at 21:02
  • 1
    The only thing that should be in the alert is the output of `print_r($_POST)` – Barmar Feb 09 '21 at 21:02
  • 4
    You need to add `e.preventDefault()` to the click handler. Otherwise the form gets submitted normally with no parameters. – Barmar Feb 09 '21 at 21:04
  • 2
    Note that `Content-disposition: attachment` has no effect in AJAX. – Barmar Feb 09 '21 at 21:05
  • https://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax – epascarello Feb 09 '21 at 21:06
  • 2
    The PHP script is being executed twice. First by `$.ajax()` when it sends the parameters and alerts the response. Second by normal form submission, with no parameters, and it downloads an empty file. – Barmar Feb 09 '21 at 21:07
  • Thanks @Barmar, but adding `e.preventDefault()` just removes the redirect to PHP entirely and only shows the success alert unfortunately. I've also tried changing the submit button to `type="button"` but it had no success, unless I did it wrong. I just don't know how to solve it. I've been chewing on this for the entire day haha – WoJo Feb 09 '21 at 21:09
  • 1
    That's what `preventDefault()` is supposed to do. Either you use AJAX or normal form submission, not both. – Barmar Feb 09 '21 at 21:11
  • It seems that the AJAX call is now not redirecting at all (even with `preventDefault()` removed). I have no idea what I did wrong but it seems that now only the form is redirecting. I'll try to fix it. Also, why was this post closed? The "duplicate" is about downloading a file with AJAX, this is about sending a JS var to PHP and then downloading a file in PHP. – WoJo Feb 09 '21 at 21:22
  • @WoJo: What do you mean by "downloading a file in PHP"? The code shown is PHP attempting to respond to the request with a file, and the request is an AJAX request. What exactly are you trying to accomplish in this code? – David Feb 09 '21 at 21:29
  • @David I initially wanted to download a file with a Javascript variable in PHP. So the code to download the file is in PHP (and has to stay in PHP). But to pass the Javascript variable to PHP I had to use AJAX. So now I'm trying to accomplish the following: User clicks a button, AJAX sends JSON String to PHP, PHP then downloads the file to the users computer containing the JSON String. – WoJo Feb 09 '21 at 21:32
  • @WoJo: So you want to make an AJAX request, and you want the response to be a file? That would be downloading a file with AJAX. You're confusing the terminology, PHP isn't "downloading" the file it's responding with the file. The AJAX operation is downloading the file *from* the server-side PHP code. The linked duplicate goes into detail on how to download a file with an AJAX request in jQuery. – David Feb 09 '21 at 21:34
  • @David Thanks, I know what you mean know and why this post was marked as a duplicate. I'm just not sure how to apply the solution of the linked duplicate to my issue yet, but I'll try to figure that out now. Thanks! – WoJo Feb 09 '21 at 21:39

0 Answers0