0

I have two files:

example.html:

<div class="my-div"></div>
<script type="text/javascript">
$(document).ready(function() {
    $.ajax({
        url: "example1.html",
        type: "get",
        success: function(response) {
            $(".my-div").html(response);
        }
    });

    $(document).on("click", "button", function() {
        console.log(alpha); // Should print "data", 
    });
});
</script>

example1.html:

<button></button>
<script type="text/javascript">
$(document).ready(function() {
    var myDropzone = new Dropzone("", {
        success: function(file, response) {
            const alpha = "data";
        }
    });
});
</script>

In example.html, I need console.log(alpha) to output "data". I make an Ajax request to example1.html, and update the contents of my div with the returned html. The constant alpha isn't useable until new Dropzone() succeeds. How can I make this code work?

dǝɥɔS ʇoıןןƎ
  • 1,674
  • 5
  • 19
  • 42
  • 1
    My personal opinion, what you want to do is a pretty bad idea. Even if it would work, the variable alpha is scoped to the success callback, it is not global so the button would not be able to see it. – epascarello Feb 01 '18 at 04:34
  • Thanks @epascarello. I understand your concerns, a better way to do this would probably be to follow [this](https://stackoverflow.com/a/28478146/7304372) answer's suggestions. – dǝɥɔS ʇoıןןƎ Feb 01 '18 at 13:31

1 Answers1

1

One option is to make your alpha variable global.

You declared your alpha variable inside success function so you can only use that variable inside it.

<button></button>
<script type="text/javascript">
const alpha; /* Init it here */

$(document).ready(function() {
    var myDropzone = new Dropzone("", {
        success: function(file, response) {
            alpha = "data"; /* Assign the value here */
        }
    });
});
</script>

Now you can access it as

$(document).on("click", "button", function() {
    console.log(alpha); // Should print "data", 
});
Eddie
  • 26,593
  • 6
  • 36
  • 58