Thymeleaf form with path variable - spring

I have a form with a method get and with an action. When I submit the form, the action parameter contains id as a standard parameter like ?id=1. How do I pass this parameter as path variable?
<form method="get" th:action="#{/mycontroller/}">
<input type="text" id="id" name="id"/>
<input type="submit"/>
</form>

Your html:
<form id="myForm" method="get" th:action="#{/mycontroller/}">
<input type="text" id="id" name="id"/>
<input type="submit"/>
</form>
And then with JQuery you could do something like this:
var $form = $( '#myForm' );
var $idField = $( "#id" );
$form.submit( function( event ) {
// respects th:action="#{/mycontroller/}" and appends id
$form.attr( 'action', $form.attr('action') + $idField.val() );
// otherwise ?id=xx
$idField.prop( "disabled", true );
// submits the form in the normal way !
return;
});

Related

Sending form data through ajax to spring controller is not working

Here is my js code. This will trigger on click of add button and will post the form manually through ajax.
function addRow()
{
var form = $('#fortForm')[0];
var data = new FormData(form);
$.ajax({
type:"POST",
enctype:"multipart/form-data",
url:"${pageContext.request.contextPath}/admin/meeting/saveBlockMom?
${_csrf.parameterName}=${_csrf.token}",
data: data,
processData: false,
contentType:false,
cache: false,
success:function(data){
alert(data);
},
});
}
The jsp code. This contains the form code need to be submitted
<div class='row'><form:form id="fortForm" method="post" modelAttribute="mom" enctype="multipart/form-data">
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
<div class='col-md-3'>
<label>hgkk</label><input type='hidden' name="blockName" id="blockName" path='blockName' value="sadsa"/></div><div class='col-md-3'><span>Whether PBG is fortfieted</span>
<label for='Yes'>Yes</label><input type='radio' id='yes_1' name='fortpbgrad_' value='yes' onChange='showFunction()'/><label for='No'>No</label>
<input type='radio' id='no_' name='fortpbgrad_' value='no' onChange='hideFunction()'/>
</div><div class='col-md-3' id='hideBlock_'><input type='text' placeholder='Enter Forfeit Percentage' id="fortPercentage" name="fortPercentage" path='fortPercentage'/></div>
<div class='col-md-3'><label for='Remarks'>Remarks:</label><input type='text' path='Remarks' id='Remarks' name="Remarks"/></div>
</form:form></div>
</div>
<button type="button" style="float:right;" onclick="addRow()">Add</button>
And the Controller in action. Data is not being transmitted to the object blockmom .
#RequestMapping(method=RequestMethod.POST, value="/saveBlockMom")
public String saveBlockMom(#ModelAttribute("blockmom") blockmom blockmom)
{
logger.info("******************You are in function saveBlockMom***********************");
/* blockmom.setBlockMomId((long) 100);*/
service.saveBlockMom(blockmom);
return "redirect:/admin/meeting/meetingList";
}

AJAX form $('form')[0].reset(); on submit not clearing values. What am I missing?

thank you in advance for any help given. I'm just learning jQuery and AJAX and would appreciate some help with the following code. All validation rules work, the form submits and the page does not refresh. The problem is that the form values are not clearing/resetting to default after the submit has triggered. Thoughts?
**********EDITED to include HTML markup*************
<div id="form">
<h1 class="title">Contact Us</h1><!-- title ends -->
<p class="contactUs">Ask about our services and request a quote today!</p><!-- contactUs ends -->
<div id="success"><p>Your message was sent successfully. Thank you.</p></div>
<p id="required">* All fields required.</p>
<form name="form" id="contactMe" method="post" action="process.php" onSubmit="return validateForm()" enctype="multipart/form-data">
<input class="txt" type="text" maxlength="50" size="50" required name="name" value="<?php echo $_GET['name'];?>" placeholder="Name" />
<div id="nameError"><p>Your name is required.</p></div>
<input class="txt" type="text" maxlength="50" size="50" required name="email" value="<?php echo $_GET['email'];?>" placeholder="Email Address" />
<div id="emailError"><p>A valid email address is required.</p></div>
<textarea name="message" rows="6" cols="40" required placeholder="Message"></textarea>
<div id="messageError"><p>A message is required.</p></div>
<input type="hidden" maxlength="80" size="50" id="complete" name="complete" placeholder="Please Keep This Field Empty" />
<input type="submit" value="SUBMIT" name="submit" />
<input type="reset" value="RESET" name="reset" />
</form>
</div><!-- form ends -->
//hide form submit success message by default. to be shown on successfull ajax submission only.
$(document).ready(function() {
if ($('#success').is(':visible')){
$(this).hide()
}
});
//form validation
function validateForm() {
//name
var a=document.forms["form"]["name"].value;
if (a==null || a=="")
{
$('#nameError').fadeIn(250);
return false;
}
//email address
var c=document.forms["form"]["email"].value;
var atpos=c.indexOf("#");
var dotpos=c.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=c.length)
{
$('#emailError').fadeIn(250);
return false;
}
//message
var e=document.forms["form"]["message"].value;
if (e==null || e=="")
{
$('#messageError').fadeIn(250);
return false;
}
}//javascript form validation ends
//ajax submit and clear form on success
$(function () {
$('form').on('submit', function (e) {
var myForm = validateForm();
if (myForm == false){
e.preventDefault();//stop submission for safari if fields empty
}
else{
$.ajax({
type: 'post',
url: 'process.php',
data: $('form').serialize(),
success: function () {
$('#success').fadeIn(250);
if ($('#nameError, #emailError, #messageError').is(':visible')) {
$('#nameError, #emailError, #messageError').fadeOut(250);
}
$('form')[0].reset();//clear form after submit success
}//success ends
});//ajax ends
e.preventDefault();//prevent default page refresh
}//else ends
});//submit ends
});//function ends
//if reset button is clicked AND messages displayed, remove all form html messages
$(document).ready(function() {
$('#form input[type="reset"]').click(function() {
if ($('#success, #nameError, #emailError, #messageError').is(':visible')) {
$('#success, #nameError, #emailError, #messageError').fadeOut(250);
}
});
});
By giving your input id="reset" and/or name="reset", you effectively overwrote the form.reset method of the form because by doing so you made form.reset target the reset button. Simply give it a different id and name value.
Never give elements name or id attributes that equal the name of a property of a dom node.

fancybox and jquery form validation

Have problem with fancybox and jquery validate plugin when form is in fancybox container.
For examle (inline):
html:
<script>
$(document).ready(function(){ $.fancybox('
<form class="myform">
<input type="text" name="email" class="email" />
<input type="submit" value="submit" name="submit" />
</form>
');
})
</script>
js file:
$(".myform").validate(
{
rules: {
email: "required",
email: "email"
}
}
);
How to make jquery validation pluging to work in fancybox?
Do two things...
Use the afterLoad FancyBox callback function to initialize .validate() immediately after the form is loaded.
Put the content for FancyBox in a hidden div instead of in your jQuery. It's cleaner.
Note: You may want to reconsider using email for the name attribute. It has potential to cause great confusion since the rule is also called email.
HTML:
<a id="test" href="#inline">Test</a>
<div style="display:none" id="inline">
<form class="myform">
<input type="text" name="email" class="email" />
<input type="submit" value="submit" name="submit" />
</form>
</div>
jQuery:
$(document).ready(function () {
$('#test').fancybox({
afterLoad: function() {
$('.myform').validate({
// rules and options for validate plugin,
rules: {
email: { // "email" is name of the field
required: true,
email: true // "email" is name of the rule
}
}
});
}
});
});
Working DEMO: http://jsfiddle.net/ZMEEW/

Codeigniter Cart: How to add multiple items with ajax and jquery

I'm building a ajax based shopping cart with Codeigniter, and the add / remove functions work perfectly. I am now trying to add an option for adding multiple items, and can't get it to work.
Here's the markup I'm using. I'm not sure if it's the best design, but it's working with the non-ajax function, so I guess it should be fine.
<form action="cart/add_multiple" method="post" accept-charset="utf-8">
<input type="hidden" name="items[0][id]" value="3571310" />
<input type="hidden" name="items[0][qty]" value="1" />
<input type="hidden" name="items[0][price]" value="59.00" />
<input type="hidden" name="items[0][name]" value="London" />
<input type="hidden" name="items[0][heb_name]" value="לונדון" />
<input type="hidden" name="items[0][full_price]" value="59.00" />
<input type="hidden" name="items[0][discount_price]" value="59.00" />
<input type="hidden" name="items[1][id]" value="7397903" />
<input type="hidden" name="items[1][qty]" value="1" />
<input type="hidden" name="items[1][price]" value="29.00" />
<input type="hidden" name="items[1][name]" value="London Triple" />
<input type="hidden" name="items[1][heb_name]" value="לונדון טריפל" />
<input type="hidden" name="items[1][full_price]" value="29.00" />
<input type="hidden" name="items[1][discount_price]" value="29.00" />
<input type="submit" name="add_multi" value="add to cart" /></form>
The ajax script is as follows:
$(document).ready(function() {
$(document).on("submit", "div#winning_combo_small form", function () { //catches every click on the submit button of the "add to cart" form
var items = $(this).serialize();
alert(items);
$.post(base_url + "cart/add_multiple", {items: items, ajax: '1' },
function(data){
if (data =='true')
{ // Interact with returned data
$.get(base_url + "cart", function(cart){ // Get the contents of the url cart/show_cart
$("#cart_sidebar").html(cart);
})
$.get(base_url + "cart/count_items", function(items){
$("#cart_items").html(items);
})
}
});
return false;
})
});
But it's not working, because the add_multiple function receives the data as a string, not an array. Do I have to decode the data somehow to convert it to an array? Do the Hebrew characters get in the way and mess it all up?
I should say that when posting the form the regular way, without ajax, the items are added to the cart and all works well. So what is the difference between the regular post and the ajax post?
Well, I got it to work, though I'm not sure if it's the most elegant way.
Here's what I did:
In the ajax script, I changed var items = $(this).serialize(); to var items = $(this).serializeArray();. I now get an array instead of a string, but it's not the format I need to insert into the cart. So I looped over this array to create an array in the desired format, and used that new array to insert into the cart.
This is my add_multiple function under the cart controller:
function add_multiple()
{
$items = $this->input->post('items');
$ajax = $this->input->post('ajax');
// Check if user has javascript enabled
if($ajax != '1'){
$this->cart->insert($items); //if posted the regular non-ajax way, the fields will be in an array in the correct format
echo 'false';
redirect('cart'); // If javascript is not enabled, reload the page with new data
}else{
$i = 0;
foreach($items as $key=>$form_field)
{
$field_name = $form_field['name'];
$from_char = strrpos($field_name, '[') +1 ;
$length = strlen($field_name)-$from_char-1;
$field = substr($field_name,$from_char,$length);
$data[$i][$field] = $form_field['value'];
if ($field == "discount_price") $i+=1; // I know 'discount price' is always the last field
}
$this->cart->insert($data);
echo 'true'; // If javascript is enabled, return true, so the cart gets updated
}
}

Submitting form into a div

Can anyone tell me why this is not working or give me another way into doing what I want.
I have a form on a page when click submit I want it to process into add.php and for it to open up in a DIV called right.
Form page
<script>
$("#Submit").click(function() {
var url = "add.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(html){ $("#right").html(html); }
});
return false; // avoid to execute the actual submit of the form.
});
</script>
</head>
<body>
<form action="add.php" method="post" enctype="multipart/form-data" id ="myForm">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
Photo: <input type="file" name="photo"><br>
<input type="submit" value="Upload">
</form>
</body>
Now if I add action to form to direct it to add.php all works fine so other script is ok yet when i do it this way,nothing happens it does not load add.php into the 'right' div like I want it to.
Anyone got any suggestions?
Your $("#Submit") selector does not match anything (the submit button has no id and is defined after that bind attempt), so the function is not bound to any event, thus never executed.
Instead the form acts the way it should: upon submit it posts its content to the url specified in the 'action' attribute. This is what happens, that div is never touched.
you have to go back to understand how jquery selectors work. How to bind a function to an event.
Is this your exact code? There are a few issues:
$("#Submit").click should be wrapped in a document ready
handler so it doesnt run before the page has actually loaded.
There is no button that matches #Submit
There is no div that matches #right
Try
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#Submit").click(function() {
var url = "add.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(html){ $("#right").html(html); }
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
</head>
<body>
<div id="right">
</div>
<form action="add.php" method="post" enctype="multipart/form-data" id ="myForm">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
Photo: <input type="file" name="photo"><br>
<input type="submit" value="Upload" id="Submit">
</form>
you have to create on div in body tag which id will be right and
<input id="submit" type="submit" name="upload" >
add new div in body tag like this
<div id="right"></div>

Resources