How to use a javascript function for multiple html forms - javascript

I am trying to use a java script function for multiple html forms with no luck. Following is my code. Please help me out. Thanks
html forms
<form id="my_form_id">
Your Email Address: <input type="text" id="email" /><br>
<input type="submit" />
<div id='loader' style='display:none'>
<img src='images/loader.gif'/>
</div>
</form>
<form id="my_form_id">
Your Email Address: <input type="text" id="email" /><br>
<input type="submit" />
<div id='loader' style='display:none'>
<img src='images/loader.gif'/>
</div>
</form>
Javascript
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
$('#my_form_id').on('submit', function(e){
$('#loader').show();
//Stop the form from submitting itself to the server.
e.preventDefault();
var email = $('#email').val();
$.ajax({
type: "POST",
url: 'xml.php',
data: {email: email},
success: function(data){
alert(data);
$('#loader').hide();
}
});
});
});
</script>

You can use jquery multiple-selector like
$('#my_form_id,#my_form_id2').on('submit', function(e){
Id need to be unique for each html element
Also there is duplicate email id. But you will like to get the email specific to that form. In That case you can use class and then use find
$(document).ready(function() {
$('#my_form_id,#my_form_id2').on('submit', function(e) {
$('#loader').show();
//Stop the form from submitting itself to the server.
e.preventDefault();
var email = $(this).find('.email').val(); // children
console.log(email)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="my_form_id">
Your Email Address: <input type="text" class="email" /><br>
<input type="submit" />
<div id='loader' style='display:none'>
<img src='images/loader.gif' />
</div>
</form>
<form id="my_form_id2">
Your Email Address: <input type="text" class="email" /><br>
<input type="submit" />
<div id='loader' style='display:none'>
<img src='images/loader.gif' />
</div>
</form>

The main issue is because id attributes need to be unique. As you're repeating them throughout the HTML on both the form and the email inputs only the first instances of each will be found.
To fix this issue change them to class attributes. From there you can use DOM traversal to find the elements related to the form which was submit in order to retrieve the required data. Try this:
jQuery(function($) {
$('.my_form').on('submit', function(e) {
e.preventDefault();
var $form = $(this);
var email = $form.find('input[name="email"]').val();
$form.find('.loader').show();
$.ajax({
type: "POST",
url: 'xml.php',
data: { email: email },
success: function(data) {
console.log(data);
$form.find('.loader').hide();
}
});
});
});
.loader {
display: none;
}
<form class="my_form">
Your Email Address: <input type="text" name="email" /><br>
<button type="submit">Submit</button>
<div class="loader">
<img src="images/loader.gif" />
</div>
</form>
<form class="my_form">
Your Email Address: <input type="text" name="email" /><br>
<button type="submit">Submit</button>
<div class="loader">
<img src="images/loader.gif" />
</div>
</form>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

The ids in a document should be unique, convert the ids to a class,
<form class="my_form_class">
And attach the listener on selecting the class.
$('.my_form_class').on('submit', function(e){// rest of the code})

Related

PHP - Submit button and get value without refresh

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');
}
});
});

ajax upload file form

I have two forms, one for uploading a file and another for filling the form with information. I need to upload the file without refreshing the page first and then submit the form using ajax. And here are the codes:
form_file
<h1>Insert Employee</h1>
<form id="form">
<input id="name" placeholder="arabic name.." type="text" name="name_ar"/><br>
<input id="name" placeholder="english name.." type="text" name="name_en" value=""/><br>
<input id="name" placeholder="arabic department.." type="text" name="dep_ar" /><br>
<input id="name" placeholder="english department.." type="text" name="dep_en" /><br>
<input id="name" placeholder="arabic job.." type="text" name="job_ar"/><br>
<input id="name" placeholder="english job.." type="text" name="job_en" /><br>
<input id="name" placeholder="extention#.." type="text" name="ext" /><br>
<input id="name" placeholder="office#.." type="text" name="office" /><br>
<input id="name" placeholder="mobile#.." type="text" name="mobile" /><br>
<input id="email" placeholder="email" type="text" name="email"/><br>
<br /><br />
<div class="upload_form">
<form id='form1'>
<input type="file" name="userfile" size="20" />
<input type="button" value="upload" id="upload" />
</form>
<br/><br/>
</div>
<input type="button" value="Click" id="submit"/>
<input type="reset" value="Reset"/>
</form>
</div>
AND HERE IS THE AJAX: I know how to submit data using ajax but I need help for how to upload a file using ajax without refreshing the page, and then take the name of that file, send it again with the form, and save it to database.
<script>
$(document).ready(function(){
$('#upload').click(function(){
console.log('upload was clicked');
//ajax POST
$.ajax({
url:'upload/do_upload',
type: 'POST',
success: function(msg) {
//message from validation php
//append it to the contact_form id
$('#uploud_form').empty();
$('#uploud_form').append(msg);
}
});
return false;
});
$('#submit').click(function(){
console.log('submit was clicked');
//empty msg value
//$('#msg').empty();
//Take form values
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
};
//ajax POST
$.ajax({
url:'',
type: 'POST',
data: form_data,
success: function(msg) {
//message from validation php
//append it to the contact_form id
$('#contact_form').empty();
$('#contact_form').append(msg);
}
});
return false;
});
});
</script>
Not sure whether I get it properly or not. I will try to answer as per my understanding.
You need to write server side code which will save the image on server.
I believe you are able to make the AJAX call to initiate point 1.
From your upload service (point 1), your should return the "relative path" of the image which was uploaded.
In success callback of your AJAX call (point 2) you should be able to capture the relative path.
Once the relative path has been captured you should add it to DOM or say any element.
Then you can start another AJAX call or post back (submit form) based on your requirement.
If this is not the problem then please be specific in what you need and provide more information.
I do it like this and it's work for me :)
<div id="data">
<form>
<input type="file" name="userfile" id="userfile" size="20" />
<br /><br />
<input type="button" id="upload" value="upload" />
</form>
</div>
<script>
$(document).ready(function(){
$('#upload').click(function(){
console.log('upload button clicked!')
var fd = new FormData();
fd.append( 'userfile', $('#userfile')[0].files[0]);
$.ajax({
url: 'upload/do_upload',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
console.log('upload success!')
$('#data').empty();
$('#data').append(data);
}
});
});
});
</script>

Multi form submit with one selector use jquery ajax

I have a problem with jquery ajax multi form.
every execution is always part of the form at the top, to form the other does not work.
can help me.
this Source Code
<form id="form_action" action="http://www.dom.dom/act/">
<input type="text" name="nama" value="" />
<button type="submit" >Save</buton>
</form>
<form id="form_action" action="http://www.dom.dom/act/">
<input type="text" name="nama" value="" />
<button type="submit" >Save</buton>
</form>
<form id="form_action" action="http://www.dom.dom/act/">
<input type="text" name="nama" value="" />
<button type="submit" >Save</buton>
</form>
<form id="form_action" action="http://www.dom.dom/act/">
<input type="text" name="nama" value="" />
<button type="submit" >Save</buton>
</form>
jquery ajax nya :
$("‪#‎form_action‬").on('submit', function(e){
e.preventDefault();
var link = $(this).attr("action");
var data = $(this).serialize();
$.ajajx({
url:link,
data:data,
type:"POST",
typeData:'html',
cache:false,
success: function(data){
//// bla bla //
}
});
return false;
});
How to use this jquery for multi form..?
When you use an id selector ($('#some-id')) you get only the first element that matches your selector, not an array as you get with other selectors.
Also, it seems that they're all the same form.. What are you trying to achieve? Maybe you can use the same form and just change action attribute or some input in the form.
Another thing, as #dave mentioned in the comments, there's no $.ajajx function in jQuery :-)

Working with multiple ajax forms in same page

After a suggestion from this question Multiple forms in in a page - load error messages via ajax
I am trying to work multiple forms in same page. I am trying to append error messages in to the respective input div classes.
I don't want to have different form ids because i need to have single id in the jquery then.
I have forms like
<form class="myform" name="myform">
<div class="name">
<input type="text" name="name" />
</div>
<div class="message">
<input type="text" name="message" />
</div>
<input type="submit" name="submit" />
</form>
<!-- second form -->
<form class="myform" name="myform">
<div class="name">
<input type="text" name="age" />
</div>
<div class="message">
<input type="text" name="gender" />
</div>
<input type="submit" name="submit" />
</form>
and the jQuery part is
$('.myform').on('submit', function(event) {
postform = $(this);
event.preventDefault();
$(this).ajaxSubmit({
url: 'process.php',
type: 'post',
dataType: 'json',
success: function( response ){
$.each(response, function(index, element){
var msgdiv = postform.children('div.' + divclass).append('<span>'+message+'</span>');
}
}
});
});
however the ajax part is working but the error messages do not load in the div tags as defined in the jQuery 'div.' + divclass. Any help would be appreciated
Like this?
postform.find('.message').append('<span>' + message + '</span>');

Submit a php form and display its result on div without reloading page

First of all, thank you for your kind help.
I have tried almost everything I found on stackoverflow but I cannot get this to work.
I created a form to send a text to the webmaster (instead of an email). So I have my index.php file
<style>
.result{
padding: 20px;
font-size: 16px;
background-color: #ccc;
color: #fff;
}
</style>
<form id="contact-form" method="post">
<div>
<input type="text" id="fullname" name="fullname" value="" placeholder="Name" required="required" autofocus="autofocus" autocomplete="off" />
</div>
<div>
<input type="email" id="email" name="email" value="" placeholder="example#yourdomain.com" required="required" autocomplete="off" />
</div>
<div>
<textarea id="message" name="message" value="" placeholder="20 characters max." required="required" maxlength="50" autocomplete="off" ></textarea>
</div>
<div>
<input type="submit" value="Submit" id="submit-button" name="submit" />
*indicates a required field
</div>
</form>
<div class="result"></div>
And this is my jquery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#contact-form').submit(function() {
$.ajax({
type:"POST",
url:"sendtext.php",
data: $("#contact-form").serialize(),
success: function(response){$(".result").appendTo(response)}
});
//return false;
});
});
</script>
The script does not work. If I put action = sendtext.php in the <form> it will work perfectly but it will take me to sendtext.php and echo the message.
What I want is to show the echo in the <div class="result"></div>.
Again thank you for your help.
UPDATE # 1
After a few comments...
this is what I have so far...
<script>
$(document).ready(function(){
$('#contact-form').submit(function(e) {
e.preventDefault();
$.ajax({
type:"POST",
url:"sendtext.php",
data: $("#contact-form").serialize(),
success: function(response){$(".result").append(response)}
});
//return false;
});
});
</script>
Update 2
After reading all the comments and try different options, no success just yet! I did what #guy suggested, and it worked but I want to use form and submit.
Again, I appreciate all your time you put to help me out. Thank you!
The problem is that when you add sendText.php as the action, your jQuery will execute because the form is submitted so that will work... BUT it will also take you to the page of the form's action field. What you want to do is not call submit but just make a button instead and have the jQuery listen to a click on that button.
Instead of:
<input type="submit" value="Submit" id="submit-button" name="submit" />
Change it to a regular button:
<button id="submit-button">Submit</button>
Then in your jQuery, change the line
$('#contact-form').submit(function() {
to
$('#submit-button').click(function() {
Also, change appendTo to html and then the result should show up in your result div.
----EDIT----
This worked for me:
<style>
.result{
padding: 20px;
font-size: 16px;
background-color: #ccc;
color: #fff;
}
</style>
<div id="contact-form" >
<div>
<input type="text" id="fullname" name="fullname" value="" placeholder="Name" required="required" autofocus="autofocus" autocomplete="off" />
</div>
<div>
<input type="email" id="email" name="email" value="" placeholder="example#yourdomain.com" required="required" autocomplete="off" />
</div>
<div>
<textarea id="message" name="message" value="" placeholder="20 characters max." required="required" maxlength="50" autocomplete="off" ></textarea>
</div>
<div>
<button id="submit-button">Submit</button>
*indicates a required field
</div>
</div>
<div class="result"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit-button').click(function() {
$.ajax({
type:"post",
url:"sendText.php",
data: $("#contact-form").serialize(),
success: function(response){
$(".result").html(response);
}
});
});
});
</script>
Use the the preventDefault() function so that the form doesn't do the redirection on submit.
After that, use append() instead of appendTo()
$('#contact-form').submit(function(e) {
e.preventDefault();
Change:
$(".result").appendTo(response)
to:
$(".result").append(response)
Can you try this,
$(".result").html(response);
instead of
$(".result").appendTo(response)
Jaavscript:
$(document).ready(function(){
$('#contact-form').submit(function() {
$.ajax({
type:"POST",
url:"sendtext.php",
data: $("#contact-form").serialize(),
success: function(response){
$(".result").html(response);
}
});
return false;
});
});
Your appendTo in success callback is backward. In your example, you are trying to append the .result element to the response variable. Should be:
success: function(response){ response.appendTo(".result")}

Categories