This question already has answers here:
Submit a form using jQuery [closed]
(22 answers)
Closed 5 years ago.
Here is my code:
<form action='insert.php' method='post' id='myform' >
<input type='hidden' name='tmdb_id'/>
<button id='insert'>Insert</button>
<p id='result'></p>
<script src='insert.js'></script>
</form>
<form action='insert.php' method='post' id='myform' >
<input type='hidden' name='tmdb_id'/>
<button id='insert'>Insert</button>
<p id='result'></p>
<script src='insert.js'></script>
</form>
<form action='insert.php' method='post' id='myform' >
<input type='hidden' name='tmdb_id'/>
<button id='insert'>Insert</button>
<p id='result'></p>
<script src='insert.js'></script>
</form>
Here is: insert.js
$('#myform').submit(function(){
return false;
});
$('#insert').click(function(){
$.post(
$('#myform').attr('action'),
$('#myform :input').serializeArray(),
function(result){
$('#result').html(result);
}
);
});
The Problem:
Only the code inside first <form></form> tag works. If i click on submit button of other<form></form> tags, then I get re-directed to insert.php file.
What is the problem? If it is related to same id thing, then I would not like to add different id's. for each new form
You don't need multiple instances of insert.js
Use common classes for all the forms and elements instead of duplication of ID's.
We can also use the submit event to post the data
HTML
<form action='insert.php' method='post' class='myform'>
<input type='hidden' name='tmdb_id' />
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' class='myform'>
<input type='hidden' name='tmdb_id' />
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<!-- load once per page -->
<script src='insert.js'></script>
JS
$('.myform').submit(function(){
// `this` is the instance of myForm class the event occurred on
var $form = $(this),
url = $form.attr('action'),
data = $form.serializeArray(); // or use serialize() which is more common
$.post( url, data, function(result){
// look inside this form instance for element to populate
$form.find('.result').html(result);
});
return false;
});
ID's Must Be Unique, specifically because it will cause problems in JavaScript and CSS when you try to interact with those elements.
Assuming you load insert.js once into the page:
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
Once you have that done you can use a single jQuery function to handle all of the forms:
$(function() {
$('.insert').click(function(e){
e.preventDefault();
$.post(
$(this).closest('.myform').attr('action'),
$(this).closest('.myform :input').serializeArray(),
function(result){
$(this).closest('.myform').find('.result').html(result);
}
);
});
});
You do have to do some DOM traversal to get the form elements related to the insert button.
$(this).closest('.myform') finds the parent of the insert button
$(this)closest(.myform').find('.result') finds the child element with the class of 'result' to add the results to.
Try something like below using jQuery Ajax:
$(".submit-button-class").click(function() {
var formData = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: "YOUR URL",
data: formData,
dataType: 'json',
beforeSend: function() {
//show loading image while processing
},
success: function(resp) {
// do something here
},
error: function(e) {
alert('error: ' + JSON.stringify(e));
}
});
});
Note: you should use class selector instead of id selector for submit button
Related
how to pass value selected from radio button to ajax url.
I have radio button select download/upload.
CODE:
<form id="listofiles" action="" class="post-form" role=form method="post">{% csrf_token %}
Select: Download:
<input class="form-check-input" name="optionsRadios" type="radio" value="download">
or Upload:
<input class="form-check-input" name="optionsRadios" type="radio" value="upload">
BUTTON:
<input type="submit" value="GO" id="download" name="download" class="btn btn-info" />
<input type="submit" value="GO" id="upload" name="upload" class="btn btn-warning" />
Based on which one is select button will show.
CODE:
<script>
$("input[name='optionsRadios']:radio")
.change(function() {
$("#upload").toggle($(this).val() == "upload");
$("#download").toggle($(this).val() == "download"); });
</script>
Once the user selects the options, it will load the data from the other HTML file into div
CODE:
<div id="fetchdata" align="center">
<!-- LOADING DATA FROM THE AJAX listofiles.html -->
</div>
AJAX CODE:
$("#listofiles").submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
url: 'listofiles.html',
type: $(this).attr('GET'),
data: $(this).serialize(), // get the form data
success: function(data) { // on success..
$("#fetchdata").html(data); // update the DIV
console.log(data);
}
});
return false;
});
HTML: listofiles.html
Issue, in this page, I have two forms with the different ID. How to load forms based on the optionsRadios selected.
CODE:
<div id="download" style="display:none"><div align="center" class="container">
<form id="download" action="download" role=form method="POST" class="post-form">{% csrf_token %}
. . .
<div class="col" align="left">
<button type="submit" name="download" class="btn btn-primary btn-lg">DOWNLOAD</button>
</div></div></form></div></div>
<div id="upload" style="display:none"><div align="center" class="container">
<form id="upload" action="upload" role=form method="POST" class="post-form">{% csrf_token %}
. . .
<div class="col" align="left">
<button type="submit" name="upload" class="btn btn-primary btn-lg">UPLOAD</button>
</div></div></form></div></div>
I am assuming that we stay on the same page: then we can update your code:
Reuse the same selector:
$("input[name='optionsRadios']:radio:checked").val() == "upload");
Use the checked pseudoselector to see which value was selected to toggle the correct div.
Executing this code will result in multiple elements with the same id name. Better to use class names or unique ids.
$("#listofiles").submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
url: 'listofiles.html',
type: $(this).attr('GET'),
data: $(this).serialize(), // get the form data
success: function(data) { // on success..
$("#fetchdata").html(data); // update the DIV
$("div[id='upload']").toggle($("input[name='optionsRadios']:radio:checked").val() == "upload");
$("div[id='download']").toggle($("input[name='optionsRadios']:radio:checked").val() == "download");
//there is already another element with id download | you need to change that, so circumventing like this for now.
}
}
});
return false;
});
Hello I want to get the value of this input and fetch it using ajax no database at all. thank you. how can i do it with ajax?
<form method="POST">
<input type="text" name="input" id="card-code" value='<?php echo $code ?>' class="form-control">
<input type="text" id="card-pin" value='<?php echo $code2 ?>' class="form-control" maxlength="3">
</form>
there is my inputs and here is the button.
<form action="top-up.php" method="POST">
</div>
</div>
<div class="col-md-6" style="margin-top: -160px">
<div class="caption">
<div class="jumbotron">
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt" onchange = "change()"></textarea><br><br><br>
<input class="btn btn-primary btn-lg" type="submit" name="btnSubcode" value="PROCESS"></input>
</div>
</div>
</div>
</div>
</form>
so the final output sould not refresh the page and the textarea value will be send to the textbox
The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process.
http://malsup.com/jquery/form/#getting-started
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<form id="myForm" action="comment.php" method="post">
Name: <input type="text" name="name" />
Comment: <textarea name="comment"></textarea>
<input type="submit" value="Submit Comment" />
</form>
// prepare Options Object
var options = {
target: '#divToUpdate',
url: 'comment.php',
success: function() {
alert('Thanks for your comment!');
}
};
// pass options to ajaxForm
$('#myForm').ajaxForm(options);
Firstly, rewrite your html code as below:
<form id="form" action="top-up.php" method="POST">
</div>
</div>
<div class="col-md-6" style="margin-top: -160px">
<div class="caption">
<div class="jumbotron">
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt"></textarea><br><br><br>
<input class="btn btn-primary btn-lg js-form-submit" type="submit"></input>
</div>
</div>
</div>
</div>
</form>
Then, you can write JS something like this:
$(document).on('click','.js-form-submit', function (e) {
e.preventDefault();
var formData = $('#form').serialize();
var url = $('#form').attr('action');
$.ajax({
type: "POST",
cache: false,
url: url // Your php url here
data : formData,
dataType: "json",
success: function(response) {
//var obj = jQuery.parseJSON(response); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handling here');
}
});
});
i am trying to build a customer list with using mysql,php and ajax. i currently have a list of customers displayed on the page and my end goal is to be able to create a new customer and edit the other customers on the same page.
i have a form for creating a new customer and then a form for each customer listed on the page its basically the same form as the new customer but with and id on the end of the name tags to make sure each name is different from the other and one updates and one creates see below
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form name='frm_details' id='frm_details' action=''>
<input type='text' class='form-control' name='box1' required>
<input type='text' class='form-control' name='box2' required>
<input type='submit' value='Save' >
</form>
<form name='frm_details' id='frm_details' action=''>
<input type='text' class='form-control' name='box1_2465' required>
<input type='text' class='form-control' name='box2_2465' required>
<input type='submit' value='Save' >
</form>
<script>
$(function() {
$('#frm_details').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: '/limitless/functions2.php',
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
if(data.status == '1')
{
$('#info').addClass('alert alert-danger no-border').html(data.message);
}
if(data.status == '2')
{
$('#info').addClass('alert alert-danger no-border').html(data.message);
}
}
});
});
});
</script>
this works flawlessly for the creation of a new customer however when i submit the second form to edit the customer with the id in the name tag it fails to execute the ajax is there any chance someone could point out where i am going wrong if possible i would like to keep a single ajax request just with the form id changed $('#frm_details2465')
1st: id must be unique as I said
2nd: you can change Ids like so
in html
<form name='frm_details' id='frm_details1' action=''>
<form name='frm_details' id='frm_details2' action=''>
in js
$('form[id^=frm_details]')
or you can use classes
<form name='frm_details' class='frm_details' id='frm_details1' action=''>
<form name='frm_details' class='frm_details' id='frm_details2' action=''>
and in js
$('form.frm_details')
I have a form with POST method and an action of another page.
Within the form i have another form that I need to make submit with a different action but its submitting with the main form action.
this is my second form:
<script>
function formSubmit()
{
document.getElementById("invoices_form").submit();
}
</script>
<form action="resend_multiple_invoices.php" name="invoices_form" method="post">
<input type="button" onclick="formSubmit()" value="Send Invoices" />
</form>
how can i get it to submit the second form and not the main one?
You cannot (universally) submit a nested form separately from its parent form. Nested forms are invalid HTML as outlined in the W3C prohibitions.
To solve your problem, I suggest you use two separate forms as follows:
<script>
function invoicesFormSubmit()
{
document.getElementById("invoices_form").submit();
}
function otherFormSubmit()
{
document.getElementById("other_form").submit();
}
</script>
<form action="resend_multiple_invoices.php" name="invoices_form" method="post">
//
// Input fields go here
//
<input type="button" onclick="invoicesFormSubmit()" value="Send Invoices" />
</form>
<form action="other_method.php" name="other_form" method="post">
//
// Input fields go here
//
<input type="button" onclick="otherFormSubmit()" value="Other Method" />
</form>
You can use the 'form'-attribute in your input-fields and then mix all your inputs.
By submitting they refer to the correct form.
<form action="" method="post" id="form1"></form>
<form action="" method="post" id="form2"></form>
<input name="firstname" form="form1">
<input name="firstname" form="form2">
<button type="submit" name="submit" form="form1">Save form 1</button>
<button type="submit" name="submit" form="form2">Save form 2</button>
See also https://www.w3schools.com/tags/att_input_form.asp
JQuery.ajax and html for validating an "inner form" through ajax, then submitting the entire form. I use ajax in both cases to show the purpose of a controller.php file and a submission id. You could also have an inner form which consists of several segregated sections by using classes instead of ids as Jquery selectors.
<form>
<input />
<textarea />
<select /> <!-- etc. -->
<section id="verify">
<input />
<textarea />
<select /> <!-- etc -->
<button type="button">submit</button>
<!-- eg. sub-submission verifies data in section -->
</section>
<select />
<input />
<input type="submit" value="submit" />
</form>
<script>
$(document).ready(function() {
$("#verify button").on ('click', verify);
$('form').submit (formSend);
function verify (){
// get input data within section only (ie. within inner form)
var postData = $('#verify').filter(':input' ).serializeArray();
postData.push ({name:"submitId", value:'verify'});
var request = $.ajax ({
type: "POST",
url: "controller.php",
data: postData,
error: function (xhr, status, message){
alert (status);
}
});
}
function formSend (){
// get input data within entire form
var postData = $(this).serializeArray();
postData.push ({name:"submitId", value:'send'});
var request = $.ajax ({
type: "POST",
url: "controller.php",
data: postData,
error: function (xhr, status, message){
alert (status);
}
});
}
});
</script>
I have the following code:
<form action="" id="search-form">
<fieldset>
<div class="rowElem">
<input type="text">
<a href="#" onClick="document.getElementById('search-form').submit()">
<div>Search</div>
</a></div>
</fieldset>
</form>
<script>
$(document).ready(function() {
$('#search-form').submit(function(event){
event.preventDefault();
alert("test");
});
});
</script>
When I submit the form I don't see the alert... What am I missing?
Thanks,
You need to remove your obtrusive onclick event and bind to the link instead.
You can't alert AFTER you submit, since that would perform whatever action you give to the form (most likely taking you off the page. If you insisted on doing so, the following would work.
<form action="" id="search-form">
<fieldset>
<div class="rowElem">
<input id="name" type="text"></input>
<a href="#" id="search" >Search</a>
</div>
</fieldset>
</form>
<script>
$(document).ready(function() {
$('#search').bind('click', function () {
// Alert the name BEFORE you do the form post
alert($('#name).val());
$('#search-form').submit(function(event){
});
});
});
</script>
I have a working JSFiddle example here: http://jsfiddle.net/7jqUF/5/
If, instead, you wanted an AJAX solution, you'd want to do something other than a form post, such as an ajax post
<script>
$(document).ready(function() {
$('#search').bind('click', function () {
// Alert the name BEFORE you do the form post
alert($('#name).val());
$.post('/ServerUrl/method', { name: $('#name').val() });
});
});
</script>
Why don't you do something like
<form action="" id="search-form">
<fieldset>
<div class="rowElem">
<input name="query" type="text" /><br />
<a class="search" href="#">Search</a>
</div>
</fieldset>
</form>
and
var form = $('#search-form');
$('.search', form).click(function(event){
event.preventDefault();
var query = $('input[name="query"]', form).val();
alert("test: " + query);
});
Demo: Fiddle
If you want to use the params as part of a ajax request you can do something like
var form = $('#search-form');
$('.search', form).click(function(event){
event.preventDefault();
var params = form.serialize();
alert("test: " + form.serialize());
$.ajax({
url: '...',
data: params,
....
})
});
Please try the following code. After removing the submit code from the $(document).ready function
<a href="#" onclick="document.getElementById('search-form').submit();">