Reputation: 675
So I know that when you put a URL in the action of an HTML form it will send the users to that url. I also added in the target attribute target="_blank"
to open the new URL in a new window. But I want to close that window and stay on the original site where the form was submitted form. I tried to do this by naming the target window and closing it but that didn't work out. I am wondering if there is a simple way to do this.
<form name="leds" id="ledSend" method="get" target="newWindow" action="https://agent.electricimp.com/NkzPvVKeHshT">
Lamp Control: <input type="radio" name="led" value="0" checked>Off
<input type="radio" name="led" value="1">On<br>
How long should the Lights stay on? <input type="text" name="timer" value="10">seconds<br>
Your name? For Our Records <input id="name" type="text" name="user" placeholder="Your name here"><br>
<input type="submit" value="Update!" onclick="alert(theInput.value +', You are about to change the Light! Keep in mind that there will be about a 2 second delay on the LiveStream.')"/>
<script>
var theInput = document.getElementById("name");
</script>
</form>
<script>
newWindow.close();
</script>
Upvotes: 0
Views: 6162
Reputation: 484
another solution, besides the ajax obvious one is using an inner hidden iframe as the target property of the form element. this way the form will open in a hidden inner element. e.g.:
<form id="eFrm" target="ifrm1">
</form>
<iframe id="ifrm1" name="ifrm1" style="display:none"></iframe>
Upvotes: 7
Reputation: 4133
AJAX request suggested by baao is the way to go, but it has a caveat. The browser won't allow to pass your AJAX request if the target server is on a different domain. To solve the problem it should provide correct CORS headers.
If target server is out of your control, you can make a proxy on your own server and call it instead of the current 3rd-party server. This will allow you to simplify things even further by making proxy at the same address as the page with the form.
Upvotes: 0
Reputation: 73241
Here is what you need, simply adjust it to your needs, create a php file that gets called within the action and let it do what you would do with your form - exactly the same way, but stay on the same page:
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data)
{
//data: return data from server
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#ajaxform").submit();
You need to include jQuery to your file to use this!
As you are using GET in your form - with this submission you will get the data in your $_POST.
Upvotes: 2