Post multiple forms with Jquery - javascript

I have multiple forms in my page. I'd like to be able to post those forms from single Jquery function.
It only work for the first form. I think this is because all forms have the same Id, I would need to use click function() instead of submit() and use something like $(this).closest("form") ...
<form class="form-horizontal" role="form" id="fpostcomm">
<input name="cmt" type="text" class="form-control input-sm" id="inputcommt" autocomplete="off">
</form>
<script>
$(document).ready(function(){
$("#fpostcomm").submit(function(){
$.ajax({type:"POST", data: $(this).serialize(), url:"ajax/ajxaaddcmt.php",
success: function(data){
$("#inputcommt").val('');
},
error: function(){
alert ("Error.");
}
});
return false;
});
});
</script>

You cannot reuse IDs. They must be unique in a document. Fix that and you can then grab them however you need.
If you want a single shared name on all of them, use a class instead.
<form class="form-horizontal fpostcomm" role="form">
<input name="cmt" type="text" class="form-control input-sm inputcommt" autocomplete="off">
</form>
<script>
$(document).ready(function(){
$(".fpostcomm").submit(function(){
$form = $(this);
$.ajax({type:"POST", data: $(this).serialize(), url:"ajax/ajxaaddcmt.php",
success: function(data){
$form.find(".inputcommt").val('');
},
error: function(){
alert ("Error.");
}
});
return false;
});
});
</script>

Related

Stop form from redirecting on submit

I'm very aware that this question has been asked several times but I have tried at least 6 solutions and it has not worked. I'm collecting data to send to a google form but on form submission the browser redirects to a success page. I'd like for it to all happen using AJAX but my code isn't working.
HTML:
<form id="userinfo" method="get" action="https://script.google.com/macros/s/xxx/exec" accept-charset="UTF-8" onsubmit="return false">
<input type="text" name="name" id="formname" placeholder="Name">
<input type="text" name="email" id="formemail" placeholder="Email">placeholder="Game Days">
<input type="submit" value="submit" id="upload_data"/>
</form>
JS:
$("#userinfo").submit(function(e) {
var urll = "https://script.google.com/macros/s/xxx/exec"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: urll,
data: $("#userinfo").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
You could use the jQuery Form Plugin to send the form without doing a submit.
Your code should look kinda like this:
$("#userInfo").ajaxSubmit({
success: function(data)
{
alert(data); // show response from the php script.
}
});

AJAX HTTP post request is triggered 3 times

In my webapp, the Ajax request is executed 3 times, and I have no idea why this is happening.
Can someone please help here?
My Javascript:
$(document).ready(function() {
console.log("ready!");
$('form').on('submit', function(e) { //
e.preventDefault();
// on form submission ...
console.log("the form has beeen submitted");
// grab values
valueOne = $('input[name="perfid"]').val();
valueTwo = $('input[name="hostname"]').val();
valueThree = $('input[name="iteration"]').val();
console.log(valueOne)
console.log(valueTwo)
console.log(valueThree)
$.ajax({
type: "POST",
url: "/",
dataType:'json',
data : { 'first': valueOne,'second': valueTwo,'third': valueThree},
success: function(data) {
var res = data.AVG;
var p = '<p><pre>'+res+'</pre></p>';
$('#result').append(p);
},
error: function(error) {
console.log(error)
}
});
}); });
And my HTML is:
<form role="form" method="post" onsubmit="return false;">
<div class="form-group">
<input type="text" class="input-medium" id="perfid" name="perfid" placeholder="Enter a Perf ID" required style="height:30px;">
<input type="text" class="input-medium" id="hostname" name="hostname" placeholder="Enter a HostName" style="height:30px;">
<input type="text" class="input-medium" id="iteration" name="iteration" placeholder="Enter a Iteration" required style="height:30px;">
<button type="submit" class="btn btn-default" style="height:30px;">Get Data</button>
</div>
</form>
I have written the code for only one AJAX POST request,
EDIT:
This is the console output:
Please make sure you have included the js file only once,
and add a return false at the end of the submit event callback
look at the selector
$('form').on('submit', function(e) {
if the page has 3 forms, the above selector will execute 3 times
Try to add id to the form like this. sorry about my bad english

How to submit form using Ajax in MVC

I am getting problem to save my form data in the database. I am done small code on that which is shown below, when i enter data in form and click on my submit button it not work.
$(".btn").click(function(e) {
e.preventDefault();
var form = $("#frm");
$.ajax({
url: '/Form/Index',
data: form.serialize(),
type: 'POST',
success: function(data) {
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" id="frm">
<div class="form-group">
<div class="col-sm-6 col-lg-12 col-md-12">
<div class="form-group">
<label for="name" style="color:black;">Product Name</label>
<input type="text" class="form-control" id="name"
placeholder="Product Name" style="color:black;">
</div>
<div class="form-group">
<label for="name" style="color:black;">Product Date</label>
<input type="text" class="form-control" id="Text1"
placeholder="Date" style="color:black;">
</div>
<div class="form-group">
<label for="name" style="color:black;">Product Price</label>
<input type="text" class="form-control" id="Text2"
placeholder="Date" style="color:black;">
</div>
</div>
</div>
<button type="submit" class="btn btn-default" id="ok" >Submit</button>
</form>
Above is my code please give me solution on that
As I've checked you code, client side code is working fine, The only problem I can imagine in this case is you url path.
make sure you are providing correct url path.
You should check if its hitting the that page or not.
Which Framework you are using. Different framework has different syntax to pass the value in URL. Check the path you are getting in the page source page view in URL parameter or you can check the error in console log after the submit. It may be not getting the correct path of your action.
Make sure ajax library loaded successfully, and try to have alert messages to have forward step where you reached, have this test:
$(".btn").click(function(e) {
e.preventDefault();
var form = $("#frm");
$.ajax({
url: '/Form/Index',
data: form.serialize(),
type: 'POST',
success: function(data) {
},
beforeSend: function() {
alert('before send alert')
},
error: function (request, status, error) {
alert(error);
},
});
});
if beforeSend not executed so your issue is related to ajax library.
use this :
$("#ok").click(function(e) {
// your code
}
Refer to id in javascript rather than class attribute.
If you refer class attribute than once it has click javascript perform preventDefault on that class so that if not refresh your page, The button is not working.
Put preventDefault function at last of your function.
Remove the type="submit" from button
You have to get the form submit with id and serialize the form data
`
$("#formid").submit(function(e) {
var url = "urlpathtohandlerequest";
$.ajax({
type: "POST",
url: url,
data: $("#formid").serialize(),
success: function(response)
{
alert(response);
}
});
e.preventDefault(); // stops default submit.
});
`

aria-required on jquery submit form

let say i have the following form
<form action="post">
<label for="firstName">First name:</label>
<input id="firstName" type="text" aria-required="true" />
<input type="submit" value="submit">
</form>
and with jQuery i want to do $.post(), i use following jQuery script
jQuery(function($){
$(SUBMIT_BTN).on('click', function(e){
var data = $('form').serialize() + '&action=save_customer';
$.ajax({
url: MYRUL,
method: 'POST',
data: data,
success: function(response){
$('form').trigger('reset');
}
});
});
});
with that script the aria-required is not working any longer. how to trigger validation in this case?
PS: I want to use this aria-required, avoiding jQuery plugins
use required="required" instead of aria-required="true"

Repopulating div with new form/content using jQuery/AJAX

Are there any jQuery/AJAX functions that when a form (or anything for that matter) is displayed, upon pressing a button the div containing the original form is replaced by a new form? Essentially, a multi-part form without having to reload the page.
Can I use something like this?
$('form#myForm').submit(function(event) {
event.preventDefault();
$.ajax({
type: '',
url: '',
data: $(this).serialize(),
success: function(response) {
$('#divName').html(response);
//somehow repopulate div with a second form?
}
})
return false;
});
I've used this before for adding items to a list, but I've never used it to totally repopulate it with different content. How can I direct it to the second form?
edit - I got it to work, but only when I write '#form2' for the replacement. I alerted the response and I get {"formToShow":"show2"}. I tried doing response.formToShow but it's undefined.
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
</head>
<div id="divName">
<form method="POST" action = "#" id="form1">
<input type="textbox" name="textbox1" value="1"/>
<input type="submit" name="submit1"/>
</form>
<form method="POST" action = "#" id="form2" style="display: none">
<input type="textbox" name="textbox2" value="2"/>
<input type="submit" name="submit2"/>
</form>
</div>
<script>
$('form#form1').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'JSON',
url: 'receiving.php',
data: $(this).serialize(),
success: function(response) {
$('#form1').hide(); //hides
//$('#form2').show(); //this will show
$(response.formToShow).show(); //this does not display form 2
}
})
return false;
});
</script>
Here is receiving.php. When I view this page {"formToShow":"show2"} is displayed
<?php
echo json_encode(array("formToShow" => "#form2"));
?>
Check the JQuery Load Function
This is personal preference, but I'd never send HTML through the response and display it like that, what I'd do is:
Send a JSON array back from the server, such as { formToShow: "#form1" }
Then you can simply do this:
success: function(response) {
$('form').hide();
$(response.formToShow).show();
}
Obviously, using this method, you'd also have to have the second form in your markup like this:
<form method="POST" action = "#" id="form2" style="display: none">
<input type="textbox" name="textbox2"/>
<input type="submit" name="submit2"/>
</form>
You'd also have to change (to pickup the array):
$.ajax({
type: 'JSON'
try this
$('form#myForm').submit(function(event) {
event.preventDefault();
$.ajax({
type: '',
url: '',
data: $(this).serialize(),
success: function(response) {
$('#divName').html(response);
$('#form1').hide();
$('#form2').show();
}
})
return false;
});
<form method="POST" action = "#" id="form1">
<input type="textbox" name="textbox1"/>
<input type="submit" name="submit1"/>
</form>
<form method="POST" action = "#" id="form2" style="dispay:none;">
<input type="textbox" name="textbox2"/>
<input type="submit" name="submit2"/>
</form>

Categories