Sorry for possibly basic question as I’m not very familiar with JS syntacsys.
I need to use a Javascript confirmation form with a dynamic text line taken from another page on the same server. The code I’m trying to use as below:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script>
function ConfirmDialog(message) {
var text = "Test"
$.get( "confirmaddress.html", function( data ) {
// the contents is now in the variable data
text=data;
});
$('<div></div>').appendTo('body')
.html('<div><h6>' + message + '?</h6></div>')
//.load('confirmaddress.html');
.append(text)
.dialog({
modal: true,
title: 'Address',
zIndex: 10000,
autoOpen: true,
width: 'auto',
resizable: false,
buttons: {
Yes: function() {
// $(obj).removeAttr('onclick');
// $(obj).parents('.Parent').remove();
$('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');
$(this).dialog("close");
},
No: function() {
$('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');
$(this).dialog("close");
}
},
close: function(event, ui) {
$(this).remove();
}
});
};
</script>
However, the variable ‘text’ always stays static and doesn’t update its value from addressconfirm.html page. I know it shall be a very simple fix and I appreciate if the community point my mistake.
2
Answers
after some investigations I have realized that the problem is related to two asynchronous functions running in parallel. As a result the fort construction is finishing before the page request therefore the dynamic form form doesn't contain the external page contain. The solution is to wait for the external page content to complete before constructing the form. Working code as below:
In your code, you are using a callback function, but you are also trying to return the data from it. This will not work, because the return statement only applies to the callback function, not to the outer function. You need to use the data inside the callback function, or pass it to another function that can handle it.
For example:
UPDATED ANSWER
Using global variables is generally not a good practice, because it can lead to conflicts, errors, and security issues. A better approach would be to use a local variable and pass it to another function that can handle it.
For example:
In your case, you can try this: