Laravel Add Loader while submitting - javascript

Currently I am doing laravel and my submit somehow takes a long time loading (for like 5 seconds) because I am sending an email
I would like to add a loader while its still submitting just like in ajax, but I am not using ajax for this. I used a form submit here
index.blade.php
<form id="form-contact" name="form-contact" action="{{route('inquiries.submit')}}" method="post" enctype="multipart/form-data">
// some fields
</form>
Route
Route::post('/contact/inquiries', 'ApiController#contactForm')->name('inquiries.submit');
Controller
public function contactForm(Request $request)
{
$data['fname'] = $request->fname;
$data['lname'] = $request->lname;
$data['body'] = $request->body;
$data['recipient_email'] = $request->email;
$data['type'] = 'Inquiry';
//some email sending code
Session::put('inquirySuccess', 'Task successfully added!');
$this->emailSent->create($data);
return redirect()->back();
}
inquiry.js
angular.module('app').controller('inquiryController', function($scope, $http, $window) {
if ($('#inquiry-success').length) {
swal({
title: "Inquiry Sent!",
text: "",
type: "success",
showCancelButton: false,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'OK',
})
}
});
How do I add loader while until the submission is completed? I am using laravel 1.4

You will not be able to do that without ajax call. Because if you submit a form, you are gone from the current page. So make the form submission Ajaxify and show a loader until you get a response from server.

Related

How can i get a stripe token on my controller with checkout?

i'm trying to get a stripe token when i use checkout, but when i submit the embeded form i don't have a POST method and i don't know how i can have the token on my php controller too.
Here is my code :
<script>
var handler = StripeCheckout.configure({
key: 'pk_test_WWlLRtqEY2yfJUlfA4TRRcyf',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function(token) {
console.log(token.id);
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
// Open Checkout with further options:
handler.open({
name: 'Musée du Louvre',
description: 'Biletterie en ligne',
currency: 'eur',
amount: '{{ price }}' * 100,
email: '{{ mail }}',
allowRememberMe: false,
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener('popstate', function() {
handler.close();
});
i tried with this :
<form post="" method="post">
my script code
</form>
but when i click on pay the page don't resfresh.
Someone can help me?
The idea is to change the code in the token callback to send the token to your server instead of logging it to the console.
Change your form to have a hidden field for the stripe token id and the email entered by the customer:
<form action="/your/route" method="POST" id="payment-form">
<input type="hidden" id="stripeToken" name="stripeToken" value="tok_XXX" />
<input type="hidden" id="stripeEmail" name="stripeEmail" value="email#example.com" />
</form>
And then change your JS to set those values and submit the form:
token: function(token) {
$("#stripeToken").val(token.id);
$("#stripeEmail").val(token.email);
$("#payment-form").submit();
}
This will submit your form and your route on the server will receive the stripeToken and the stripeEmail values in the POST parameters.

Validate username and password without postback in login form ASP.NET MVC

I want to validate the entered username and password entered in the textboxes present in a form without Postback/Refresh. I know I am gonna need Javascript or AJAX for this purpose, but somebody please guide me through this like refer me to any tutorial or please explain me the code here.
My present code without this feature looks like this:
#using(Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.TextBoxFor(u => u.PPNumber, new { #class = "form-control", type = "number", placeholder = "Enter Number",#min="1" })
#Html.ValidationMessageFor(u => u.PPNumber)
#Html.TextBoxFor(u => u.Password, new { #class = "form-control", type = "Password", placeholder = "Password" })
#Html.ValidationMessageFor(u => u.Password)
<input type="submit" value="Login" class="btn btn-primary btn-block" />
}
You can use ajax.
When user submits the form, you need to hijack that event in javascript and stop that(prevent the normal full page form submit) and instead make an ajax call to the action method with the form data. This action method should have code to verify the user credentials and can return a JSON data structure which has a status property which says whether the credential validation is successful or not. You can inspect this response in your ajax call's success/done callback and act accordingly.
Here is a quick sample using jQuery $.post method.
Give an Id to your form so that we can use that to wire up the submit event.
#using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id="loginForm"))
{
#Html.TextBoxFor(u => u.PPNumber)
#Html.TextBoxFor(u => u.Password, new { #class = "form-control", type = "Password"})
<input type="submit" value="Login" class="btn btn-primary btn-block" />
}
and the javascript code to hijack the submit event and do an ajax post instead.
$(function () {
$("#loginForm").submit(function(e) {
e.preventDefault();
$.post($(this).attr("action"), $(this).serialize())
.done(function(response) {
if (response.status === 'success') {
alert("Login successful.Do something else now");
} else {
alert("Login failed");
}
});
});
});
Assuming your Login action method in AccountController will return a Json response with a status property.
public ActionResult Login(string PPNumber,string password)
{
if(PPNumber=="thisIsDemo" && password=="ButDoTheActualCheck")
{
return Json(new { status = "success" });
}
return Json(new { status = "failed" });
}
Here i just hard coded the usrename /password check to 2 static values. You can change that to check it against your db table/whatever your credentials checking mechanism is.

VueJS prevent form submission on submit and submit the form on keyup

I have a form that looks like this:
<form id="myForm" action="/searchuser" method="POST" #submit.prevent="onSubmit(inputValue)">
<div class="field">
<label class="label">Name</label>
<div class="control">
<input class="input" type="text" placeholder="Text input" v-model="inputValue" #keyup="onKeyUp" #blur="inputFocused = false">
<ul v-if="inputFocused">
<li v-for="value in values"><a class="panel-block is-primary" :href="value.link">#{{value.title}}</a></li>
</ul>
</div>
</div>
</form>
And in my JavaScript, I have two methods onSubmit and onKeyPress:
<script>
export default {
data() {
return {
inputValue: "",
inputFocused: false,
values: [
{ title: "facebook", link: "http://facebook.com" },
{ title: "twitter", link: "http://twitter.com" },
{ title: "gplus", link: "http://plus.google.com" },
{ title: "youtube", link: "http://youtube.com" }
]
};
},
methods: {
onKeyUp: function() {
document.forms["myForm"].submit();
this.inputFocused = true;
},
onSubmit: function(inputval) {
console.log(inputval);
}
}
};
</script>
What I am trying to achieve is when the user presses a key, I want the form to be submitted but I don't want the page to be redirected to /searchuser route. But as soon as I press a key, the page gets redirected even though I am using the prevent modifier to prevent the submission. How do I prevent it from being redirected and submit it on keyup/keydown only? My goal is to perform an ajax call through onSubmit by sending the inputval to the server.
Vue is not overriding the DOM default behavior, if you decide to
access the DOM API directly while bypassing vue mechanics (e.g.
document.forms)
If you want to submit a form without the redirection, you have to do
ajax request.
you have to use axios (my personal choice). because you are trying to submit the form directly ...in order to keep up with the default form submission data format, I assume you need to sereialize the data as application/x-www-form-urlencoded format. check the docs.
see the code:
onKeyUp method:
onKeyUp: function() {
axios.post("/searchuser", qs.stringify({ inputValue: inputValue }));
this.inputFocused = true;
},
Remember to add axios and qs to your dependencies using npm, and import them on the file.

Bootbox incorrectly submits a form when a single input field is present

I have a strange problem that's really starting to bug me. Apologies in advance for a wall of code and somewhat confusing question.
I need to display a modal form for the user, and have them fill in some details.
The user can click Save to save their changes.
The user can click Cancel to cancel their changes.
I use the save handler to serialize the form and send its data to a JSON service.
If I have a form with multiple input fields, it all works great, and nothing unexpected happens.
If I have a form with a single input field, however, I get an unexpected side-effect. Hitting Enter/Return in that input field causes the modal form to be submitted, and instead of my JSON handler getting called the page is reload with the form's arguments as parameters — exactly as if the form is being submitted. In fact, adding an action= parameter to the form element has proven that, as you get navigated to the page you specify.
Here's the form I'm using:
<form id="surveyQuestionForm" class="form-horizontal" style="display:none;">
<div class="row">
<input name="surveyQuestionId" id="surveyQuestionId" type="hidden">
<input name="surveyId" type="hidden" value="${survey.surveyId}">
<div class="control-group">
<label class="control-label" for="questionType"><b><spring:message code="survey.question.type"/></b></label>
<div class="controls">
<select class="input-large" name="questionType" id="questionType">
<option value="">(Select one)</option>
<c:forEach items="${surveyQuestionTypes}" var="surveyQuestionType">
<option value="${surveyQuestionType.code}">${surveyQuestionType.name}</option>
</c:forEach>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="questionText"><b><spring:message code="survey.question.text"/></b></label>
<div class="controls">
<input type="text" class="input-xlarge" name="questionText" id="questionText" maxLength="64"/>
</div>
</div>
</div>
</form>
and here's the code I use to display the form modally:
function addQuestion() {
// find the form, and initialise its validation.
var form = $('#surveyQuestionForm');
var validator = form.validate(
{
rules: {
questionType: {
required: true
},
questionText: {
required: true
}
},
messages: {
questionType: {
required: '<spring:message javaScriptEscape="true" code="survey.question.type.required"/>'
},
questionText: {
required: '<spring:message javaScriptEscape="true" code="survey.question.text.required"/>'
}
},
onkeyup: false
});
// reset form validation, and hide any error message
validator.resetForm();
$("#errorMessage").hide();
// show the dialog
bootbox.dialog({
title: '<i class="icon-plus green"/> <spring:message javaScriptEscape="true" code="survey.add.question"/>',
message: form,
closeButton: false,
buttons: {
cancel: {
label: '<i class="icon-remove bigger-130"></i> <spring:message javaScriptEscape="true" code="button.cancel"/>',
className: "btn btn-danger"
},
save: {
label: '<i class="icon-ok bigger-130"></i> <spring:message javaScriptEscape="true" code="button.save"/>',
className: 'btn btn-success',
callback: function () {
var result = false;
if (!form.valid())
return false;
$.ajax({
type: "POST",
url: '/addSurveyQuestion.json',
async: false,
data: form.serialize(),
success: function (outcome) {
if (outcome.success) {
$('#question-list').dataTable().fnReloadAjax();
result = true;
}
else {
$("#errorMessage").html(htmlEncode(outcome.message)).show();
}
}
}
).fail(function () {
$.gritter.add({
title: '<spring:message javaScriptEscape="true" code="general.error"/>',
text: '<spring:message javaScriptEscape="true" code="server.error"/>',
class_name: 'gritter-error'
}
);
}
);
return result;
}
}
},
show: false,
animate: false,
onEscape: false
}
).on('shown.bs.modal', function () {
var form = $('#surveyQuestionForm');
form.find('#surveyQuestionId').val(null);
form.find('#questionType').val('');
form.find('#questionText').val('');
form.show().find('#questionType').focus();
form.show();
}
).on('hide.bs.modal', function (e) {
if (e.target === this)
$('#surveyQuestionForm').hide().appendTo('body');
}
).modal('show').addClass("bootboxDialog40");
}
If I use this code as-is, with Bootbox 4.4, hitting Enter/Return while the user is in the questionText field submits the form, and my page redisplays but with the form fields as parameters, eg:
page.html?surveyQuestionId=&surveyId=3&questionType=Y&questionText=blah
If I have a second input field, hitting Enter/Return in the fields does nothing, and the user has to click Save or Cancel.
Submit-on-enter for a single input field is a browser behavior that you will need to override. You can do this a few ways.
<form onSubmit="return false;">
I don't think you are using the native submit function at all, so adding this bit of inline scripting prevents the form submission. But putting scripts in your markup isn't great. A little jQuery can do the same thing for you:
$('form').on('submit', function(){ return false; });
I believe this is not related to bootbox plugin. The actual reason is here:
https://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2
When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form.
Coming to the solution, you can add another hidden field in your form which will prevent the submission of the form on enter.

Why my javascript won't post or submit to my database?

I've create a form using jQuery and I want to submit it into my SQL SERVER Database by AJAX. but It won't submit, I don't know where the problems comes. I create this site with ASP.
Here is the javascript to submit:
$("#reg_tr_new").click(function(){
$("#refresh_tr").submit();
});
$("#refresh_tr").validate({
debug: false,
rules: {
deskripsi: "required"
},
messages: {
deskripsi: {
required: 'Deskripsi harus diisi'
}
},
success: "valid",
submitHandler: function(form) {
$("#right-container").hide();
$("#add_no").show();
.post('trx_menu/queries/svTR_.asp', $("#refresh_tr").serialize(), function(data) {
$('#refresh_tr_show').html(data);
});
}
});
Here is the code in trx_menu/queries/svTR_.asp:
<%
noTrx=request.form("noTrx")
deskripsi=request.form("deskripsi")
from=request.form("from")
tos=request.form("tos")
user_input=Session("ss_ckduser")
BankTrx=request.form("BankTrx")
Dim tgl_inpt
tgl_inpt=Now
strsql="select count(*)+1 as idtrbaru from "& dbweb &".dbo.trmitrareghd"
set qdata = conn.execute(strsql)
idbaru = qdata("idtrbaru")
strsql="insert into "& dbweb &".dbo.trmitrareghd values('"& idbaru &"','"& noTrx &"','"&BankTrx&"','"& deskripsi &"','"&date()&"','"&date()&"','0','"& user_input &"','"& tgl_inpt &"')"
set qdata = conn.execute(strsql)
'response.write strsql
%>
You have the validation plugin debug option set to true which blocks form submittal while you ...debug!
You are also missing a $ before post
.post('trx_menu/queries/svTR_.asp'......
Should be:
$.post('trx_menu/queries/svTR_.asp'......
Use a browser console to check script and syntax errors as well as to inspect the request itself.

Categories