Preventing refresh upon AJAX request - javascript

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() )

Related

Failed to refresh a div when submit a form

I'm trying to refresh a div when submiting a form, but I'm having a 404 error
jquery.min.js:2 POST Https://xxxx.com.ar/Home/#Url.Action(%22Pagination2%22,%22Home%22) 404 (Not Found)
This is my form:
<form action="~/Home/Pagination" method="post" id="ajax_submit_siguiente">
<button class="siguiente-imagen #ViewData["btnSiguiente"]" id="btnSiguientePaginacion" value="#item.getNumeroEntrega()" type="submit">
Siguiente
</button>
</form>
And this is my js:
$(document).ready(function () {
$("#ajax_submit_siguiente").submit(function (e) {
// prevent regular form submit
e.preventDefault();
var data = {
'paginacion': 'siguiente',
'entrega': $("#btnSiguientePaginacion").val()
}
$.ajax({
url: '#Url.Action("Pagination","Home")',
type: 'POST',
data: data,
success: function (result) {
console.log(result);
// refresh
$(" #container-galeria-imagenes").load(window.location.href + " #container-galeria-imagenes ");
},
error: function (err) {
console.log(err);
}
});
})
});
And this is my JsonResult...
[HttpPost]
public async Task<JsonResult> Pagination(string paginacion, string entrega)
{
List<PedidoViewModel> list;
// Working code....
return Json(list);
}
I'm very new with ajax, I read the documentation and was like this how to refresh a div after sending a submit...
since its a form submit rather than creating the object serialize the form and pass it to the server. also just to double confirm check the conversion of '#Url.Action("Pagination","Home")'is correct using the browser debugger tool and also make sure the routing is implemented correctly in Server side
$(document).ready(function() {
$('#myForm').submit(function(event) {
event.preventDefault(); // prevent the form from submitting normally
$.ajax({
type: 'POST',
url: '/my/url',
data: $('#myForm').serialize(),
success: function(response) {
$('#myDiv').html(response); // update the content of the div with the response
}
});
});
});

How to prevent a page from refreshing when I want to submit a form?

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>

Why is the raw JSON object getting returned instead of my partial view?

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.

Do HTML affect ajax calls

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;
});

Submit checkbox state without a submit button

I have a view with a few checkboxes that can be selected or unselected. I'd like to always register any change in a checkbox, without the use of a submit button (the user could forget to do it, and it would waste time).
So, is there a way to handle this inside the view? Up to now, I've only used the controller to do that job.
So, a piece of code :
#ModelType MvcApplication.OpportuniteDetails
#Code
ViewData("Title")="Details"
#End Code
<script type="text/javascript">
$(function () {
$(':checkbox').change(function() {
$.ajax({
url: '#Url.Action("update")',
type: 'POST',
data: { isChecked: $(this).is(':checked') },
success: function (result) { }
});
});
});
</script>
[... Some code here...]
#Html.Raw("Mail sent?") #Html.CheckBox(Model.Opportunite.Mail)
<input type="checkbox" name="mail" id="mail" onclick="test()" />
You could use AJAX:
$(function() {
$(':checkbox').change(function() {
var form = $(this).closest('form');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(result) {
}
});
});
});
In this example we subscribe to the change event of each checkbox. When this event is trigerred we look for the containing form and send its contents to the server using an AJAX request.
And if you only wanted to submit the current checkbox state to the server and not the entire form:
$(function() {
$(':checkbox').change(function() {
$.ajax({
url: '#Url.Action("SomeAction")',
type: 'POST',
data: { isChecked: $(this).is(':checked') },
success: function(result) {
}
});
});
});
where you could have a controller action which will do the necessary processing:
[HttpPost]
public ActionResult SomeAction(bool isChecked)
{
...
}
If you don't need or want AJAX and just want to submit the form, this
$(':checkbox').change(function() {
var form = $(this).closest('form');
form.get( 0 ).submit();
});
would do it.

Categories