submit a form in jQuery [duplicate] - javascript

This question already has answers here:
Submit a form using jQuery [closed]
(22 answers)
Closed 8 years ago.
I have a form like this
<form id="add-to-cart" action="http://example.com/add_to_form" method="post">
<div>
<input type="hidden" name="cartkey" value="">
<input type="hidden" name="id" value="10">
buy Now
</div>
<div>
<input type="hidden" name="cartkey" value="">
<input type="hidden" name="id" value="12">
buy Now
</div>
<div>
<input type="hidden" name="cartkey" value="">
<input type="hidden" name="id" value="19">
buy Now
</div>
</form>
and I want to submit the form using jquery by taking the id. So can someone kindly tell me how to do this?
Update
You can see with each link I have the id. I just want to pass this id to the form action.

Try to use the .submit() function to manually trigger the form's submission,
$('#add-to-cart').submit();

You can use the .submit() function to submit your form through id's ..

you need to try like this. otherwise you cant get result.
<form id="add-to-cart" action="http://example.com/add_to_form" method="post">
<div>
<input type="hidden" name="cartkey" value="">
<input type="hidden" name="id" value="">
buy Now
</div>
<div>
buy Now
</div>
<div>
buy Now
</div>
</form>
<script>
$('.buy-now-button').click(function(){
$('[name="id"]').val($(this).attr("id"));
$('#add-to-cart').submit();
});
</script>

As mentioned in this SO article, you can post back the value of a button if you give your submit button a name property (and obviously, a value to post).
From the linked question (with corrected code snippet):
<input type="submit" name="respond" value="Confirm" class="btn_confirm" />
<input type="submit" name="respond" value="Ignore" class="btn_ignore" />
The "response" value that will be posted back to the server will contain either "Ignore" or "Confirm", depending on which button was clicked.
I would suggest adding these attributes so the form submission will send back the value you want, and no custom code or custom event is required. That should keep it easier to understand.

<form id="add-to-cart" action="test.php" method="post">
<div>
<input type="hidden" name="cartkey" value="">
<input type="hidden" name="id" value="10">
buy Now
</div>
<div>`enter code here`
<input type="hidden" name="cartkey" value="">
<input type="hidden" name="id" value="12">
buy Now
</div>
<div>
<input type="hidden" name="cartkey" value="">
<input type="hidden" name="id" value="19">
buy Now
</div>
<input type="hidden" name="currentId" id="currentId" >
</form>
<script>
$( ".buy-now-button" ).click(function() {
$( "#currentId" ).val(this.id);
$( "#add-to-cart" ).submit();
});
</script>
Your can get the current id from $_POST['currentId']

As you have several inputs with the same name, your form looks more like three forms.
<form class="add-to-cart" action="http://example.com/add_to_form" method="post">
<input type="hidden" name="cartkey" value="">
<input type="hidden" name="id" value="10">
<button type="submit">buy Now</button>
</form>
<form class="add-to-cart" action="http://example.com/add_to_form" method="post">
<input type="hidden" name="cartkey" value="">
<input type="hidden" name="id" value="12">
<button type="submit">buy Now</button>
</form>
<form class="add-to-cart" action="http://example.com/add_to_form" method="post">
<input type="hidden" name="cartkey" value="">
<input type="hidden" name="id" value="19">
<button type="submit">buy Now</button>
</form>
Now if you want to submit your form(s) via ajax, you can do something like:
$(".add-to-cart").on("submit", function(e) {
e.preventDefault();
e.stopPropagation();
$.ajax({
url: $(this).attr("action"),
method: "POST",
data: $(this).serialize()
});
});
UPDATE:
But unless you want a fallback in case javascript is deactivated, you don't need any form:
buy Now
buy Now
buy Now
JavaScript:
$(".buy-now-button").on("click", function(e) {
e.preventDefault();
e.stopPropagation();
$.ajax({
url: "http://example.com/add_to_form",
method: "POST",
data: {id: $(this).attr("id")}
});
});

Related

How to execute HTML code from ajax response

I'm implementing MyPos payment gateway to accept debit card purchases. Their SDK is working in a weird manner. When I start the payment process, the SDK tries to echo HTML code with a form which will auto submit itself to their checkout page. This shouldn't be a problem if I submit my order page with the normal form submit, but I'm using ajax from my order page. I'm handling all other payment methods through ajax calls to my server, so I'd like to be consistent and use ajax here too.
So basically:
From my order page i press "pay with card" button.
Javascript will make ajax call to my server with order details, and will set up a purchase with MyPos sdk.
MyPos sdk echoes a HTML (but I'm capturing it with output buffer) which looks as following
<body onload="document.ipcForm.submit();">
<form id="ipcForm" name="ipcForm" action="https://www.mypos.eu/vmp/checkout-test" method="post"><input type="hidden" name="IPCmethod" value="IPCPurchase">
<input type="hidden" name="IPCVersion" value="1.4">
<input type="hidden" name="IPCLanguage" value="it">
<input type="hidden" name="SID" value="000000000000010">
<input type="hidden" name="WalletNumber" value="61938166610">
<input type="hidden" name="KeyIndex" value="1">
<input type="hidden" name="Source" value="SDK_PHP_1.2.1">
<input type="hidden" name="Currency" value="EUR">
<input type="hidden" name="Amount" value="5.26">
<input type="hidden" name="OrderID" value="46057">
<input type="hidden" name="URL_OK" value="http://website.test/api/private/mypos/success-redirect">
<input type="hidden" name="URL_Cancel" value="http://website.test/api/private/mypos/cancel-redirect">
<input type="hidden" name="URL_Notify" value="http://website.test/api/private/mypos/ipc-notify">
<input type="hidden" name="Note" value="">
<input type="hidden" name="customeremail" value="testuser24#gmail.com">
<input type="hidden" name="customerphone" value="3333333333">
<input type="hidden" name="customerfirstnames" value="Test">
<input type="hidden" name="customerfamilyname" value="User">
<input type="hidden" name="customercountry" value="ITA">
<input type="hidden" name="customercity" value="Arco">
<input type="hidden" name="customerzipcode" value="38062">
<input type="hidden" name="customeraddress" value="Via Fiori 12">
<input type="hidden" name="CartItems" value="1">
<input type="hidden" name="Article_1" value="CRONO-Ex 1kg">
<input type="hidden" name="Quantity_1" value="1">
<input type="hidden" name="Price_1" value="5.26">
<input type="hidden" name="Amount_1" value="5.26">
<input type="hidden" name="Currency_1" value="EUR">
<input type="hidden" name="CardTokenRequest" value="0">
<input type="hidden" name="PaymentParametersRequired" value="1">
<input type="hidden" name="PaymentMethod" value="3">
<input type="hidden" name="Signature" value="jq7OSRfkJmyt22rquIDoxK0QB1GBFug4eUcGYyyKg08bY+d036bgJ/R49iq9L8ZMB+Sz8VBDb/QsqLtRLqIbaP2e7j1sYRaoZZDeK+E3gRuDp/yJofVjPWjK8Q1ZbaokoM9ETaBZI+6oUjUEIES9nqfMYFgH0tk3axDcHkZ8HKg=">
</form>
</body>
Technically i should echo this to a page, and it will auto submit to their website. But instead I'm capturing this with output buffer, and send it back to javascript with JSON response.
Now how can I execute this HTML and make it do it's job? (eg. auto submitting itself to that post action URL)
You could read the Action URL from the response separately and then serialize the form and make a new Ajax call again.
var myForm = $(response).find("#ipcForm");
var url = myForm.attr('action'); //get submit url [replace url here if desired]
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes form input
success: function(data){
console.log(data);
}
});

How can I get the value of a hidden input field when submitting a form?

I have a page with multiple forms on it. Each form has two submit buttons and one hidden input field which contains an ID.
When the user clicks one of the submit buttons, I need to send the value of the clicked submit button along with the value of the hidden input field with the form submission.
Here is an example of what my page looks like:
<form id="options">
<input type="hidden" value="104">
<input type="submit" onclick="this.form.submited=this.value;" value="Delete">
<input type="submit" onclick="this.form.submited=this.value;" value="Reply">
</form>
<form id="options">
<input type="hidden" value="44">
<input type="submit" onclick="this.form.submited=this.value;" value="Delete">
<input type="submit" onclick="this.form.submited=this.value;" value="Reply">
</form>
<form id="options">
<input type="hidden" value="39">
<input type="submit" onclick="this.form.submited=this.value;" value="Delete">
<input type="submit" onclick="this.form.submited=this.value;" value="Reply">
</form>
<script>
$(document).on("submit", "#options", function(e) {
e.preventDefault();
console.log(this.submitted) // gets the value of the submit button
});
</script>
Currently I can only send the value of the clicked submit button with the form submission and not the value of the hidden input field. While I am aware that I could use onclick="this.form.submited=this.previousElementSibling.value;" to get the ID, this would mean I cannot get the value of the clicked submit button.
Use $(this) to to get the hidden input of the current form, and you can't use the same id for multiple elements, change your id to class="options".
var val = $(this).find('input:hidden').val());
$(document).on("submit", ".options", function(e) {
e.preventDefault();
console.log($(this).find('input:hidden').val()) // gets the value of the submit button
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="options">
<input type="hidden" value="104">
<input type="submit" onclick="this.form.submited=this.value;" value="Delete">
<input type="submit" onclick="this.form.submited=this.value;" value="Reply">
</form>
<form class="options">
<input type="hidden" value="44">
<input type="submit" onclick="this.form.submited=this.value;" value="Delete">
<input type="submit" onclick="this.form.submited=this.value;" value="Reply">
</form>
<form class="options">
<input type="hidden" value="39">
<input type="submit" onclick="this.form.submited=this.value;" value="Delete">
<input type="submit" onclick="this.form.submited=this.value;" value="Reply">
</form>
Give an id say hiddenInput to the hidden input box. To access the value you can use $(.hiddenInput).val();. To access the value on the server side, you can access it using req.query.id()
You can use val():
var value = $('input[name="input-name"]').val();
Edit:
If you want to use more than one input with the same name, use it like this:
$('input[name="input-name"]').forEach(function($in) {
var value = $in.val();
});
Try this:
$(document).ready(function() {
$("input[type='submit']").click(function(event) {
event.preventDefault();
var id = $(this).parent().find("input[name='id']").val();
var action = $(this).data("action");
console.log("action: " + action + ", id: " + id);
});
});
<html>
<body>
<form id="options1">
<input type="hidden" name="id" value="104">
<input type="submit" data-action="delete" value="Delete">
<input type="submit" data-action="reply" value="Reply">
</form>
<form id="options2">
<input type="hidden" name="id" value="44">
<input type="submit" data-action="delete" value="Delete">
<input type="submit" data-action="reply" value="Reply">
</form>
<form id="options3">
<input type="hidden" name="id" value="39">
<input type="submit" data-action="delete" value="Delete">
<input type="submit" data-action="reply" value="Reply">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
Just a simple find will fetch you the required data.
$(document).on("submit", "form", function(e) {
alert($(this).find('input[type="hidden"]').val())
e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="options">
<input type="hidden" value="104">
<input type="submit" onclick="this.form.submited=this.value;" value="Delete">
<input type="submit" onclick="this.form.submited=this.value;" value="Reply">
</form>
<form id="options">
<input type="hidden" value="44">
<input type="submit" onclick="this.form.submited=this.value;" value="Delete">
<input type="submit" onclick="this.form.submited=this.value;" value="Reply">
</form>
<form id="options">
<input type="hidden" value="39">
<input type="submit" onclick="this.form.submited=this.value;" value="Delete">
<input type="submit" onclick="this.form.submited=this.value;" value="Reply">
</form>
All you need is this:
<form>
<input type="hidden" name="id" value="104">
<input type="submit" name="action" value="Delete">
<input type="submit" name="action" value="Reply">
</form>
Clicking the Reply button yields:
id=104&action=Reply

how to display a value(in text field) from one form(after submitting it) to another form (both are on the same page)

So, I have the form1 where i am giving values in two fields and submitting it,
<form action="new_cand.php" name="form1" method="post">
<input type="number" name="aadhar_r" id="aadhar_r" required/>
<input type="text" name="cand_r" id="cand_r" required/>
<input type="submit" name="submit" id="submit" onclick="setValues();" />
</form>
I want these values to automatically be written and visible in the two textinput and numberinput fields in form2.
<form action="in_cand.php" name="form2" method="post">
<input type="number" id="a_number" name="a_number" required>
<input type="text" id="cid" name="cid" required>
<input type="submit" name="submit" id="submit" />
</form>
how do i use javascript to automatically set values visible and ready to submit
to the fields in form2 ???
Note: i'm using two forms because they both have different actions after clicking submit and both the forms are on the same page.
Here is one small example using id hashes, with this idea, I think you can start, object hash will have pair list,
You can restrict specific form by mentioning id of it, in place of $('form :input').on():
var hash = {
aadhar_r : 'a_number',
cand_r : 'cid'
}
$('form :input').on('keyup',function(){
if(this.id in hash){
$('#'+hash[this.id]).val($(this).val())
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="new_cand.php" name="form1" method="post">
<input type="number" name="aadhar_r" id="aadhar_r" required/>
<input type="text" name="cand_r" id="cand_r" required/>
<input type="submit" name="submit" id="submit" onclick="setValues();" />
</form>
<form action="in_cand.php" name="form2" method="post">
<input type="number" id="a_number" name="a_number" required>
<input type="text" id="cid" name="cid" required>
<input type="submit" name="submit" id="submit" />
</form>
If you use jQuery, you can serialize your first form and send it directly to the server. Then you get the value from the input field and set it to the other input field.
Form 1:
<form id="form1">
<input type="number" name="aadhar_r" id="aadhar_r" required/>
<input type="text" name="cand_r" id="idOfInput1" required/>
<button id="submit" />
</form>
Script:
$("#submit").click(function () {
$.post("new_cand.php", $("#form1").serializeArray(), function () { /* Nothing to do with new_cand.php data */});
$("#idOfInput2").val($("#idOfInput1").val());
});
Form 2:
<form action="in_cand.php" name="form2" method="post">
<input type="number" id="a_number" name="a_number" required>
<input type="text" id="idOfInput2" name="cid" required>
<input type="submit" name="submit" id="submit" />
</form>
Attention: this is not tested, requires jQuery and is for a post method

Get datepicker value to prepopulate a field after redirect

I have a form with a datepicker field and I want when I submit this form to redirect me to another page and pre-populate an input-field in another form.
To be more specific.
I have the form with the jquery datepicker field:
<form id="form" action="form.php" method="post">
<input type="text" name="datepicker-field" id="datepicker"/>
<input type="submit" id="btn" value="check"/>
</form>
And the form.php page has another form
<form id="another-form" action="mail.php" method="post">
<input type="text" name="input-field" id="input-field"/>
<input type="submit" id="btn" value="check"/>
</form>
I suppose I have to initialise the datepicker value somehow But I haven't got any javascript knowledge.
I appreciate any help!
Something like
<form id="another-form" action="mail.php" method="post">
<input type="text" name="input-field" id="input-field" value="<?php echo htmlspecialchars($_POST['datepicker-field']) ?>"/>
<input type="submit" id="btn" value="check"/>
</form>

Javascript automatic form submission

I took this quick script from another post on StackOverflow, but it doesn't seem to work on my form. It just throws an error saying 'object expected'. Can anyone help me fix it.
<html>
<head></head>
<body onLoad="document.forms[0].submit()">
<form name="EPDQForm" method="post" action="mypage.aspx" >
<input name="item" type="hidden" value="data">
</form>
</body>
</html>
EDIT:
This is the exact page code (I removed most of it for displaying on here):
<html>
<head></head>
<body onLoad="document.forms[0].submit()">
<form id="myform" name="myform" method="post" action="https://secure2.mde.epdq.co.uk/cgi-bin/CcxBarclaysEpdq.e">
<input name="epdqdata" type="hidden" value="972">
<input name="returnurl" type="hidden" value="http://www.xxxx.co.uk/Secure/EPDQReturn.aspx">
<input name="merchantdisplayname" type="hidden" value="xxxxxx">
<input name="submit" type="hidden" value="purchase">
<input name="shipping" type="hidden" value="0.00">
<input name="baddr1" type="hidden" value="152 Smith St">
<input name="baddr2" type="hidden" value="">
<input name="bcity" type="hidden" value="Manchester">
<input name="bcountry" type="hidden" value="UK">
<input name="bpostalcode" type="hidden" value="M4 6DH">
<input name="email" type="hidden" value="xxxx#xxxx.co.uk">
<input name="saddr1" type="hidden" value="152 Smith St">
<input name="scity" type="hidden" value="Manchester">
<input name="scountyprovince" type="hidden" value="Alderney">
<input name="scountry" type="hidden" value="UK">
<input name="spostalcode" type="hidden" value="M4 5GG">
</form>
</body>
</html>
This code shows the error. And I don't see why. In firefox it says:
document.forms[0].submit is not a function
What happens if you remove the onload attribute from your opening <body> tag and place this code just before your closing </body> tag?
<script>
var frm = document.getElementById('myform');
if (frm) {
frm.submit();
}
</script>
Ok, the problem is in this part : input name="submit" type="hidden" value="purchase".
Submit input has the same name as the form function.
If you replace the name 'submit' by other name (submit1 as example) it should be working as a charm. :-)
Good luck.

Categories