Close opened pop-up window on form submission and trigger click on the parent window

ぐ巨炮叔叔 提交于 2019-12-05 18:09:07

The new window (popup) you have opened will load a new HTML page on submit (the function of the jQuery submit call is executed before the form is sent to the sever).

You shall do the actions within the new page being loaded in the popup window.

This would be helpful for others in the future. I was able to achieve this myself by just modifying the above code to the code given below:

// parent window handling of information returned from the pop-up window
function HandlePopupResult(value) {
    alert("The field value is: " + value);
    $("input[value='Search']").trigger("click");
}

Changed the form submission to an AJAX post call to ensure that the form submission has occurred and then carry out my remaining tasks of Handling the result of the pop-up window after which I close the popup window. Works like a charm!

//pop-up window handling of information to be returned to the parent window on submission
$("#myForm").submit(function() {
        $.ajax({
          type: 'POST',
          url: $(this).attr('action'),
          data: $(this).serialize(),
          success: function(data) {
            window.opener.HandlePopupResult($("#field").val());
            window.close();
          }
        });
        return false;
      });

Another way to simplify that some would be using the $.post method instead. Saves a few lines, but achieves the same thing.

$.post( url, data, callback);

$.post( $( "#myForm" ).attr('action'), $( "#myForm" ).serialize(), function(){
        window.opener.HandlePopupResult($("#field").val());
        window.close();
});

You can either throw that inside of your .submit as a shorthand replacement for the AJAX request, or throw it into its own function that you call from your form.

<form onsubmit="submitHandler(this); return false" name="myForm" id="myForm">

You can also combine it with JSON to add some further functionality/validation before you have it sending things back to your main page, which could be helpful in many situations. As well, it's an awesome way of returning data from your PHP (or whatever you use) scripts back to your JS/jQuery.

$.post( $( "#myForm" ).attr('action'), $( "#myForm" ).serialize(), function(data){
      if(data.status == 'failed')
      {
        // Lets present an error, or whatever we want
      }
      else
      {
       // Success! Continue as we were
        window.opener.HandlePopupResult($("#field").val());
        window.close();
      }
}, 'json');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!