I have a form in HTML to apply a Discount Coupon to a current shopping cart.
I would like the user to just click on APPLY (after entering the coupon code) and then without refreshing the page, to have some PHP code run so it computes the corresponding discount.
Here is my form:
<form action="">
<input type="text" name="couponCode">
<input type="submit" value="Apply">
</form>
PHP to be run:
if (isset($_REQUEST['couponCode']) && $_REQUEST['couponCode']!='')
{
$couponCode = $_REQUEST['couponCode'];
if ($couponCode == "TEST1")
{
$discount=0.2;
}
}
How would this be done using javascript?
You need to use either the onsubmit event of the form or the onclick event of the button.
In the event handler, you assemble a URL and "get" it. For example:
<script type="text/JavaScript">
function submitCouponCode()
{
var textbox = document.getElementById("couponCode");
var url =
"https://www.example.com/script.php?couponCode=" + encodeURIComponent(textbox.value);
// get the URL
http = new XMLHttpRequest();
http.open("GET", url, true);
http.send(null);
// prevent form from submitting
return false;
}
</script>
<form action="" onsubmit="return submitCouponCode();">
<input type="text" id="couponCode">
<input type="submit" value="Apply">
</form>
Use jQuery AJAX. When it's complete, refresh your page as needed.
You can use Jquery to do an AJAX post you your PHP script, and then use JS to change the contents of the calling page.
http://api.jquery.com/jQuery.post/
It's simple with jQuery. You just have to use the right tag. If you use an "a" tag the page will refresh.
<button id="MyButton">Click Me!</button>
<script>
$("#MyButton").click( function(){
$.post("somefile.php");
});
</script>
Related
i have html form and in that form when i click it redirect to paypal page but i want before redirect on paypal page it should go send.php and then paypal page
i have tried onclick function on submit button and inthat function use window location function for redirect to send.php page but it's not working page redirect only paypal page
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" enctype="multipart/form-data" >
<input class="btn btn-primary" type="submit" value="Send" onclick="mymail()">
</form>
javascript code
<script>
function mymail() {
window.location.assign("send.php")
}
</script>
it only redirect paypal page not redirecting on send.php
First you have to add id for form and change onclick function as below
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="Post" enctype="multipart/form-data" id="frm">
<input type="submit" value="send" onclick="return mymail()">
</form>
and now use ajax call in mymail() to send.php and on success of ajax submit the form through javascript by form id as shown below
function mymail()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("frm").submit()
}
};
xhttp.open("GET", "send.php", true);
xhttp.send();
return false;
}
now on click of submit, page goes to send.php through ajax and on success the form will be submiteed
Submit button first event is to submit the form to your "action" location (paypal), the second event "onclick" is to redirect to send.php.
So if you want it to go to send.php first make the action send.php, do your thing there, than send your post data to paypal.
Take a look at something like this: https://stackoverflow.com/a/32197769/6340057
Here you are using input type submit so when it will pressed it will take default form submit action which is on paypal.com
your on click is also working here (try to put alert in that it will execute) also work but the problem is when on click completes its execution it will continue execute the form's default action .
so if you want to redirect from your on click my mail() function then you need to add ajax to the javascript function
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" enctype="multipart/form-data">
function mymail()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("frm").submit()
}
};
xhttp.open("GET", "send.php", true);
xhttp.send();
return false;
}
First of all clear action="" and method="", because even tho you change the button property, when the user clicks enter within that form, it will redirect to the given action no matter what your javascript does.
Secondly, change your <input> into a <button type="button"> rather than <input type="submit"> and call the onclick="mymail()" function there just like you did.
Here is how your form would look like:
<form enctype="multipart/form-data" >
<button class="btn btn-primary" type="button" onclick="mymail()">Send</button>
</form>
Make sure you read all the form fields and put it into data.
Good luck.
My if(isset) validation is returning false after I have submitted the form through jQuery ,however works fine when done without jquery. Reason I am using jQuery is because I need to submit multiple forms:
Button
<input class="btn btn-primary" type ="submit" id="myButton"
name="create_record" value="Submit 1">
jQuery:
<script>
$(document).ready(function () {
$("#myButton").click(function (event) {
event.preventDefault();
$("#form1").submit();
// $("#form2").submit();
});
});
</script>
PHP
<?php
if(isset($_POST['create_record'])){
$ecode = $_POST['ecode'];
$ename = $_POST['ename'];
$date = $_POST['date'];
$jobRole = $_POST['jobRole'];
}else{
echo "did not receive anything";
}
?>
Always getting "did not receive anything" . Can someone please help.
The submit button value only gets sent if the form is submitted in the traditional way by a button click. Since you are submitting the form via javascript, you'll need to explicitly include the submit button's value or validate your post data in some other way. If you need the value of the specific button that was clicked, something like this should work:
$("#myButton").click(function (event) {
event.preventDefault();
var el = '<input type="hidden" name="' + $(this).prop('name') + '" value="' + $(this).val() + '">';
$("#form1").append(el).submit();
});
As for your objective of submitting multiple forms at once, I believe it's impossible without using ajax as discussed here. If you need guidance on how to do that, better to open a new question.
Your code, isset($_POST['create_record']) maybe false or it didn't receive any values. If your query is only in one PHP file together with your jQuery, you need to check first your algorithm or use var_dump() for testing. Second, If it didn't work, make an alternative solution for it. Do the proper HTML code when using form or make another PHP file for receiving post purpose only.
<form action="directory_to_another_file" method="POST">
<!-- SOME INPUTS HERE -->
<input type="submit" value="Submit 1" name="create_record">
</form>
Try to test all of your codes.
You have to set form method as "POST" type and if you want to receive the form data in same page then empty the "action" key otherwise give the target link.
<?php
if(isset($_POST['create_record'])){
print_r($_POST);
}
?>
<form action="" method="POST" id="form1">
<input type="text" name="create_record" value="Submit 1"/>
</form>
Submit
<script>
$(function(){
$("#myButton").click(function (event) {
event.preventDefault();
$("#form1").submit();
});
})
</script>
Let me know if it's work for you.
I wrote an array to pass variables in the GET to a search page. The search page only has 4 fields but I'm only passing the most important variables, first name and last. Here is the array:
<?php echo "<td><a href='" . matry::base_to('test/trace', array('first'=>$patient->first , 'last' =>$patient->last)) . "'><ul class='controls'>
<li id='check_orders'><`span class='symbols'>L</span><span class='label'>Skip Trace</span></li>
</ul></a></td>";?>
When the page loads i'm just echoing the _GET to pre populate the first and last input fields on that page..
What I'm looking for is a script that will execute the search with the first and last name fields populated as that page loads automatically. Additionally, when the search is executed it's populating in an iframe. (forgot about that part)~!
I tried using:
<script>document.getElementById('stack').submit();</script>
<form action='http://xxxx.yyyyyyy.com/stuffhere' name='es' target="my_iframe" id="stack">
with no avail.
Your <script> is running before the <form> exists.
Move the <script> below the <form>.
You are calling the submit function before the form is even loaded on the page.
Place the script tag after the closing form tag or call submit on document ready or window onload.
<form id-"stack">
... form fields...
</form>
<script>document.getElementById('stack').submit();</script>
or
<script>$(function(){$('#stack').submit();})</script>
Please imagine this simple example:
<html>
<head>
<script type="text/javascript">
function body_onload() {
var form = document.getElementById('theform');
form.submit();
}
</script>
</head>
<body onload="body_onload()">
<form id="theform" action="action.php">
<input type="hidden" name="query" id="query" value="foo" />
</form>
</body>
</html>
It will submit the form after the page has loaded.
But are you really searching for a non AJAX solution?
Try this, been using this on a redirect page for a while. This of course needs to be below the from so it is run after the browser process the form.
<script type="text/javascript">
function send(o)
{
var f = document.getElementById("theForm");
f.submit();
}
send();
</script>
If you want to submit the form when the page loads you should change your code to this:
<script>window.onload = function(){ document.getElementById('stack').submit(); }</script>
However this will redirect the user (as if they have clicked a form submit button). To avoid this you will need to use AJAX (I recommend using jQuery to do this). See example below:
$(document).ready(function(e) {
var form_data = $("#form_id").serialize();
var form_url = $("#form_id").attr("action");
var form_method = $("#form_id").attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false
});
});
See this page for more info on using AJAX
I have the following form and javascript function on my web page. This is a dummy function that I am using to test whether what I would like to do is possible.
What I am attempting to do is have a form send an AJAX request to the server, so that the server can update the database while the page itself continues along it's predetermined path. I am in a tight time crunch, so I unfortunately do not have time to rewrite the entire page to better support this. The problem that I have is the xmlhttp object does not seem to return properly. I get a readyState of 4 but a status of 0. can someone please explain what I need to do?
Here's my code:
ajax.php
<html>
<head>
<script type="text/javascript">
function test(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
document.getElementById("new").innerHTML+="<b>"+xmlhttp.readyState+"</b> "+xmlhttp.status;
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("hello").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","response.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
if ($_POST){
echo $_POST['hello'];
}
?>
<form action="ajax.php" method="post">
<input type="text" name="hello" />
<input type="submit" value="submit" onclick="test();" />
</form>
<div id="hello"></div>
<h3>debug</h3>
<div id="new"></div>
</body>
</html>
response.php
<?php
echo "Hello there";
?>
EDIT
Please note that I do not want to prevent the default behavior. In fact, the forn must be submitted as usual. I simply want to add an AJAX request to the process.
You can't trigger an AJAX request and allow the form to submit at the same time. Incomplete AJAX requests are cancelled when the page reloads (as is the case when the form is submitted). You'll either have to not submit the form at all, or wait until your AJAX call has completed before submitting the form. If you wanted to go the second route, you could make the following changes to your code:
<html>
<head>
<script type="text/javascript">
function test(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
document.getElementById("new").innerHTML+="<b>"+xmlhttp.readyState+"</b> "+xmlhttp.status;
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("hello").innerHTML=xmlhttp.responseText;
**document.getElementById("ajaxform").submit();**
}
}
xmlhttp.open("GET","response.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
if ($_POST){
echo $_POST['hello'];
}
?>
<form action="ajax.php" method="post" **id="ajaxform"**>
<input type="text" name="hello" />
<input type="submit" value="submit" onclick="test();**return false;**" />
</form>
<div id="hello"></div>
<h3>debug</h3>
<div id="new"></div>
</body>
</html>
Changes/additions are marked with **.
Note that there are a few practices in there I don't like, in particular using the onsubmit, etc attributes of HTML tags to attach Javascript event handlers.
I know this doesn't directly answer your question but if you are strapped for time then I would suggest just using jQuery to handle the AJax.
You can attach it to a button press and then call some code: http://api.jquery.com/jQuery.ajax/
I can dig out some code examples if you need them.
Once the submit button is pressed the browser will submit data to the server and a new page will be loaded. You can bind the submit event of the form and in the event make the ajax call but you will have 2 problems.
The browser may redirect before all ajax data is sent
You have no idea if the ajax call was successful or not
I would try sending the data you are sending via ajax in the same form data using hidden inputs. If both calls are aimed at different urls then try this:
var ajaxSent = false;
$('#myForm').submit(function(e){
if (!ajaxSent){
e.preventDefault();
$.ajax({
url: "ajaxUrl",
// data, method, etc
success: function(){
ajaxSent = true;
$('#myForm').trigger('submit');
}
}
// else submit the form
});
I am using the following code to effect an iframe that allows an ajax file upload on submit of the form without refresh.
This works as expected
window.onload=init;
function init() {
document.getElementById('form').onsubmit=function() {
document.getElementById('form').target = 'iframe';
}
}
What i would like to do is the same thing but 'onchange' of the file field input, i.e. when the user has chosen a file, to autmatically trigger the init() function and thus upload the file. I have tried with this code:
document.getElementById('file').onchange=function(){...
This doesn't work, and i'm completely stuck. Any ideas?
Many thanks
This should work for you
<script type="text/javascript">
window.onload = function() {
// add old fashioned but reliable event handler
document.getElementById('file_input').onchange = function() {
// submit the form that contains the target element
this.form.submit();
}
}
</script>
<iframe name="my_iframe"></iframe>
<form target="my_iframe"
action="your/file.ext"
method="post"
enctype="multipart/formdata">
<input type="file" name="my_file" id="file_input">
<!-- for no js users -->
<noscript>
<br/>
<input type="submit">
</noscript>
</form>
i think something like .live() will solve your issue hopefully, comment if you want more info on how to use it...
Give the file input element an id and:
$(document).ready(function(){
$(element).change(function(e){
fileInfo = e.currentTarget.files[0];
init();
});
});