KP Joy KP Joy - 5 months ago 15
jQuery Question

How to automatically close the new popup window in Javascript and PHP?

I have a main window (

main.php
) on which there is a link, clicking on which opens a new popup window (
newpopup.php
).

<a href="" onclick="openNewPopUpWindow()">Open New Popup Window</a>

function openNewPopUpWindow()
{
window.open("newpopup.php", "_blank", "height=340, width=600, status=yes, toolbar=no, menubar=no, location=no, addressbar=no, top=250, left=500");
}


Now, in this
newpopup.php
, I am updating some records by firing
MYSQL
query. My requirement is that, as soon as the query is fired and database is updated, this window should get automatically closed and my parent window
main.php
should get refreshed.

Following is the simple code snippet for
newpopup.php
file:

<?php
$query="UPDATE users SET isActive = 1";
$mydb->dbnonquery($con, $query);
header("Location:http://localhost/myProject/main.php");
?>


But, this code is not working. After the query is fired successfully, window is not getting closed and main window is also not getting refreshed.

Update:

I am able to close my newpopup.php window by ajax request.

$.ajax({
type: "POST",
url: "process_newpopup.php",
data: {"param1" : myparameter},
success: function (data)
{
window.close();
}
});


I have taken my PHP logic to update database in the
process_newpopup.php
file. When this logic is executed,
window.close()
method is executed. So, half of the problem is resolved. Now only problem persisting is how should I refresh my main page (
main.php
)?

Update 2:

$.ajax({
type: "POST",
url: "process_newpopup.php",
data: {"param1" : myparameter},
success: function (data)
{
window.opener.location.reload();
window.close();
}
});


Adding
window.opener.location.reload();
solved my second part of problem that is to refresh the parent window.

Answer

this string header("Location:http://localhost/myProject/main.php");

it's redirect header, so if you didn't output anything before it

for example: some text, or php notices, content of newpopup.php will be replaced by main.php

you have to change newpopup.php

<?php
   $query="UPDATE users SET isActive = 1";
  // where is $mydb variable defined?
  $mydb->dbnonquery($con, $query);
?>

<script>
   // works on chrome, will reload opener window main.php
   // don't forget this will be work only on same domain (read about cors)
   window.opener.location.reload();
   // will close current window, but not refreshes parent
   window.close();
</script>
Comments