Change page after submitting the form using javascript - javascript

I have a form that after submitting goes to page "http://qwertyasdfgh.rozblog.com/New_Post" ( the action value )
I don't want to change the action but I want to redirect to another page after submitting.
I tried to redirect to "http://qwerty.rozblog.com/page/success" after submitting but it doesn't work .
here is the code I tried :
(html)
<form method="post" action="http://qwertyasdfgh.rozblog.com/New_Post" id="f1">
<input type="text" name="title" style="width:300px"><br />
<input type="text" name="pimg" style="width:300px" maxlength="3072"><br />
<textarea dir="rtl" id="post" name="post" style="width:300px;" aria-hidden="true"></textarea><br />
<input type="submit" name="postsubmit" value=" submit " style="background:#333;" onclick="location()">
</form>
(js)
function location() {
window.location.replace("http://qwerty.rozblog.com/page/success");
}
and here is the fiddle

You can submit the form using jquery and AJAX (or I misunderstood you):
$('#f1').submit(function(e)
{
e.preventDefault();
$.post('http://qwertyasdfgh.rozblog.com/New_Post',
formDataAsJSON, //use eg. jquery form plugin
function(data)
{
window.location = 'somewhere';
}
);
});

You have two choices.
1) Submit that form using AJAX and after recieving response from server redirect browser to your desired page. You can use for example jQuery with Ajax form plugin. The code would look like this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'f1' form and provide a simple callback function
$('#f1').ajaxForm(function() {
window.location = "/page/success"
});
});
</script>
OR
2) You can leave your form and js as is, and use for example php to redirect user after doing some stuff.
New_post.php
<?php
// some stuff without printing (you cant change headers if you print something)
Header("Location: /page/success");

If possible, you can configure /New_Post to redirect to /page/success using meta refreshing in head:
<meta http-equiv="refresh" content="0; url=http://qwerty.rozblog.com/page/success">

Related

What is the proper way to submit a form with JS and still post all form data successfully?

I'm working with an embedded app on our dev site and when I click the submit button inside the iframe, I am triggering a manual submission event on another form (not in an iframe) on that page. If I manually click the submit button for the form, my data posts and everything works correctly. However, I want to eliminate an extra user click and submit the external form automatically when a user submits the other form inside the iframe.
I've got everything working correctly on a base level. When a user clicks the submit button in the iframe, I am using JQuery to grab values from inside the iframe and set values in this external form. Using the jquery 'submit()' event, I am then able to submit that external form. The problem is, the page refreshes and the data doesn't go anywhere. If I remove the 'submit()' event and manually click the submit button, the form posts and in this case, adds a product with custom data to the product cart.
As a proof of concept, this is my 'iframed' HTML.
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Proof of Concept</h1>
<p>Total cost: $<span id="cust_price">222.22</span> plus shipping.</p>
<p>Quote number: <span id="quot_num">1546751962211</p>
<form method="POST" enctype="multipart/form-data" id="newQuoteForm">
<button type="submit" class="btn btn-primary" name="new-app-btn">Add to Cart</button>
</form>
</body>
<footer>
</footer>
</html>
Here is my on-page form that is OUTSIDE the iFrame.
<form method="POST" enctype="multipart/form-data" id="outer-quote-form" action="/checkout/">
<label class="quote_number">Quote Number:
<input type="text" id="quote_number" name="quote_number" value="">
</label>
<label class="custom_price">price:
<input type="text" id="custom_price" name="custom_price" value="">
</label>
<button type="submit" class="btn btn-primary" name="ws-add-to-cart">Add to Cart</button>
</form>
Then, I have JQuery working to grab the iframed values and puts them in the exterior form. Afterwards, it fires a 'submit()' event on that form.
<script>
jQuery('#newQuoteApp').load(function() {
var iFrameDOM = jQuery("iframe#newQuoteApp").contents();
jQuery('#newQuoteApp').contents().find('#newQuoteForm').submit(function() {
jQuery("input#custom_price").val(jQuery('#newQuoteApp').contents().find('#cust_price').text()); // updated
jQuery("input#quote_number").val(jQuery('#newQuoteApp').contents().find('#quot_num').text());
jQuery("#outer-quote-form").submit();
return true; //return false prevents submit
});
});
</script>
Except when the jquery submit() event fires, the form appears to submit and the page refreshes but no data is posting as it does when I manually submit the form. Is there an extra step here or a better way to fire the form submit with post data?
Edit: Adding the PHP function that isn't firing on jquery submit() for context.
if (isset($_POST['ws-add-to-cart'])) {
add_action( 'init', 'add_product_to_cart' );
function add_product_to_cart() {
global $woocommerce;
global $product;
$product_id = 138;
$woocommerce->cart->add_to_cart($product_id);
}
header("Location:https://www.devsite.com/checkout/");
}
The reason for the form not submitting because you are submitting the whole form without the submit button which is <button type="submit" class="btn btn-primary" name="ws-add-to-cart">Add to Cart</button> which you have declared in php to get a post request like this
if (isset($_POST['ws-add-to-cart'])) {...
When you call submit(); on the form via the get method, you see '/new-quote/?quote_number=1546751962211&custom_price=222.22'
but where's ws-add-to-cart, it's not submitting and that's the reason why php isn't getting your request
The fix will be to add .click() on the submit button instead of submitting the form
<script>
function enterVals($val){
var price = $val.price;
document.getElementById("quote_number").value = $val.num
document.getElementById("custom_price").value = $val.price
document.getElementsByName("ws-add-to-cart").click();
}
</script>
Or in your script in case you want to use jquery, this is the fix
<script>
jQuery('#newQuoteApp').load(function() {
var iFrameDOM = jQuery("iframe#newQuoteApp").contents();
jQuery('#newQuoteApp').contents().find('#newQuoteForm').submit(function() {
jQuery("input#custom_price").val(jQuery('#newQuoteApp').contents().find('#cust_price').text()); // updated
jQuery("input#quote_number").val(jQuery('#newQuoteApp').contents().find('#quot_num').text());
jQuery("button[name=ws-add-to-cart]").click();
return true; //return false prevents submit
});
});
</script>
This is definitely the answer and sorry for my stupidity, i didn't pay required attention before
try removing return true from your js code
if that doesn't work, try changing the <form method="POST" to <form method="GET" to debug the values in the url just for checking that the form actually fires up with values
Alternative method: Old school method
code for page OUTSIDE the Iframe
<script>
function enterVals($val){
var price = $val.price;
document.getElementById("quote_number").value = $val.num
document.getElementById("custom_price").value = $val.price
document.getElementById("outer-quote-form").submit();
}
</script>
code for the Iframe file
<script type="text/javascript">
$('#newQuoteForm').on('submit', function(event) {
var Page = window.parent;
var allVals = {
price:$('#cust_price').text(),
num:$('#quot_num').text()
}
Page.enterVals(allVals);
event.preventDefault();
});
</script>
Explanation
window.parent refers to the parent window where the iframe is loaded on, with reference to this we can trigger functions that are in the parent window so by this, we created a variable and added the information which is sent by the function enterVals() to the window
The enterVals() function just puts the values and submits the form without any jQuery.
What is the proper way to submit a form with JS?
This might not be the 'best' way to submit a form with js but is cross-browser which is good

Send HTML form to external service

I've got a request to figure out if it's possible to send excisting HTML forms to an external service without losing the current form handling on the website.
Basically the idea is:
Visitor fills in form
Form data is send to external webapplication which does it's own form handling
Form continues to execute it's own POST data on the website itself (sending emails to visitor etc)
I'm looking for some input on step 2. I'm requested to build a simple dashboard that saves all the form data with an export functionality but they want to keep all the current form handling on the website as well.
I'm hoping someone can give me some input on what to look for as in keywords to google or some techniques to check out.
Thanks in advance
Maybe the following code is helpfull
<html>
<head>
<script language="Javascript">
<!--
function OnButton1()
{
document.Form1.action = "response1.php"
// document.Form1.target = "_blank"; // Open in a new window
document.Form1.submit(); // Submit the page
return true;
}
function OnButton2()
{
document.Form1.action = ""
document.Form1.submit(); // Submit the page
return true;
}
-->
</script>
<noscript>You need Javascript enabled for this to work</noscript>
</head>
<body>
<!-- create the form -->
<form name="Form1" method="post">
<!-- Add the data entry bits -->
Your Name <input type="text" name="name" size="10" /><br />
<!-- Add some buttons -->
<INPUT type="button" value="Button1" name=name onclick="OnButton1(); OnButton2();">
<!-- close the form -->
</form>
</body>
</html>
Found it here
Idea is to read the data that is needed to post and to the external and local site first then post it with help of AJAX request that would be much better (as shown below).
Or have two forms once user click submit populate both forms and the submit request programatically.
<div>
<form action="" id="helloForm">
Enter Text: <input type="text" id="txt" />
<input type="button" value="submit" id="submitButton"/>
</form>
</div>
$("#submitButton").click(function(e){
//extract data
var data = {
text: $("#txt").val()
};
alert(JSON.stringify(data));
//make external request one
$.post( "externalpage.php", data);
//make external request two
$.post( "ownserverpage.php", data);
});

No Javascript Fallback for AJAX Form submission

I am new to AJAX and am in the process of converting some regular HTML forms to AJAX.
My existing implementation is as follows - form (on page1.php) posts to page2.php which does some validation on post data and redirects to an error page if something is missing. If the input is fine, it includes page3.php which processes the request and redirects back to page1.php.
php/page1.php
<form method="post" action="/php/page2.php" >
<input type="text" name="input1" placeholder="Howdy..." />
<input type="text" name="input2" placeholder="Howdy..." />
<input type="submit" value="Submit" />
</form>
php/page2.php
<?php
// perform some validation on inputs
if (empty($_POST['input1']))
{
$location ='Location: /php/error.php';
header($location);
exit;
}
// Inputs are fine
include('/php/page3.php');
?>
page3.php
<?php
// do some form processing
// redirect back to page1.php
$location = 'Location: /php/page1.php";
header($location);
exit;
?>
To convert to AJAX, I am using #SSL's solution on this SO link How to show loading gif when request goes Ajax
http://jsfiddle.net/clickthelink/Uwcuz/1/
The error from validation and success page are both displayed back on page1.php via the callback function.
php/page2.php
<?php
// perform some validation on inputs
if (empty($_POST['input1']))
{
// Echo erorr code isntead of redirect
echo "Please enter input1";
return;
//$location ='Location: /php/error.php';
//header($location);
//exit;
}
// Inputs are fine
include('/php/page3.php');
?>
page3.php
<?php
// do some form processing
// Echo success instead of redirect
echo "SUCCESS";
// redirect back to page1.php
//$location = 'Location: /php/page1.php";
//header($location);
//exit;
?>
This part is working fine.
My question (finally) is how do I handle users who have javascript disabled? I know the form will get submitted appropriately but I wont get the redirect back in case of the error or success. I would like to retain header() redirect type of functionality in this case also. Is this possible? I would appreciate the help.
You want to detect if this is an xhr request, and default to the non-ajax behavior if it is not.
I would look at $_SERVER['HTTP_X_REQUESTED_WITH']
Keep your current form setup as-is, if it is working for you without javascript.
For javascript enabled browsers you can hijack the 'submit' event on the form. Capture the event and post the form, via ajax, to scripts/pages that handle and return the data in a javascript-friendly format for final consumption.
For example, using jquery:
<form method="post" action="/php/page2.php" id="js-form" >
<input type="text" name="input1" placeholder="Howdy..." />
<input type="text" name="input2" placeholder="Howdy..." />
<input type="submit" value="Submit" />
</form>
<script>
$(document).ready(function(){
$('#js-form').on('submit',function(e){
// logic to submit ajax form and handle response
// return false to cancel native browser form submission.
return false;
});
});
</script>
Another idea is to keep the pages you already have, but send a flag with the ajax request to disable the browser redirect headers. For example, add 'src=ajax' when submitting the form via ajax. Then in the script use logic to say:
<?php
if( !empty($_REQUEST['src'] && $_REQUEST['src'] == 'ajax' ) {
// add redirect logic here.
}
?>

How to display notification before form submit with jquery?

Is it possible to hold form submission to display notification for a couple of seconds?
Before a page reloads after the callback form is submitted I would like to display something along those lines: "Thank you for your callback request. We will be in touch shortly."
You can use preventDefault() to stop the form from submitting, show the information you want and submit() the form in a setTimout() after the desired delay.
if you're submitting with AJAX there is no need to refresh.
Take this as an example:
<form>
<input type="text" name="fname"/>
<input type="text" name="lname"/>
<input type="text" name="email"/>
<input type="text" name="address"/>
<input type="password" name="password"/>
<!--
Here you have two options. Use <a></a> or an input with type="submit"
since you're using AJAX, I reccomend using Submit
-->
Submit
</form>
Thank you for your callback request. We will be in touch shortly.
On javascript then:
<script>
$(document).ready(function(){
$("#submit_form").bind("click",function(){
//do a $.post();
$.post("submit/this.php",something : "content_of_something",
function(response){
if(response==1)//or whatever you want
$('#some_id').fadeIn(function() {
setTimeout(function(){
window.location.reload();
},3000);
});
else
alert("Error ocurred");
}
);
});
});
</script>
On PHP, check if the variable got to the server through $_POST(for debug purpose do var_export($_POST) on the server and on the client put a alert(response) right after function(response)). If everything went how it was supposed, echo 1(so response will match 1== response == 1), else, you can echo something else you want.

Show a DIV with form data on submit

Probably something stupid I'm doing. I want to populate a hidden DIV with values of a form on submit.
The DIV does open with correct data, but then resets after the page is finished loading. What am I doing wrong?
Here's my test:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content=
"text/html; charset=us-ascii" />
<title>Test</title>
<script type="text/javascript">
function test(){
var usr = document.getElementById('user').value;
var pwd = document.getElementById('passwd').value;
document.getElementById('out').innerHTML = usr + " " + pwd;
document.getElementById('out').style.display = "block";
return true;
}
</script>
</head>
<body>
<form action="" onsubmit="return test()">
<input type="text" id="user" name="user" />
<input id="passwd" type="text" name="passwd" />
<p><input type="submit" value="Go" /></p>
</form>
<div id="out" style="display:none;">
</div>
</body>
Short answer:
Change this
return true;
to this
return false;
Long answer:
Forms are designed to load a new page when they are submitted. However, with scripting we can prevent this behavior by stopping the submit event. This can be achieved in many ways, but for your example, simply returning "false" from your handler will cancel the event, but only if the onsubmit attribute also has a return statement (which you already had).
The onsubmit function is submitting the form back to the page. You need to cancel the event to prevent it from submitting the data and reloading the page. The easy way to do this is to have your test() function return false. If you still want the form to submit and display the data in a div you'll want to submit the form via AJAX or in an iFrame.
Try replacing "return true;" at the end of your function with "return false;". My reasoning is, because you have the action attribute specified but value, it may think that the current page is the value and since you're not cancelling the event the page reloads.
You need to return false
You see, the return value of onsubmit is used to decide whether to continue to submit the form. So if it's true, the page will reload and the values will be lost. If its false, it won't!
This line is probably your problem:
<form action="" onsubmit="return test()">
The blank action attribute causes the page to bounce to itself (reload) when the form is submitted. You can prevent this by making sure test() returns false rather than true, which will keep the form from submitting at all.
When you post the form, the data will be lost. You could stop the form from posting by setting return true to return false, or you could add some logic to print out the user and passwd fields in the DIV id="out" and set the display to block if user and passwd fields have a value.
As an alternativ you can use a link which do the job without submittig the form.
Do
Your problem is on the line
you should fill the action with the name of the page or with php code to directing to the page itself:
i have tested.

Categories

Resources