$(...).jqBootstrapValidation is not a function at HTMLDocument.<anonymous> - asp.net

i am trying to implement a contact us page using bootstrap template. I am a really beginner in asp.net and its my first time using a template.
I cant really get it where is the problem that is causing the above error.
I want to when the user click the send Message button to send emails to a current business email.
Can anyone help me?
contact.cshtml
<div class="row">
<div class="col-lg-8 mb-4">
<h3>Send us a Message</h3>
<form name="sentMessage" id="contactForm" novalidate>
<div class="control-group form-group">
<div class="controls">
<label>Full Name:</label>
<input type="text" class="form-control" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block"></p>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Phone Number:</label>
<input type="tel" class="form-control" id="phone" required data-validation-required-message="Please enter your phone number.">
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Email Address:</label>
<input type="email" class="form-control" id="email" required data-validation-required-message="Please enter your email address.">
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Message:</label>
<textarea rows="10" cols="100" class="form-control" id="message" required data-validation-required-message="Please enter your message" maxlength="999" style="resize:none"></textarea>
</div>
</div>
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="btn btn-primary" id="sendMessageButton">Send Message</button>
</form>
</div>
</div>
</div>
<script src="~/Content/vendor/jquery/jquery.min.js"></script>
<script src="~/Scripts/contact_me.js"></script>
<script src="~/Scripts/jqBootstrapValidation.js"></script>
<script src="~/Content/vendor/bootstrap/js/bootstrap.min.js"></script>
contact_me.js
$(function () {
$('#contactForm input,#contactForm textarea').jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$this = $("#sendMessageButton");
$this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages
$.ajax({
url: "mail/contact_me.php",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append($("<strong>").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"));
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
complete: function() {
setTimeout(function() {
$this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
}, 1000);
}
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});

As my answer morphed through the comments:
the answer was that the OP added Jquery twice making a conflict in
file jqBootstrapValidation.js
Also, to help others based on the OP's post, this next part could be helpful as well:
Javascript files need to be loaded in the order of their dependence. Since your custom javascript file, contact_me.js depends on functions contained in the javascript file, jqBootstrapValidation.js, you need to load jqBootstrapValidation.js before contact_me.js, to fix this switch the order in which these files are loaded:
<script src="~/Content/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="~/Scripts/jqBootstrapValidation.js"></script>
<script src="~/Content/vendor/jquery/jquery.min.js"></script>
<script src="~/Scripts/contact_me.js"></script>

Related

Multiple submit button fail to find the handler method in asp.net core 3.1 razor page application

I have a single form which has two button one to upload image using ajax call & other is main submit button which saves all the data.
I am still very new to asp.net core and trying different thing to learn asp.net core with razor page.
I read lot of article about multiple form submit but most of then where using two form with submit button for each.
My issue is when i hit the submit button it fails to find the handler method, after full days troubleshoot nothing worked and last few article point to error/failure to antiforgery, i not sure how to implement it in below code as i tried few but they gave error may be article where old referencing core 2.2 etc example1 example2
I am not sure about the what exactly is causing the issue any help would be appreciate.
I am trying to upload Image using Ajax method in asp.net core Razor pages, I am main form in will all input fields are kept and with the form for Fileupload i am also added addition button which is for file upload using Ajax, When i hit the
<input type="submit" value="Upload Image" asp-page-handler="OnPostUploadImage" id="btnUploadImage" />
i want it to call OnPostUploadImage method in pageModel file but it alway goes to default OnPost method. when i rename the OnPost to OnPost2 nothing happend..
How can i call OnPostUploadImage() on button btnUploadImage click event.
When i hit click btnUploadImage it generates following error on browser console
Error in FF
XML Parsing Error: no root element found Location:
https://localhost:44364/Admin/News/NewsCreate?handler=OnPostUploadImage
Line Number 1, Column 1:
Error in Chrome
jquery.min.js:2 POST
https://localhost:44364/Admin/News/NewsCreateMultipleSubmit?handler=OnPostUpLoadImage
400 (Bad Request)
event though path looks fine but it cant find it as per error message
#page
#model BookListRazor.Pages.Admin.News.NewsCreateModel
#{
ViewData["Title"] = "News Create";
Layout = "~/Pages/Shared/_LayoutAdmin.cshtml";
}
<div class="border container" style="padding:30px;">
<form method="post" enctype="multipart/form-data">
<div class="text-danger" asp-validation-summary="ModelOnly"></div>
<input hidden asp-for="News.NewsImage" />
<input id="fileName" hidden value="" />
<div class="form-group row">
<div class="col-2">
<label asp-for="News.NewsHeading"></label>
</div>
<div class="col-10">
<input asp-for="News.NewsHeading" class="form-control" />
</div>
<span asp-validation-for="News.NewsHeading" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="News.NewsImage"></label>
</div>
<div class="col-10">
#*<input asp-for="News.NewsImage" type="file" class="form-control" id="NewsImage">*#
#*Photo property type is IFormFile, so ASP.NET Core automatically creates a FileUpload control *#
<div class="custom-file">
<input asp-for="NewsImageForUpload" class="custom-file-input form-control">
<label class="custom-file-label">Click here to change photo</label>
<input type="submit" value="Upload Image" asp-page-handler="OnPostUploadImage" id="btnUploadImage" />
</div>
</div>
<span id="imageStatus" class="text-danger"></span>
<span asp-validation-for="NewsImageForUpload" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-3 offset-3">
<input id="btnSave" type="submit" value="Create" class="btn btn-primary form-control" />
</div>
<div class="col-3">
<a asp-page="Index" class="btn btn-success form-control">Back to List</a>
</div>
</div>
</form>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/4.14.0/full/ckeditor.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script>
$(document).ready(function () {
$("#btnSave").addClass("disable-button");
$('.custom-file-input').on("change", function () {
var fileName = $(this).val().split("\\").pop();
$(this).next('.custom-file-label').html(fileName);
$("#fileName").val(fileName);
$("#btnSave").removeClass("disable-button");
});
if ($("#fileName").val() == "") {
//alert("Select Image...");;
}
});
</script>
</div>
#section Scripts{
<partial name="_ValidationScriptsPartial" />
<script>
$(function () {
$('#btnUploadImage').on('click', function (evt) {
console.log("btnUploadImage");
evt.preventDefault();
console.log("btnUploadImage after evt.preventDefault()");
$.ajax({
url: '#Url.Page("", "OnPostUploadImage")',
//data: new FormData(document.forms[0]),
contentType: false,
processData: false,
type: 'post',
success: function () {
alert('Uploaded by jQuery');
}
});
});
});
</script>
}
.cs file CODE
public async Task<IActionResult> OnPost()
{
if (ModelState.IsValid)
{
return Page();
}
else
{
return Page();
}
}
public IActionResult OnPostUploadImage()
{
//Some code here
}
Verify that you add the following code to the ConfigureServices method of startup.cs:
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
If you want to enter the OnPostUploadImage method, the url of the Ajax request needs to be changed to #Url.Page("", "UploadImage") without adding OnPost.
And the Ajax request should send the anti-forgery token in request header to the server.
Change your ajax as follow:
#section Scripts{
<partial name="_ValidationScriptsPartial" />
<script>
$(function () {
$('#btnUploadImage').on('click', function (evt) {
console.log("btnUploadImage");
evt.preventDefault();
console.log("btnUploadImage after evt.preventDefault()");
$.ajax({
url: '#Url.Page("", "UploadImage")',
//data: new FormData(document.forms[0]),
contentType: false,
processData: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'post',
success: function () {
alert('Uploaded by jQuery');
}
});
});
});
</script>
}
You can refer to this for more details.

Forbidden (CSRF cookie not set.):

i am using ajax to post data from asp (as front) to Django rest api (as backend)
First, I had a problem in Accessing to different domain but it solved using CORS
then i had another error which is related to CSRF
and the error like above :Forbidden (CSRF cookie not set.)
i've used #csrf_exempt to pass this validation but i want a solution for use it without csrf exmption
i tried more than one solution but it's not working or maybe i dont understand the way
Is there any clearly solution to solve it in ajax
In Error 403 ,
'''
JQuery sends " xhr.send( options.hasContent && options.data || null );
'''
i'll include code of my .cshtml file bellow
'''
form id="std_form" class="mx-auto form-horizontal" method="POST" asp-antiforgery="false">
#Html.AntiForgeryToken()
<div class="box-body">
<div class=" form-group">
<label for="inputEmail3" class="col-sm-3">ID</label>
<div class="col-md-8">
<input type="number" id="first">
</div>
</div>
<div class=" form-group">
<label for="inputEmail3" class="col-sm-3">ID</label>
<div class="col-md-8">
<input type="number" id="second">
</div>
</div>
<div class=" form-group">
<label for="inputEmail3" class="col-sm-3">ID</label>
<div class="col-md-8">
<input type="number" id="third">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer d-flex">
<button type="submit" id="save_btn" class="btn-success btn">Save</button>
</div>
<!-- /.box-footer -->
</form>
</div>
'''
'''
window.CSRF_TOKEN = "{% csrf_token %}";
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
'''
and this is ajax request
'''
$(document).on('submit', '#std_form', function (e) {
e.preventDefault();
let val1 = parseInt($('#first').val());
let val2 = parseInt($('#second').val());
let val3 = parseInt($('#third').val());
let x={val1,val2,val3};
$.ajax({
type: 'POST',
url: ('http://127.0.0.1:8000/Callfun/processdata/'),
data:{
First: val1,
Second:val2,
Third:val3,
csrfmiddlewaretoken: window.CSRF_TOKEN,
},
success: function (context) {
alert("Wooooooooowwwww");
$('#first').val(context.Max);
$('#second').val(context.Min);
$('#third').val(context.Avg);
},
error: function (context) {
alert("So Bad");
}
})
})
'''

Adding errors to form validation doesn't work?

According to the Semantic UI docs on form validation, I can add errors manually:
add errors(errors) | Adds errors to form, given an array errors
(I want to use this feature because I submit my form via AJAX, do server-side validation, then want to display the results.)
I tried the following code:
$('#my-form').form("add errors", [ 'error' ]);
$('#my-form').form("validate form");
I get this contradictory output from the console when calling the above methods, and the form validates as successful when it obviously shouldn't.
Any idea?
To perform server-side validation via AJAX, use a custom rule:
$myForm = $('.ui.form');
var settings = {
rules: {
custom: function () {
// Perform AJAX validation here
return false;
}
}
};
var rules = {
ajaxField: {
identifier: 'ajaxField',
rules: [{
type: 'custom',
prompt: 'Custom error!'
}]
}
};
$myForm.form(rules, settings);
Here it is in action: http://jsbin.com/sufiwafe/1/edit
For how to use callbacks and form validation in general, there is an important discussion on the Semantic-UI issues page on GitHub. The author mentions:
... the documentation was ambiguous but validation + settings is passed
like $(".form').form(rules, settings);
It appears like you are trying to recreate the wheel when using semantic ui.
Assuming you have included the complete versions of semantic.css in the head and semantic.js just above the body closing tag, here is an abbreviated version of working code for a simple contact form with some of the error work done by semantic and some by html5. For completeness I have included a user side captcha.
HTML
<form class="ui form" name="contact_sdta" action="" method="post">
<div class="field">
<label>Your Email </label>
<div class="ui left labeled icon input">
<input name="email" id="email" placeholder="name#mail.com" type="email">
<i class="mail icon"></i>
<div class="ui corner label">
<i class="asterisk red icon"></i>
</div>
</div>
</div>
<div class="field">
<label>Subject</label>
<div class="ui left labeled icon input">
<input name="subject" id="subject" placeholder="I am interested in more information about" type="text">
<i class="text file outline icon"></i>
<div class="ui corner label">
<i class="asterisk red icon"></i>
</div>
</div>
</div>
<div class="field">
<label>Message</label>
<div class="ui left labeled icon input">
<textarea name="message"></textarea>
<i class="text file outline icon"></i>
<div class="ui corner label">
<i class="asterisk red icon"></i>
</div>
</div>
</div>
<div class="ui buttons">
<input type="reset" value="Cancel" class="ui button">
<div class="or"></div>
<input type="submit" value="Submit" class="ui blue submit button">
</div>
<div class="ui error message"></div>
</form>
mainjs
$(function(){
$('form input[type=reset]')
.before('<div>Are you a human? <input type="checkbox" name="captcha" /><i class="asterisk red icon"></i></div><br />');
$('.ui.form').form({
email: {
identifier: 'email',
rules: [
{
type: 'empty',
prompt: 'Please enter your email'
}
]
},
subject: {
identifier: 'subject',
rules: [
{
type: 'empty',
prompt: 'Please enter a subject'
}
]
},
message: {
identifier: 'message',
rules: [
{
type: 'empty',
prompt: 'Please enter a message'
}
]
},
human: {
identifier: 'captcha',
rules: [
{
type: 'checked',
prompt: 'You must behuman'
}
]
}
});
});
I hope this helps to clear things up.
The developer confirmed this was a bug on GitHub:
https://github.com/Semantic-Org/Semantic-UI/issues/959
MVC5: Try Add this in the lowermost part of your View
#section Scripts {
#Scripts.Render("~/bundles/jqueryval") }

Form validation in meteorjs

I am doing simple validation of inputs in meteorjs, after first tour it works, and every next time it doesn't work (until I reload the page) – it means error messages are not displayed.
//main.js//
Template.addMealForm.events({
'click #submitNewMeal': function (ev) {
ev.preventDefault();
var query = {
name: $("#name").val().trim(),
price: $("#price").val(),
calories: $("#calories").val(),
category: $("#category").val()
};
areInputsValid(query);
}
});
var areInputsValid = function (query) {
if ((query.name.length === 0) || (query.price.length === 0) || (query.calories.length === 0)) {
$("#warningLabel").addClass("di")
$(".warningLabel").text("All fields are required");
}
else if ((isNaN(query.price) === true) || (isNaN(query.calories) === true)) {
$("#warningLabel").addClass("di")
$(".warningLabel").text("To Price and Calories fields please enter a number");
}
else {
console.log('it works');
$('.dn').hide();
}
};
//main.html//
<template name="addMealForm">
<form role="form">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control input_form" id="name" placeholder="Name of the meal">
</div>
<div class="form-group">
<label for="price">Price</label>
<input class="form-control input_form" id="price" placeholder="Price">
</div>
<div class="form-group">
<label for="calories">Calories</label>
<input class="form-control input_form" id="calories" placeholder="Calories">
</div>
<div id="warningLabel" class="form-group has-error dn">
<label class="control-label warningLabel"></label>
</div>
<button id="submitNewMeal" type="submit" class="btn btn-rimary">Add</button>
</form>
</template>
The problem is that you are calling $('.dn').hide() in the success case. Because #warningLabel has a class of dn it will not be displayed again on subsequent errors.
One solution is to add $('.dn').show() to the top of areInputsValid.
You already have Tracker as part of Meteor, so I put a little tutorial and JSfiddle together on how to use it to implement a typical form validation scenario.
http://bit.ly/meteor-form-validation-video
http://bit.ly/meteor-form-validation-fiddle

How to display Meteor.loginWithPassword callbak error message on the same page

I have created a custom login page and used the Meteor.loginWithPassword(user, password, [callback]) function to login to the app.
Following is the login template:
<template name ="Login">
<form class="login-form form-horizontal">
<div class="control-group">
<input class="email" type="text" placeholder="Email">
</div>
<div class="control-group m-inputwrapper">
<input class="password" type="password" placeholder="Password">
</div>
<div class="control-group">
<button type="submit" class="submit t-btn-login" >Login</button>
</div>
</form>
<div class="alert-container">
<div class="alert-placeholder"></div>
</div>
</template>
Template.Login.events({
'submit .login-form': function(e, t) {
e.preventDefault();
// retrieve the input field values
var email = t.find('.email').value,
password = t.find('.password').value;
Meteor.loginWithPassword(email, password, function(err) {
if (err) {
$(".alert-placeholder").html('<div></div><div class="alert"><span><i class="icon-sign"></i>'+err.message+'</span></div>')
}
});
return false;
}
});
While i debugging i can see the error message displayed and added to the dom. but it will get refresh and message will disappear.
Is meteor re render the page after Meteor.loginWithPassword() ? How can i overcome this?
When using meteor, if you find yourself manually injecting html elements with jQuery, you are probably doing it wrong. I don't know the blaze internals well enough to give you an exact answer to why your elements are not being preserved, but here is a more meteor-like solution:
In your alert container, conditionally render an error message:
<div class="alert-container">
{{#if errorMessage}}
<div class="alert">
<span><i class="icon-sign"></i>{{errorMessage}}</span>
</div>
{{/if}}
</div>
In your login callback, Set the errorMessage session variable if err exists:
Meteor.loginWithPassword(email, password, function(err) {
if (err) {
Session.set('errorMessage', err.message);
}
});
Finally, add a template helper to access the errorMessage session variable:
Template.Login.helpers({
errorMessage: function() {
return Session.get('errorMessage');
}
});
You can use Bert for showing error message in each page. I use it in login page like this :
Meteor.loginWithPassword(emailVar, passwordVar, function(error) {
if (error) {
Bert.alert(error.reason, 'danger', 'growl-top-right');
} else {
Router.go('/dashboard');
}
});

Resources