I currently have this code to prevent normal form submission and instead retrieve the desired output from an API. However, I am then trying to set this data as a variable so a button click can redirect there (output data is a URL). I have the following code, but it doesn’t seem to work. Any thoughts?
var tourl;
$("form#surlform").submit(function(){
var url = $("input#url").val();
$.get("api/create.php?url=" + url, function(data) {
$("input#url").val(data);
$("input#url").select();
$('#button').hide();
$('#hbutton').show();
var tourl = data;
});
return false;
});
});
$('#hbutton').bind('click', function() {
window.location = tourl;
});
You need to move the
bindcall inside the success event handler:Firstly,
tourlis scoped to the success event handler. It won’t be available outside of that function.Secondly, since your making an AJAX request,
tourlwill beundefineduntil that request returns a response. The only way to be suretourlhas been assigned its value is to wait until the callback to do anything that depends upon it.As noted in the comments, this will bind multiple event handlers to your button if the AJAX request is executed multiple times. To get around that, you can unbind the event handler before binding the new one.