skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

        <script>
    
    
    async function readHTMLPage(url) {
      try {
        const response = await fetch(url); // Fetch the HTML page
        if (!response.ok) {
          throw new Error('Error: ' + response.status);
        }
    
        const htmlContent = await response.text(); // Get the HTML content as text
        return htmlContent;
      } catch (error) {
        console.error('Error:', error);
        return null; // Return null if an error occurs
      }
    }
    
    
    function ConfirmDialog(message,url) {
      let text2="";
    
    $.get( "confirmaddress.cfm", function( data ) {
        // the contents is now in the variable data
        //alert( data );
        console.log(data);
    });
    
    (async function() {
      text2 = await readHTMLPage("confirmaddress.html?latlon="+message);
    
    $('<div></div>').appendTo('body')
        //.html('<div><h6>' + message + '</h6></div>')
        .html('<div><h6> Is address correct: </h6></div>')
        .append(text2)
        .dialog({
          modal: true,
          title: 'Confirm 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>');
          window.open(url, "myWindow", "width=600,height=400");
              $(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>
    

  2. 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:

    $.get("confirmaddress.html", function (data) {
      text = data;
      console.log(text); // logs data
    });
    
    console.log(text); // logs "Test"
    

    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:

    $.get("confirmaddress.html", function (data) {
      var text = data;
      doSomethingWithText(text);
    });
    
    function doSomethingWithText(text) {
      console.log(text);
    }
    

    In your case, you can try this:

    function ConfirmDialog(message) {
      $.get("confirmaddress.html", function (data) {
        createConfirmDialog(message, data);
      });
    }
    
    function createConfirmDialog(message, data) {
      $("<div></div>")
        .appendTo("body")
        .html("<div><h6>" + message + "?</h6></div>")
        //.load('confirmaddress.html');
        .append(data)
        .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();
          },
        });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search