I've created two forms and assigned different submit button IDs. But ajax is executing single form every time even if I execute different button for different ajax call. Following is the code:
Form1.
<button class='btn genz-light-red'type='submit'
style="margin-top:20px;width:50%; background:#FF1744; height:33px;color:white;" id="customButton">Enroll</button>
</div>
</form>
<script src="https://checkout.stripe.com/checkout.js"></script>
<script type="text/javascript">
var handler = StripeCheckout.configure({
key: 'pk_test_YgHVTCLIMQLW4NV6ntnJPAXs',
image: '/assets/img/icons/GenZ_Logo.png',
locale: 'auto',
token: function (token) {
$("#stripeToken").val(token.id);
$("#stripeEmail").val(token.email);
$("#monthlyForm").submit();
$.ajax({
url: '/monthlycharged',
data: $('form').serialize(),
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
}
});
$('#customButton').on('click', function (e) {
handler.open({
name:'Monthly',
description:'Monthly Package',
amount:1450
});
e.preventDefault();
});
$(window).on('popstate', function () {
handler.close();
});
</script>
Form2:
<form action='/cancelannual' method='post'><a href="/cancelannual">
<input class='btn genz-light-red'style=";width:50%; background:#FF1744; height:33px;color:white;"type="submit" value="Cancel" /></a></form>
<!-- Custom Button -->
<form id="yearlyForm" action="/yearlycharged" method="post" >
<div class="form-group">
<input type="hidden" id="stripeToken" name="stripeToken" />
<input type="hidden" id="stripeEmail" name="stripeEmail" />
<button class='btn genz-light-red'type='submit'
style="margin-top:20px;width:50%; background:#FF1744; height:33px;color:white;" id="customButton1">Enroll</button>
</div>
</form>
<script src="https://checkout.stripe.com/checkout.js"></script>
<script type="text/javascript">
var handler = StripeCheckout.configure({
key: 'pk_test_YgHVTCLIMQLW4NV6ntnJPAXs',
image: '/assets/img/icons/GenZ_Logo.png',
locale: 'auto',
token: function (token) {
$("#stripeToken").val(token.id);
$("#stripeEmail").val(token.email);
$("#yearlyForm").submit();
$.ajax({
url: '/yearlycharged',
data: $('form').serialize(),
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
}
});
$('#customButton1').on('click', function (e) {
handler.open({
name:'Yearly',
description:'Yearly Package',
amount:9500
});
e.preventDefault();
});
// Close Checkout on page navigation
$(window).on('popstate', function () {
handler.close();
});
</script>
If I click on "customButton" it processes yearly subscription if I click on "customButton1" still it processes yearly subscription instead of monthly. Surprisingly when form popups it has the monthly values in it. But after processing database shows Yearly package processed. In my python/flask code without ajax I can process both packages seperately so the problem is not in my views it lies somewhere in Ajax. Please advise
You have two var handler declarations in the global scope - the second hides the first. Name them differently or wrap both code fragments in separate $(document).ready(function() {...});
Related
I am trying to build my first website and I encountered a problem that I couldn't resolve by now. So, when an user wants to add an item to the cart, or to increment the quantity, I want to prevent the page from refreshing when hitting the submit button. I've looked for many answers, I tried to apply Ajax/JQuery, but unsuccessful.
Here is my code:
html
<form action="{% url 'cart-add' %}" method="GET" id="myform">
{% csrf_token %}
<label>
<input type="hidden" name="{{ product.pk }}">
<input type="number" max="{{ product.quantity }}" min="1" name="quantity" value="1">
<button type="submit" value="">Add to chart</button>
</label>
</form>
Ajax/JQuery script
<script type="text/javascript">
$(document).ready(function () {
$('myform').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "GET",
data: $(this).serialize(),
success: function (data) {
$("myForm").html(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
</script>
When I hit add-to-cart submit button, it throw me to the "cart.html". I do not want to do that, instead I want to prevent that and throw a message to the user saying that his/her item has been successfully added.
Can somebody help me? Thank you very much for your time. I much appreciate it!
You need to return false, otherwise, the function with carry on with the default behaviour after the function is complete:
<script type="text/javascript">
$(document).ready(function () {
$('#myform').on('submit', function(e) { // fix typo
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "GET",
data: $(this).serialize(),
success: function (data) {
$("myForm").html(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
// Prevent function from saving
return false;
});
});
</script>
Update: looking at the jQuery documentation, I don't know if return false is necessary if e.preventDefault() is present.
Is $('myform') a typo? Should it be $('#myform')?
To reference a HTML's ID, use a #idName.
To reference a HTML class, use a .className
To reference a HTML element, just enter name
$('myform') is looking for a <myform></myform> element.
$('#myform') is looking for a <... id="myform"></...>
$('.myform') is looking for a <... class="myform anotherRandomClass"></...>
Your form is submitting normally because your jquery selector is wrong. You have to change $('myform') to $('#myform')
<script type="text/javascript">
$(document).ready(function () {
$('#myform').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "GET",
data: $(this).serialize(),
success: function (data) {
$("#myform").html(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
</script>
When I submit my form, the page gets redirected to a new window with the raw json object instead of showing the alerts that I have set up for testing. I'm guessing that it has something to do with returning a Json result from the controller, but I'm not experienced enough with ajax or json to know why this is happening.
Partial View (named _FooterButtons)
<div class="row col-12">
<div class="col-12 footerbuttons">
<button type="button" onclick="submit()" id="submit-form" class="btn btn-primary" value="Print" style="display: inline-block">Print</button>
<input type="button" class="btn btn-secondary" value="Cancel" />
</div>
</div>
Main View
#using (Html.BeginForm("Daily", "Reports", FormMethod.Post, new { id = "reportForm", #class = "report-form col-9" }))
{
...
<partial name="../Shared/_FooterButtons" />
}
JavaScript
$(document).ready(function () {
$("#startdatepicker").datepicker();
$("#enddatepicker").datepicker();
// Add the listener only when everything is loaded
window.onload = function () {
// Get the form
let rform = document.getElementById('reportForm');
console.log(rform);
// Add the listener
rform.addEventListener('submit', function (e) {
// Avoid normal form process, so no page refresh
// You'll receive and process JSON here, instead of on a blank page
e.preventDefault();
// Include here your AJAX submit:
console.log("Form submitted");
$.ajax({
type: 'POST',
data: $('#reportForm').serialize(),
url: '#Url.Action("Daily","Reports")',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.success) {
alert("Data Success");
} else {
alert("Data Fail");
$('#errorsModal').modal('toggle');
$('#errorsModal .modal-body label').html(data.message);
}
}
});
});
};
});
Controller
[HttpPost]
public IActionResult Daily(Daily dailyReport)
{
var dr = new ReportDaily();
var rc = new ReportDailyCriteria();
dr.Preview(rc, IntPtr.Zero, out Notification notification);
//dr.CreateReportAsPDF(ReportCriteria(), #"C:/");
if (notification.HasErrors)
{
return Json(new
{
success = false,
message = notification.GetConcatenatedErrorMessage(Environment.NewLine + Environment.NewLine)
});
}
return Json(new { success = true });
}
Json object that gets returned in a new window
{"success":false,"message":"Must select a payment Source, County and/or Municipal.\r\n\r\nMust select at least one payment type.\r\n\r\nMust select at least one user.\r\n\r\n"}
You need to avoid the normal form process and you have 2 options:
First: Add return false to onclick event.
<button type="button" onclick="submit(); return false" id="submit-form" class="btn btn-primary" value="Print" style="display: inline-block">Print</button>
This first option will be executed only if button is clicked, but maybe not if ENTER key is pressed while typing on an input.
Second and better option: Add an event listener to your form:
<script>
// Add the listener only when everything is loaded
window.onload = function() {
// Get the form
let rform = document.getElementById('reportForm');
// Add the listener
rform.addEventListener('submit', function(e) {
// Avoid normal form process, so no page refresh
// You'll receive and process JSON here, instead of on a blank page
e.preventDefault();
// Include here your AJAX submit:
console.log("Form submitted");
$.ajax({
type: 'POST',
data: $('#reportForm').serialize(),
url: '#Url.Action("Daily","Reports")',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.success) {
alert("Data Success");
} else {
alert("Data Fail");
$('#errorsModal').modal('toggle');
$('#errorsModal .modal-body label').html(data.message);
}
}
});
});
};
</script>
Edit: Since you're using jQuery .ready(), things are a bit different:
$(document).ready(function () {
$("#startdatepicker").datepicker();
$("#enddatepicker").datepicker();
// Not really sure if window.onload inside .ready() was the problem,
// but it could be
// Get the form and add the listener
$("#reportForm").on('submit', function (e) {
// Avoid normal form process, so no page refresh
// You'll receive and process JSON here, instead of on a blank page
e.preventDefault();
console.log("Form submitted");
$.ajax({
type: 'POST',
data: $('#reportForm').serialize(),
url: '#Url.Action("Daily","Reports")',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.success) {
alert("Data Success");
} else {
alert("Data Fail");
$('#errorsModal').modal('toggle');
$('#errorsModal .modal-body label').html(data.message);
}
}
});
});
});
I used a method similar to what Triby has suggested, but instead of adding an event listener on the form submit, I added one onto the submit button click.
The following code is working fine when the form is submitted correctly with all valid data in the first attempt. If there is any server side error after submitting the form then when user resubmits the form the recaptcha does not reset.
Following is the sample code:
html-form
<script src="https://www.google.com/recaptcha/api.js"></script>
<div>
<form name="signupForm" method="POST" action="/signup">
<div class="form-group mobile-number">
<input type="tel" id="mobileNo" class="form-control" name="mobileNumber" maxlength="10"
autofocus>
<label for="mobile"> Your Mobile no. </label>
</div>
<div class="g-recaptcha"
data-sitekey="{key}"
data-callback="setResponse"
data-badge="inline"
data-size="invisible">
</div>
<input type="hidden" id="captcha-response" name="captcha-response"/>
<button id="submitButon" type="submit">Sign me up!</button>
</form>
</div>
javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
function setResponse(response) {
document.getElementById('captcha-response').value = response;
submitForm();
}
function submitForm() {
var $form = $("form");
var data = JSON.stringify($form.serializeObject());
var myJsonObject = JSON.parse(data);
data = JSON.stringify(myJsonObject);
$.ajax({
type: "POST",
url: "dummy url",
contentType: "application/json",
xhrFields: {withCredentials: true},
data: data,
success: function (data, textStatus, request) {
// success
},
error: function (xhr, err) {
// logics here
grecaptcha.execute();
setResponse;
}
});
}
</script>
<script>
jQuery(document).ready(function () {
//homepage form
$('form[name="signupForm"]').validate({
onfocusout: function (element) {
$(element).valid();
},
rules: {
mobileNumber: {
required: true,
minlength: 10,
maxlength: 10
}
},
// Specify validation error messages
messages: {
mobileNumber: "A valid mobile number is of 10-digit",
},
//submit handler
submitHandler: function (form) {
submitForm();
}
});
});
</script>
I think the error is in ajax call but not able to figure out why the captcha is not resetting again.
I have a form in my code, and I would simply like to display the fields from that form on my webpage, using AJAX. I tried e.preventDefault() and return false but none of these seem to be working.
I trigger the submit through a button click event.
My Jquery code:
$("body").on('click', '#save', function (e) {//button which triggers submit
$('form').submit();
e.preventDefault();
});
$('#form').on('submit', function(e){
e.preventDefault();
e.stopPropagation();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: '/results',
data: $('#form').serializeArray(),
success: function (data) {
//if no error from backend validation is thrown
return false;
$('#tabShow').html(data);
},
error: function () {
alert('error');
}
});
My form html is : <form class="form-horizontal" method="POST" action="/results" id="form">
In my web.php:
Route::post('/results', function() {
$m=Request::all();
var_dump($m);
});
The problem with this code is that it refreshes the current page that I am on.
I have a save button, which should submit the form. I can't use a type submit because of my other functions.
Thank you for the help.
Do the request in the Save button click event, eg.
HTML
<form id="contact-form" class="form-horizontal" action="/echo/html/" method="post">
<!-- many fields -->
<button id="save" class="btn btn-primary btn-lg">Submit</button>
</form>
JS
$("body").on('click', '#save', function (e) {//button which triggers
var contactForm = $('#contact-form');
e.preventDefault();
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-TOKEN', $('meta[name="csrf-token"]').attr('content'));
}
});
// Send a POST AJAX request to the URL of form's action
$.ajax({
type: "POST",
url: contactForm.attr('action'),
data: contactForm.serialize()
})
.done(function(response) {
console.log(response);
})
.fail(function(response) {
console.log(response);
});
});
Working demo
Try using return false at the end of your script (also remove preventDefault() )
I was making Wikipedia viewer, and I implemented Wikipedia title search ajax calls were working fine until I added forms tag around input & button tag.
<form class="pure-form">
<input type="text" id="txtff" class="pure-input-rounded" placeholder="Search for...">
<button type="submit" class="pure-button"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button>
</form>
My ajax code is:
$("button").click(function() {
var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&list=allpages&aplimit=5&apfrom=Albert";
$.ajax({
url: url,
jsonp: "callback",
dataType: "jsonp",
success: function(resp){
console.log(JSON.stringify(resp));
},
error: function(err){
console.log("ERR")
}
});
});
I was doing all this on codepen: http://codepen.io/theami_mj/pen/KMKPvZ
Use type='button', type='submit' will submit the form and page will be unloaded.
$("button").click(function() {
var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&list=allpages&aplimit=5&apfrom=Albert";
$.ajax({
url: url,
jsonp: "callback",
dataType: "jsonp",
success: function(resp) {
console.log(JSON.stringify(resp));
},
error: function(err) {
console.log("ERR")
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form class="pure-form">
<input type="text" id="txtff" class="pure-input-rounded" placeholder="Search for...">
<button type="button" class="pure-button"><span class="glyphicon glyphicon-search" aria-hidden="true"></span>Go!
</button>
</form>
I feel the problem was with form submission with submit button type added. Just add one line of code i.e. e.preventDefault() to prevent default action of your button which is submitting the form, so that it would not submit the form
$("button").click(function(e) {
e.preventDefault()
var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&list=allpages&aplimit=5&apfrom=Manoj";
$.ajax({
url: url,
jsonp: "callback",
dataType: "jsonp",
success: function(resp) {
console.log(JSON.stringify(resp));
},
error: function(err) {
console.log("ERR")
}
});
});
UPDATED FIDDLE
You should attach you click handler / AJAX call to the form's onsubmit event handler:
<form class="pure-form" onsubmit="myAjaxCall">
<input type="text" id="txtff" class="pure-input-rounded" placeholder="Search for...">
<button type="submit" class="pure-button"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button>
</form>
This would be your script (just created a function called myAjaxCall instead of attaching a click event handler).
myAjaxCall = function() {
var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&list=allpages&aplimit=5&apfrom=Albert";
$.ajax({
url: url,
jsonp: "callback",
dataType: "jsonp",
success: function(resp){
console.log(JSON.stringify(resp));
},
error: function(err){
console.log("ERR")
}
});
}
http://www.w3schools.com/jsref/event_onsubmit.asp
This is normal behavior. button with type submit will send the form. Try to just replace type="submit" with type="button".
You should get rid of the form, or you should add
$("form").on("submit", function(e){
e.preventDefault();
return false;
});
To your JS code, to prevent the default behaviour of the form.
Alternatively, you could move all the logic from your button click event here, too:
$("form").on("submit", function(e){
e.preventDefault();
// your AJAX call here
return false;
});