I want to create a form inside a popover and use jQuery and Ajax to submit the form(do some calculation while submitting the form). But somehow jQuery is not working at all. I'm using ruby on rails.
Here is my code on the view:
%a.btn.btn-small{:id => "example", "data-toggle" => "popover", :type => "button"}
%i.icon-calendar
.head.hide Do Something
.content.hide
=form_for :object, action: '#', :html => { :class => "form", remote: true} do |c|
=c.number_field :var_1
=c.number_field :var_2
%buttion.btn.btn-default{id: "submit", type: "button"}Click
Here is my code in js and jQuery under app/assets/javascript,
$(function () {
$('#example').popover({
html : true,
title: function () {
return $(this).parent().find('.head').html();
},
content: function () {
return $(this).parent().find('.content').html();
}
}).popover('show');
});
$(function(){
$('.form').submit(function(e) {
alert(1);
e.preventDefault()
var datastring = $(this).serializeArray();
datastring.push({name:"post", value:"Post"});
var request = $.ajax({
type: "POST",
url: $(this).attr('action'),
data: datastring});
request.success(function(data) {
console.log(data);
})
});
});
When I click "Click" button, there is even no alert(1) showing up, so i think the jQuery is not working but I can't work out what is going wrong?
Use this instead, this will bind the submit event in ajax loaded content
$('body').on('submit', '.form', function(){
# your code
});
if you follow the best practices then you should be writing jQuery like this :
$(document).ready(function(){
$('body').on('submit', '.form', function(){
// your code
});
});
Related
I have a limited understanding of JavaScript, but with some copying and pasting I managed to make a form that gets sent via AJAX.
I'm also running the standard Boostrap 5 input validation. It all worked fine until I found out AJAX fires even without some fields missing.
Then I tried to put the AJAX stuff inside the validation function, but now I need to press "Submit" twice. I understand why, but I don't know how to solve it and would need some help.
This is what I came up with:
(function () {
'use strict'
// Fetch all the forms we want to apply validation styles to
var forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
var frm = $('#orderform');
frm.submit(function (e) {
var formData = {
firstName_r: jQuery('#firstName_r').val(),
lastName_r: jQuery('#lastName_r').val(),
action:'the_ajax_mail'
};
$.ajax({
type : 'POST',
url : "<?php echo admin_url('admin-ajax.php'); ?>",
data : formData,
encode : true
}).done(function(data) {
console.log(data);
form.classList.remove('was-validated');
document.getElementById('submitForm').disabled = true;
}).fail(function(data) {
console.log(data);
});
e.preventDefault();
});
}, false)
})
})()
I know the part with var frm = $('#orderform'); and frm.submit(function (e) { needs to go, but I have no idea how...
Try this
(function() {
'use strict'
// Fetch all the forms we want to apply validation styles to
var forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function(form) {
form.addEventListener('submit', function(event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
return
}
form.classList.add('was-validated')
var formData = {
firstName_r: jQuery('#firstName_r').val(),
lastName_r: jQuery('#lastName_r').val(),
action: 'the_ajax_mail'
};
$.ajax({
type: 'POST',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: formData,
encode: true
}).done(function(data) {
console.log(data);
form.classList.remove('was-validated');
document.getElementById('submitForm').disabled = true;
}).fail(function(data) {
console.log(data);
});
e.preventDefault();
}, false)
})
})()
A have an 'Add to basket' button which submits a form via Ajax with all products' details. At the moment the module responsible for that operation is loaded straight away when the website is loaded. I would like it to be loaded only when the button is clicked, though. This is what I have so far:
$('form:not(.contact-form__items)').on('submit', event => {
import('./modules/adding-products-to-basket.js')
.then(module => {
module.AddingProductsToBasket.addProductToBasket(event);
});
});
Module's content:
export const AddingProductsToBasket = {
addProductToBasket (event) {
const _this = AddingProductsToBasket;
event.preventDefault();
$.ajax({
url: 'basket',
method: 'POST',
data: $(event.currentTarget).serialize(),
dataType: 'text',
success: function(response) {
_this.openAddedToBasketLightbox();
}
},
});
}
};
I'm not getting any errors in the console but the problem is that
event.preventDefault() inside addProductToBasket doesn't do it's job, so user is taken to the basket page instead of staying on the page where the 'Add to basket' button is.
Thank you both for your help. It's working now.
Loading the module when the form shows:
if ($('form:not(.contact-form__items)').length) {
import('./modules/adding-products-to-basket.js')
.then(module => {
$('form:not(.contact-form__items)').on('submit', event => {
module.AddingProductsToBasket.addProductToBasket(event);
});
});
}
Loading the module not when the form loads but when it is submitted:
(event.preventDefault() in AddingProductsToBasket() can be removed)
$('form:not(.contact-form__items)').on('submit', event => {
event.preventDefault();
import('./modules/adding-products-to-basket.js')
.then((module) => {
module.AddingProductsToBasket.addProductToBasket(event);
});
});
I have an Asp.Net MVC web application. I want to run some code on the successful response of the API method which is called on form submit.
I have the below Code.
#using (Html.BeginForm("APIMethod", "Configuration", FormMethod.Post, new { #class = "form-horizontal", id = "formID" }))
{
}
$('#formID').submit(function (e) {
$.validator.unobtrusive.parse("form");
e.preventDefault();
if ($(this).valid()) {
FunctionToBeCalled(); //JS function
}
}
But FunctionToBeCalled() function gets called before the APIMethod(), but I want to run the FunctionToBeCalled() function after the response of APIMethod().
So I made the below changes by referring this link. But now the APIMethod is getting called twice.
$('#formID').submit(function (e) {
$.validator.unobtrusive.parse("form");
e.preventDefault();
if ($(this).valid()) {
//Some custom javasctipt valiadations
$.ajax({
url: $('#formID').attr('action'),
type: 'POST',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
}
}
function FunctionToBeCalled(){alert('hello');}
So I am not able to solve the issue.
If you want to execute some work on success, fail, etc. situation of form submission, then you would need to use Ajax call in your view. As you use ASP.NET MVC, you can try the following approach.
View:
$('form').submit(function (event) {
event.preventDefault();
var formdata = $('#demoForm').serialize();
//If you are uploading files, then you need to use "FormData" instead of "serialize()" method.
//var formdata = new FormData($('#demoForm').get(0));
$.ajax({
type: "POST",
url: "/DemoController/Save",
cache: false,
dataType: "json",
data: formdata,
/* If you are uploading files, then processData and contentType must be set to
false in order for FormData to work (otherwise comment out both of them) */
processData: false, //For posting uploaded files
contentType: false, //For posting uploaded files
//
//Callback Functions (for more information http://api.jquery.com/jquery.ajax/)
beforeSend: function () {
//e.g. show "Loading" indicator
},
error: function (response) {
$("#error_message").html(data);
},
success: function (data, textStatus, XMLHttpRequest) {
$('#result').html(data); //e.g. display message in a div
},
complete: function () {
//e.g. hide "Loading" indicator
},
});
});
Controller:
public JsonResult Save(DemoViewModel model)
{
//...code omitted for brevity
return Json(new { success = true, data = model, message = "Data saved successfully."
}
Update: If SubmitButton calls a JavaScript method or uses AJAX call, the validation should be made in this method instead of button click as shown below. Otherwise, the request is still sent to the Controller without validation.
function save(event) {
//Validate the form before sending the request to the Controller
if (!$("#formID").valid()) {
return false;
}
...
}
Update your function as follows.
$('#formID').submit(function (e) {
e.preventDefault();
try{
$.validator.unobtrusive.parse("form");
if ($(this).valid()) {
$.ajax({
url: $('#formID').attr('action'),
type: 'POST',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
}
}
catch(e){
console.log(e);
}
});
Check the browser console for fetching error. The above code will prevent of submitting the form.
I think line $.validator.unobtrusive.parse("form") were throwing error.
For that use you need to add the following jQuery libraries.
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script>
I think you should remove razor form tag if you want to post your form using ajax call and add post api URL directly to ajax request instead of getting it from your razor form tag using id:
Here is the revised version of your code :
<form method="post" id="formID">
<!-- Your form fields here -->
<button id="submit">Submit</button>
</form>
Submit your form on button click like:
$('#submit').on('click', function (evt) {
evt.preventDefault();
$.ajax({
url: "/Configuration/APIMethod",
type: 'POST',
dataType : 'json',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
});
function FunctionToBeCalled(){alert('hello');}
You need to use Ajax.BeginForm, this article should help [https://www.c-sharpcorner.com/article/asp-net-mvc-5-ajax-beginform-ajaxoptions-onsuccess-onfailure/ ]
The major thing here is that I didn't use a submit button, I used a link instead and handled the rest in the js file. This way, the form would nver be submitted if the js file is not on the page, and with this js file, it initiates a form submission by itself rather than th form submitting when the submit button is clicked
You can adapt this to your solution as see how it respond. I have somthing like this in production and it works fine.
(function() {
$(function() {
var _$pageSection = $('#ProccessProductId');
var _$formname = _$pageSection.find('form[name=productForm]');
_$formname.find('.buy-product').on('click', function(e) {
e.preventDefault();
if (!_$formname.valid()) {
return;
}
var formData = _$formname.serializeFormToObject();
//set busy animation
$.ajax({
url: 'https://..../', //_$formname.attr('action')
type: 'POST',
data: formData,
success: function(content) {
AnotherProcess(content.Id)
},
error: function(e) {
//notify user of error
}
}).always(function() {
// clear busy animation
});
});
function AnotherProcess(id) {
//Perform your operation
}
}
}
<div class="row" id="ProccessProductId">
#using (Html.BeginForm("APIMethod", "Configuration", FormMethod.Post, new { #class = "form-horizontal", name="productForm" id = "formID" })) {
<li class="buy-product">Save & Proceed</li>
}
</div>
Not sure what i am doing wrong here other than i am very weak in JQuery. The code in my onSwitchChange is not working. If i were to change it and put in alert("something"), it fires the alert, so i assume its in the ajax request. I have a breakpoint on my controller, but it never even hits the controller.
$(document).ready(function () {
$("[name='my-checkbox']" ).bootstrapSwitch({
onText: "Yes",
offText: "No",
onColor: "success",
offColor: "danger",
animate: false,
onSwitchChange: function (event, state) {
$ajax({
url: '/ProposalWork/ChangeActivityStatus/',
data: { id: #ViewBag.Activity.id, state: state }
}).done(function () { alert('Status Changed'); });
}
});
});
You missed a . in your ajax call.
$.ajax({
})
I am new to rails. Please help me as I do not have clear knoledge on usage of jquery and ajax in rails.
I am having a checkbox for tasks. I have a boolean field is_completed in my database which is set to false by default. when checkbox is checked the value of is_completed should be set to true and if unchecked it should be false.
migration for tasks table
t.boolean :is_completed, :default => false
my view code is
<%= check_box_tag :is_completed %>
in my task.js
$(':checkbox').change(function() {
if (this.checked) {
alert('completed')
/* is_completed should be true */
}
else {
/* is_completed should be true */
}
});
});
Please tell me how to do this.
try this:
$(':checkbox').click(function() {
var checked = $(':checkbox').prop('checked');
if (checked)
alert('yes');
else
alert('no');
});
Use jquery ajax:
$(':checkbox').change(function() {
$.ajax({
url: "/tasks/" + task_id,
data: "&task[is_completed]=" + this.checked,
dataType: "json",
type: "PUT"
});
});
I have created a method and passed the value from jquery and using ajax request got the things done.
In task.js
$(function () {
$(':checkbox').change(function () {
var task_id = jQuery('#task_id:hidden').val();
complete_task(task_id);
});
function complete_task(task_id) {
$.ajax({
type: "GET",
dataType: "html",
url: "/tasks/"+task_id+"/complete_task",
data: {"task_id": task_id},
success: function(data) {
$("#task_status").html(data);
}
});
}
});
in tasks_controller
def complete_task
#task =Task.find(params[:task_id])
#task.is_completed = true
#task.save
render :partial => 'task'
end