dǝɥɔS ʇoıןןƎ
dǝɥɔS ʇoıןןƎ

Reputation: 1810

Use variable from Ajax response

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?

Upvotes: 0

Views: 150

Answers (1)

Eddie
Eddie

Reputation: 26844

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", 
});

Upvotes: 1

Related Questions