could give me an example to extract data from input after submit button and send in same page to output h2?
This my input and submit button.
<div class="input-field col s6">
<i class="material-icons prefix">perm_identity</i>
<input placeholder="..." id="nameClient" name="nameClient" type="text" class="validate">
<label for="nameClient">Nome do cliente:</label>
</div>
<button class="btn waves-effect waves-light indigo" id="publish-sell" type="submit"><i class="material-icons left">attach_money</i>EFETUAR VENDA</button>
Was using this example to extract the typed data input to another input by means of a click.
$("#copyMapResearch").click(function () {
var endereco = $("#addressDeliveryClient").val();
$("#pac-input").val(endereco);
});
$("#copyToForm").click(function () {
var endereco = $("#pac-input").val();
$("#addressProvider").val(endereco);
});
The purpose of this code is to introduce it into a complete function of ajax.
$(document).ready(function () {
$('#draft-sell').click(function () {
var payload = {
nameClient: $('#nameClient').val(),
nameFantasySell: $('#nameFantasySell').val(),
addresOfClientSell: $('#addresOfClientSell').val(),
annotations: $('#annotations').val(),
neighborhood: $('#neighborhood').val(),
cep: $('#cep').val(),
phoneLandline: $('#phoneLandline').val(),
cellphone: $('#cellphone').val(),
autocompleteBusinessReseller: $('#autocompleteBusinessReseller').val(),
amountProduct: $('#amountProduct').val(),
productSoldSell: $('#productSoldSell').val(),
producFinalPrice: $('#producFinalPrice').val(),
registeredDaySell: $('#registeredDaySell').val()
};
$.ajax({
url: "/product/sell-draft",
type: "POST",
contentType: "application/json",
processData: false,
data: JSON.stringify(payload),
complete: function (data) {
// here is the place of the code that will extract the data from the data entered in the input and write in front-end
}
});
});
});
This my final html tag to display results.
<h2 class="left-align white-text person-name" id="nameClientReciept">
Thanks for help!!
If you want to use a form with submit button, then you need to use the submit action of the form, and prevent the default.
let form = document.querySelector('form');
let nameClinet = document.querySelector('#nameClient');
let output = document.querySelector('#output');
form.onsubmit = function(e){
e.preventDefault(); // stop the submit from actually happening
console.log("Client Name:", nameClient.value);
output.innerText = nameClient.value;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>
<form>
<div class="input-field col s6">
<i class="material-icons prefix">perm_identity</i>
<input placeholder="..." id="nameClient" name="nameClient" type="text" class="validate">
<label for="nameClient">Nome do cliente:</label>
<h2 id="output"></h2>
</div>
<button
class="btn waves-effect waves-light indigo"
id="publish-sell"
type="submit">
<i class="material-icons left">attach_money</i>EFETUAR VENDA
</button>
</form>
Related
I found setting the title a bit awkward, it's complicated to exaplain in 1 sentence.. Some of our pages use popups where the user can fill in fields and then send. This is based on some Kallyas stuff and works fine with just text fields. After submitting, user staus on the same page, the form stays open and in it the message appears that the form has been sent (or not). There is also recaptcha handling in it.
Now I need to give the possibility to upload a file and this is where I am stuck. There is a .js file that does the handling. It picks up the form and does a ajax submit. I can see the form field of my input type="file" here, but with a fakepath/empty. If, in this javascript I try to append the file to the form I can submit, but the the backend says the form field is not there.
First, let me share the code.
The form :
<!-- Application form pop-up element content -->
<div id="application_panel" class="mfp-hide contact-popup">
<div class="contact-popup-panel">
<div class="container-fluid">
<div class="row">
<div class="col-md-12 col-sm-12">
<!-- Application form pop-up element -->
<div class="applicationForm pop-up-form" style="padding:50px;">
<!-- Title -->
<div id="jatitlewrapper">
<h3 class="m_title m_title_ext text-custom contact-popup-title c_title">
Some title
</h3>
<h4 class="tbk__subtitle fw-thin dark">
</h4>
</div>
<form id="appform" action="#request.projectname#/scripts/ajax/save/processform.cfm" method="post" class="contact_form row mt-40" enctype="multipart/form-data">
<div id="jafldwrapper">
<div class="col-sm-6 kl-fancy-form">
<input type="text" name="firstname" id="cf_firstname-pop-up" class="form-control" placeholder="Vul hier je voornaam in" value="" tabindex="1" required>
<label class="control-label">
VOORNAAM
</label>
</div>
<div class="col-sm-6 kl-fancy-form">
<input type="text" name="lastname" id="cf_lastname-pop-up" class="form-control" placeholder="Type je achternaam in" value="" tabindex="1" required>
<label class="control-label">
ACHTERNAAM
</label>
</div>
<div class="col-sm-12 kl-fancy-form">
<input type="text" name="place" id="cf_place-pop-up" class="form-control" placeholder="Voeg een onderwerp toe" value="" tabindex="1" required maxlength="78">
<label class="control-label">
WOONPLAATS
</label>
</div>
<div class="col-sm-12">
<label class="label_upl">
UPLOAD FILE
</label>
<input id="resume" style="padding-bottom:15px;" type="file" name="resume" id="cf_subject-pop-up" class="" placeholder="" value="" tabindex="1">
</div>
<cfif Application.isProductionURL>
<div class="col-sm-12" style="margin-left:15px;">
<div class="g-recaptcha" data-sitekey="somesitekey"></div>
</div>
<div class="col-sm-6">
<!-- Contact form send button -->
<button id="submitbtn" class="btn btn-fullcolor" type="submit" onClick="$('.g-recaptcha-response').attr('name','g_recaptcha_response');">
Send
</button>
</div>
<cfelse>
<div class="col-sm-6">
<!-- Contact form send button -->
<button id="submitbtn" class="btn btn-fullcolor" type="submit">
Send
</button>
</div>
</cfif>
<div class="col-sm-6" style="text-align:right;">
<button class="btn btn-fullcolor" type="button" onClick="closePopup();">
Cancel
</button>
</div>
</div>
<input type="hidden" name="fjobuuid" id="fjobuuid" value="">
</form>
</div>
<!--/ Application form pop-up element -->
</div>
<!--/ col-md-12 col-sm-12 -->
</div>
<!--/ .row -->
</div>
<!--/ .container -->
</div>
<!--/ .contact-popup-panel -->
<button title="Sluiten (Esc)" type="button" class="mfp-close">×</button>
</div>
<!--/ Application form pop-up element content -->
Some javascript for the popup to show :
window.onload = function() {
$('.abutton').magnificPopup({
closeBtnInside: true,
type: 'inline',
preloader: false
});
}
The standard js that handles the sumbit and works with all text fields on the form :
if(typeof($('.applicationForm form, .applicationForm.pop-up-form form, .contact_form form')) != 'undefined') {
$.each($('.applicationForm form, .applicationForm.pop-up-form form, .contact_form form'), function(index, el) {
var cform = $(el),
cResponse = $('<div class="cf_response col-sm-12"></div>');
cform.prepend(cResponse);
cform.h5Validate();
cform.submit(function(e) {
$('#g-recaptcha-response').attr('name','g_recaptcha_response');
e.preventDefault();
if(cform.h5Validate('allValid')) {
cResponse.hide();
$.post(
$(this).attr('action'),
cform.serialize(),
function(data){
console.log(data);
cResponse.html(data).fadeIn('fast');
if(data.match('success') != null) {
cform.get(0).reset();
}
}
); // end post
}
return false;
});
});
}
The backend does some handling of the fields and then produces a message, which is then visible in the popup :
<cfoutput><div class="alert alert-success alert-dismissible" role="alert"><p>Message sent, thank you</p></div></cfoutput>
or a message with class alert-danger if something went wrong.
Now I tried adding the file field 'resume' to the form by adding a cform.append, right after the cform.submit :
var files = $("#resume")[0].files;
for (var i = 0; i < files.length; i++) {
cform.append(files[i].name, files[i]);
}
It does loop and seems to append the file.
But the backend says form.resume is not there.
I tried writing my own submit :
$("#submitbtn").on("click", function(e) {
var form = $("#appform");
var params = form.serializeArray();
var files = $("#resume")[0].files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
$(params).each(function (index, element) {
formData.append(element.name, element.value);
});
$.ajax({
type: "POST",
url: $(form).prop("action"),
data: formData,
processData: false,
error : function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);}
,
success : function(data){
console.log(data);
}
});
})
Then the backend has all fields needed, including the actual file. But then I don't know how to integrate staying on the same url with the popup still in place and the message from the backend in the right place.
Then I tried changing the button type from sumbit to button, but then it won't let me send the file with the ajax call.
$.ajax({
type: "POST",
url: 'proctname//scripts/ajax/save/processform.cfm',
data: formData,
processData: false,
contentType: false,
error : function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);}
,
success : function(data){
var obj = $.parseJSON( data );
console.log(data);
}
});
Giving form field 'resume' is undefined. Apparently it needs to be a form submit.
Can I add the file field 'resume' to the standard code after the cform.submit, keep page and popup open, have the message handling etetc and if so, how?
I have a button for a form. When I click the button, the form is created. After being created, the form is not working with Ajax. My script codes are in here. My #testform is not wrong because it's working without creating form. Do you have any ideas?
function addDiv() {
var panel = document.querySelector(".add_new");
var div = document.createElement("div");
div.innerHTML = '<br> <form id="testform" method="POST"> <div class="row" style="padding-left:10rem;"> <div class="col-md-4"> <input type="text" class="form-control" value="" placeholder="Başlık" name="yeniBaslik" required></div> <div class="col-md-4"> <input type="text" placeholder="Açıklama" name="yeniAciklama" class="form-control" value="" name="" required> </div> <div class="col-md-2 text-left"> <button type="submit" class="btn btn-success btn-animated btn-wide addToDatabase">Add to the Database</button> </div> </row> </form> <br>';
panel.appendChild(div);
}
$("#testform").submit(function(e) {
e.preventDefault();
var formData = new FormData($("#testform").get(0));
$.ajax({
url: 'config.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function() {
setTimeout(
function() {
$(".addToDatabase").html("Successfully.");
}, 1000);
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="addDiv()"> Create a form </button>
<div class="add_new"></div>
Since second statement is executed before "div" is created, submit event is not being listened to on the new <form>
function addDiv() {
/*...*/
panel.appendChild(div);
$("#testform").submit(function(e) { /*...*/ });
}
Button Click search prefect Working Only Error For Search By Enter Key
Only For NoRecord Result Otherwise Working Correctly
if i search No record result it working once again even i try to correct record does not work hide the popup form & submitted successful mgs display.
This Is the Enter Key Function
$("#app-search").keyup(function (event) {
if (event.keyCode == 13) {
$(".search-pool").click();
}
});
<div class="modal-body">
<div class="row">
<div class="col-md-4 pull-right" id="search-view">
<div class="input-group">
#Html.TextBoxFor(m => m.search, new { id = "app-search", #class = "form-control"})
<a id="btn-clear-search2" class="fa fa-times-circle-o"></a>
<span class="input-group-btn">
<button class="search-pool btn btn-primary" type="button">
<span class="fa fa-search"></span>
</button>
</span>
</div>
</div>
</div>
This is the Button Click Function
$('.search-pool').on('click', function () {
$('#label-error').hide();
$.ajax({
url: '#Url.Action("PoolDetails")',
type: 'GET',
dataType: 'html',
data: { search: $('#app-search').val() }
})
.done(function (responce) {
$('#pool-details').html(responce);
$('#btn-clear-search2').show();
checkSelected();
FillSelected();
})
});
I need to submit form using through Ajax call but I'm having trouble selecting the form. I don't want to use form ID because I'm having multiple forms and I need to setup one code for all
$(".pay").on("click",function(){
var form = $(this).closest(".card-body").find("form");
//$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {
})
//});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card" >
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body" >
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline" >decline</button>
</div>
</div>
No need to add form submit code because you are preventing submit, so when will you click just fetch data from the form and call your AJAX service.
I added one console log where you can see your form data.
$(".pay").on("click",function(){
var form = $(this).closest(".card-body").find("form");
var formData = $(form).serialize();
console.log(formData);
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body" >
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline" >decline</button>
</div>
</div>
This will help you to reduce duplicating the code..
$(document).ready(function() {
$('form').on('submit', function(e){
e.preventDefault();
Var action = $(this).action;
Var method = $(this).method;
Var data = $(this).serialize();
// perform ajax operation here with data, action and method
});
});
Happy coding :)
Your code is creating submit handler everytime the button is clicked, all you want is to send ajax call onclick, so just do that part.
$(".pay").on("click",function(){
var form = $(this).closest(".card-body").find("form");
// below code is creating submit handler everytime the button is clicked
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {
})
});
});
Also .find returns jQuery object, no need to make it Jquery object again, simple form will do instead of $(form).. rather declare like var $form = $(this).closest(".card-body").find("form")
Something like below, try
$(".pay").on("click",function(){
var $form = $(this).closest(".card-body").find("form");
e.preventDefault();
var formData = $form.serialize();
submitForm(formData);
});
function submitForm(formData){
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {
})
}
I've created below sample to refer
$(function() {
$(".pay").on("click", function(e) {
var $form = $(this).closest(".card-body").find("form");
e.preventDefault();
var formData = $form.serialize();
console.log(formData)
submitForm(formData);
});
function submitForm(formData) {
alert("submitting form with " + formData)
$.ajax({
type: 'POST',
url: "php/pay.php",
data: formData
})
.done(function(response) {})
}
});
.card {
width: 50%;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body">
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline">decline</button>
</div>
</div>
<div class="card">
<div class="card-header">
<h1>YYY</h1>
</div>
<div class="card-body">
<form>
<input name="user2" value="mat2" type="hidden">
<input name="id2" value="122" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay2</button>
<button class="btn btn-danger decline" value="decline">decline2</button>
</div>
</div>
Erm.. Why not just put the two buttons inside the form, to avoid any confusion or off-chance that the script might trigger another one of the "multiple forms" and refer to the nameless form through the parent element instead, like?
html:
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline">decline</button>
</form>
script:
$(function() {
$(".pay").on("click", function(e) {
var $form = $(this).parent();
e.preventDefault();
var formData = $form.serialize();
submitForm(formData);
});
I've setup a view which contains a search form:
<form>
<input type="hidden" id="product_id" value="{{$tour->id}}">
<div class="form-group col-md-4">
<label>Date:</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control pull-right" id="start" placeholder="Start Date">
</div>
</div>
<div class="form-group col-md-4">
<label>End:</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control pull-right" id="end" placeholder="End Date">
</div>
</div>
<div class="form-group col-md-4" id="dateprice-search">
<label></label>
<button type="submit" class="btn" id="btn-search" >
Search
</button>
</div>
The below is the ajax code to handle the request of the form:
$(document).ready(function() {
$('#dateprice-search').on('click', '#btn-search', function() {
$.ajax({
type: 'post',
url: '/date-price',
data: {
'_token': $('input[name=_token]').val(),
'product_id': $("#product_id").val(),
'start': $("#start").val(),
'end': $("#end").val()
},
success: function(data) {
$('.shadow-z-1').show();
$('.shadow-z-1').append("<tr class='liquid-row><td>" + data.start + "</td><td>"+ data.end + "</td><td>" + data.end + "</td><td><a class='btn-m btn btn-m-success'>Available</a></td></tr>");
}
});
});
});
Route:
Route::post('/date-price','GetPublicController#datePrice')
->name('searchDate');
And finally method in controller to give the results:
public function datePrice(Request $request){
$start = $request->start;
$end = $request->end;
$dates = DatePrice::where('tour_id','=',$request->product_id)
->whereBetween('start', array($request->start, $request->end))
->whereBetween('end', array($request->start, $request->end))
->get();
return response()->json($dates);
}
At first the url looks like this before submitting the form http://localhost:8000/trips/popular/trekking/test and url becomes http://localhost:8000/trips/popular/trekking/test? after clicking the search button. Console section of inspect element shows no error in script. What mistake I had made over here ?
It mean your form submiting to same page due to type="submit"
1) change to type="button"
<button type="button" class="btn" id="btn-search" >
2) Here click event should be for button not to div so change the selector and add e.preventDefault(); in jquery to prevent the default submit .
$('#btn-search').on('click', '#btn-search', function() { e.preventDefault(); });
note :
1st : your action attribute missing so form will be submit same page .
2nd : your method attribute missing so it will take default GET method
You have given button type as submit, either remove it as
<button type="button" class="btn" id="btn-search" >
Search
</button>
or use the jquery preventDeafult() function to prevent the default behavior of submit button i.e form submit in your button click event as
$(document).ready(function() {
$('#dateprice-search').on('click', '#btn-search', function(e) {
e.preventDefault();
//your ajax code
});
});