How to submit a form with specific fieldset - javascript

I have a form like this:
<form name="paymentForm" id="paymentForm" action="/submit.jsp" method="post">
<fieldset id="ccData">
<input id="ccNumber" name="ccNumber"/>
</fieldset>
<fieldset id="otherData">
<input id="requestId" name="requestId"/>
</fieldset>
</form>
When you slick submit, I would like to submit(via ajax) only #ccData filedset to some different url (e.g. submitCC.jsp) and based on response I want to submit full form to actual url.
How can I achieve that ?

Use jQuery's serialize method
var formData = $("#ccData").serialize()​;
$.post("TheUrl",formData);

You could do that with JavaScript - e.g jQuery. You build an eventHandler like
$('#paymentForm').on('click', function () {
$(this).preventDefault();
if ($(this).hasClass('first_send')) {
$.ajax({
url: "your_url",
data: { ccData: $('#ccData').val()}
}).done(function ( data ) {
$('#paymentForm').addClass('first_send')
// examin the data, insert stuff you need and send the form again
// with ajax
})
} else {
$(this).removeClass('first_send')
// this is the second send - so do stuff here - show a result or so
}
})
With the class first_send you can check if it is the first send or the second. This is just an untested, incomplete idea how you could do it. I guess you get the big picture ...

Related

How to redirect to another page after click on submit button in form with required inputs

I need to redirect to index.html after clicking on button in a form. I tried this:
$("#btn").on("click", function() {
window.location.replace("index.html");
localeStorage.clear();
})
However in the form I have required inputs, so when I had some empty required input, it redirected, but at the same time it said that I must write something to input.
I need to redirect to index.html after successful form submission. Like on a eshop after submitting an order
Firstly, if you want the form to be validated first before the redirection you need to place the event on the submit of the form, not the click of the button.
Secondly, performing a redirect in JS when the form is submit is redundant; just set the action of the form to where you want the user to be sent.
With the above in mind, try this:
<form id="yourForm" action="index.html">
<input type="text" name="foo" required />
<!-- Some more 'required' form controls... -->
<button type="submit">Submit</button>
</form>
$("#yourForm").on("submit", function() {
localeStorage.clear();
});
what you could do is to verify that the inputs are present before the redirect:
$("#btn").on("click", function() {
// do some checks
//if checks ok call redirect, if ko returns
window.location.replace("index.html");
localeStorage.clear();
})
You can verify the values, use fetch to send the form and then redirect.
( You can add some gestion of server response before redirect. Like "Login already in database ... )
$("#btn").on("click", function() {
const verif = *verifAndFormat(...)* // function that return json like {valid:true , data:... }
if( verif.valid ){
fetch( URL , {method:'POST', body: verif.data} )
.then( resp =>{
/*some operations*/
localeStorage.clear();
window.location.replace("index.html");
})
.catch( err => /*error gestion*/
}else{
/*Invalid value gestion*/
}
})
$(function(){
$('#btn').On('click', function() {
window.location.href="../index.html";
}
}
And also you can call it form html coding on click event to call function submit and redirect from that..
html coding
<input type="button" id="btn" onclick="submit()"/>
Javascript coding
function submit(){
window.location.replace("http://webpagename.index.html");
}

Add a dynamic form field after pressing a button

I have a form with a simple button $builder->add('language_switcher', ButtonType::class); which should simply, if pressed, add another field. To do that, I used Symfony's cookbook http://symfony.com/doc/current/form/dynamic_form_modification.html
$builder
->get('language_switcher')
->addEventListener(
FormEvents::POST_SUBMIT,
function () use ($builder, $options) {
$preparedOptions = $this->prepareOptions($options['data']['productCustomizations']);
$builder->add('lang_switcher'), ChoiceType::class, $preparedOptions);
}
);
When now submitting it via AJAX
<script>
var $button = $('#xyz');
$button.click(function() {
var $form = $(this).closest('form');
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
success: function(html) {
console.log(html);
$('#xyz').replaceWith($(html).find('#lang_switcher'));
}
});
});
</script>
I'm getting the error Buttons do not support event listeners. So I tried it out with a hidden field. I added the hidden field to the Form, set the EventListener to it, and added this data to my AJAX request
data[$('#id_of_hidden_field').attr('name')] = 1;
However this did nothing. The example in the cockbook is after submitting a choice field so I don't know how to adapt it to my needs. I couldn't use a SubmitType, because then it would submit the form, right? I just want to have it with a simple button.
The problem is, that, when I do a console.log(html) I don't see the new html element, so it seems like I'm not getting to the EventListener which is weird, because if I dump contents inside the listener I'm getting some data. It just seems like I'm not getting it inside the response
Ok, got it. The problem was that I used the builder inside the POST_SUBMIT event but I had to use a FormInterface. Since I couldn't add it AFTER submit I had to buy the same callback function as in Symfony's cookbook
$formModifier = function (FormInterface $form, $preparedOptions) {
$form->add($this->childIdentifier, ChoiceType::class, $preparedOptions);
};
And then the listener is built like this
$builder
->get('lang_switcher')
->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier, $options) {
$preparedOptions = $this->prepareOptions($options);
$formModifier($event->getForm()->getParent(), $preparedOptions);
}
);
<script type="text/javascript">
function inputBtn(){
var input=document.createElement('input');
input.type="file";
input.name="img[]";
input.multiple="multiple";
//without this next line, you'll get nuthin' on the display
document.getElementById('target_div').appendChild(input);
}
</script>
<button id="ifile" onclick="inputBtn();">create</button>
<form action="test.php" method="post" enctype="multipart/form-data">
<div id="target_div"></div>
<input type="submit">
</form>

AJAX / jQuery $.get method works, but $.post does not

Yesterday I made my first successful AJAX call using this function which was linked to a button click event.
function function1(){
$.get("ajax/calendar.php", function(data){
$('#ajaxResponse').html(data);
});
};
Now I would like to use the $.post method so that I can pass in 2 values that I had simply hard coded when I used the $.get method.
Here are my inputs and submit button:
<div ... >
<div ... >
<div ... >
<span ... >From:</span>
<input ... name="strDte">
</div>
<div ...>
<span ... >To: </span>
<input ... name="endDte">
</div>
</div>
<div ... >
<button type="submit" onclick="dateRange(strDte, endDte)">OK</button>
</div>
</div>
I created a similar function to my $.get method:
function dateRange(startD, endD){
$.post("ajax/calendar.php", {startDate : strDte, endDate : endDte}, function(data){
$('#ajaxResponse').html(data);
});
};
and I updated "ajax/calendar.php" to accept the value that were hard coded before:
$formStartDate = $_POST['startDate'];
$formEndDate = $_POST['endDate'];
EDIT: my console is telling me that the parameters are not being recognized by function call in the event handler.
Does anyone see what my issue is? I'd also love some design suggestions if you think there is a better way of achieving this function.
You are passing up form elements, not the values of the elements. You have wrong variable names.
Give the inputs ids
<input ... name="strDte" id="strDte">
<input ... name="endDte" id="endDte">
Update the JavaScript to reference the value.
function dateRange(startD, endD){
$.post("ajax/calendar.php", {startDate : startD.value, endDate : endD.value}, function(data){
$('#ajaxResponse').html(data);
});
};
You are using bad practice by referencing elements directly by their name/id and inline events are not the greatest thing to use. You should use getElementById or querySelector to reference the elements.
The variable names used in your function definition should match the names you use within your function. That is
{startDate : strDte, endDate : endDte}
should be
{startDate : startD, endDate : endD}
I suggest you play around with this fiddle: http://jsfiddle.net/Uwcuz/3657/
It is using a service from JSFiddle to echo back what you send to it. I changed the AJAX call to use $.post() instead of $.ajax() since this is the function you are playing with! :)
Some additional tips when learning such technologies. Always check with your browsers developers' tools. There you can follow the request being sent to your backend and catch any errors. The "Network" and "Console" (on Chrome dev tools, but Firefox has similar, too) tabs are your friends in this case!
Enjoy and happy learning!
Since you are not using a form, you should be declaring your button to be a button type to show that you are not submitting a form.
<button id="submitBtn" type="button">OK</button>
Your problem is that you are not supplying an id attribute for your <input> tags. name is only used in forms. Change your <input> tags to be
<input id="strDte">
<input id="endDte">
Then in your script, you can use
$("#submitBtn").click(function () {
var start = $("#strDte").val();
var end = $("#endDte").val();
$.post("ajax/calendar.php", { startDate: start, endDate: end }, function (data) {
$("#ajaxResponse").html(data);
}
});
The variable names you pass into the function must pass those you use in the data parameter of $.post(). You're passing:
startD but trying to use strDte .. and
endD but trying to use endDte .... strDte and endDte are not defined anywhere.
Try this instead:
function dateRange(startDate, endDate){
$.post("ajax/calendar.php", {startDate : startDate, endDate : endDate}, function(data){
$('#ajaxResponse').html(data);
});
};
UPDATE
Now that I know where the confusion was coming from the best approach is one that allows you to separate, clearly, your JS from your HTML.
Per your request for suggestions, here's how:
$(function() {
$('#my_form').on('submit', function(event) {
//stop the form from submitting via default submission
event.preventDefault();
//get form data
var formData = $(this).serialize();
//see what the data looks like
console.log( formData );
//make ajax call
$.post('ajax/calendar.php', formData, function(data){
$('#ajaxResponse').html(data);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="my_form">
<div><label for="strDte">Start Date:</label>
<input type="text" name="startDate" id="strDte"/>
</div>
<div><label for="endDte">End Date:</label>
<input type="text" name="endDate" id="endDte"/>
</div>
<div>
<input type="submit" value="OK" />
</div>
</form>
here is a simple ajax post you can play around with...
<input id="start_date" name="startDate" />
<input id="end_date" name="endDate" />
<button type="submit" id="submit_dates">Submit</button>
$(document).ready(function(){
$("button#submit_dates").click(function(){
var startDate = $("#start_date").val();
var endDate = $("#end_date").val();
$.ajax({
type:'POST',
url:'ajax/calendar.php',
data:"startDate=" + startDate + "&endDate=" + endDate,
success:function(data) {
if(data) {
$("#ajaxResponse").html(data);
} else {
// no response
}
}
});
});
});

AJAX returns data twice on submit

Instead of redirecting the user to a new page, I want to add an overlay over the form. Somehow, the following code returns the overlay twice.
AJAX
$(document).ready(function ()
{
$('#form_informations').submit(function ()
{
$.get('php/formulaires.php', $(this).serialize(), function (data)
{
$('#form_informations').append('<div id="conf_informations" class="confirm"><p><img src="img/check.png" /><br /><?=FORMULAIRE_SAUVEGARDE;?></p></div>');
});
return false;
});
});
The id #form_informations is only used once.
For now, the second overlay is not created in php/formulaires.php because the file is empty as I have not started parsing the data.
Why is this happening? I don't see where this second overlay is coming from.
This is the HTML form:
HTML Form
<form id="form_informations" method="post" enctype="multipart/form-data">
<!-- form here -->
<input type="submit" name="submit_general" value="Save" />
</form>
May be you can add some code like this in the submit function
if(!$("#conf_informations").size()) {
$.get... //your get request here
}
Final solution
if(!$("#conf_informations").length()) {
$.get... //your get request here
}

Handling Json results in ASP.NET MVC with jQuery

I am working on a view containing two forms, handled by separate controller actions which return a string serilaized to Json:
return Json(message);
The forms are submitted using jQuery, by clicking on a button outside the two forms.
The button handler:
$('#inviteForm').ajaxSubmit({
success: function(html, status) {
$("#response").text(html);
}
})
$('#trialForm').ajaxSubmit({
success: function(html, status) {
$("#response").append(html);
}
});
The browser receives the result and prompts the user to download as it is interpreted as "application/json".
However, if I only submit one of these forms in the jQuery, the resulting Json message is displayed as a string in the #response element as desired.
Why does adding a second ajaxSubmit() cause this different behaviour?
Thanks.
The view contains the following forms:
<form action="/Controller1/SaveAttachments/<%=Model.ObjectId %>" id="trialForm" method="post" enctype="multipart/form-data">
<input type="file" name="trialForm" size=30/>
<input type="file" name="trialSheet" size=30/>
<input type="file" name="trialApproval" size=30/>
</form>
and...
<form action="/Controller1/UpdateTemplate/<%=Model.ObjectId %>" id="inviteForm" method="post" enctype="multipart/form-data">
<%=Html.TextArea("invitationSheet", Model.InvitationSheet,
new { #name = "invitationSheet"})
<script type="text/javascript">
window.onload = function() {
var sBasePath = '<%=Url.Content("~/Content/FCKeditor/")%>';
var oFCKeditor = new FCKeditor('invitationSheet');
oFCKeditor.BasePath = sBasePath;
oFCKeditor.HtmlEncodeOutput = true;
oFCKeditor.ReplaceTextarea();
}
</script>
</form>
Update:
You can't upload files directly via AJAX so it is doing an actual post of the form containing file inputs. You should look at a plugin that will let you upload files using the hidden iframe technique that works asynchronously instead of trying to upload using AJAX.

Categories

Resources