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
}
});
});
});
Related
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.
I'm trying to prevent the submit button depending of the result of an ajax call. I tried this:
<button type="submit" id="update" class="btn btn-success">Update</button>
and JS
$('#update').click(function (event) {
event.preventDefault();
const profiles = $('select#profiles').val();
const self = this;
$.ajax({
url: '/getDemosByProfiles',
method: 'POST',
data: {
profiles: profiles,
}
}).done(function (data) {
if(data.status == "success") {
self.submit();
} else {
event.preventDefault();
// show some message
}
}).fail(function() {
$.growl.error({ title: 'Error', message: 'Error'});
});
})
But I'mk getting a "Uncaught TypeError: self.submit is not a function".
What I'm doing wrong?
You are referencing the button, not the form. You need to reference the form.
self.form.submit();
This is because button element has no method named submit().
You want to use submit() method on the form element like this:
document.querySelector("formSelector").submit()
where formSelector is the id, class or tag name of the form element.
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() )
First of all, I have to say that I'm beginner with using Ajax... So help me guys.
I want to insert the data into db without refreshing the page. So far, I have following code...
In blade I have a form with an id:
{!! Form::open(['url' => 'addFavorites', 'id' => 'ajax']) !!}
<img align="right" src="{{ asset('/img/icon_add_fav.png')}}">
<input type="hidden" name = "idUser" id="idUser" value="{{Auth::user()->id}}">
<input type="hidden" name = "idArticle" id="idArticle" value="{{$docinfo['attrs']['sid']}}">
<input type="submit" id="test" value="Ok">
{!! Form::close() !!}
And in controller I have:
public function addFavorites()
{
$idUser = Input::get('idUser');
$idArticle = Input::get('idArticle');
$favorite = new Favorite;
$favorite->idUser = $idUser;
$favorite->idArticle = $idArticle;
$favorite->save();
if ($favorite) {
return response()->json([
'status' => 'success',
'idUser' => $idUser,
'idArticle' => $idArticle]);
} else {
return response()->json([
'status' => 'error']);
}
}
I'm trying with ajax to insert into database:
$('#ajax').submit(function(event){
event.preventDefault();
$.ajax({
type:"post",
url:"{{ url('addFavorites') }}",
dataType="json",
data:$('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
}
error: function(data){
alert("Error")
}
});
});
Also in my web.php I have a route for adding favorites. But when I submit the form, it returns me JSON response like this: {"status":"success","idUser":"15","idArticle":"343970"}... It actually inserts into the db, but I want the page not to reload. Just to display alert box.
As #sujivasagam says it's performing a regular post action. Try to replace your javascript with this. I also recognized some syntax error but it is corrected here.
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
You could just replace <input type="submit"> with <button>instead and you'll probably won't be needing event.preventDefault() which prevents the form from posting.
EDIT
Here's an example of getting and posting just with javascript as asked for in comments.
(function() {
// Loads items into html
var pushItemsToList = function(items) {
var items = [];
$.each(items.data, function(i, item) {
items.push('<li>'+item.title+'</li>');
});
$('#the-ul-id').append(items.join(''));
}
// Fetching items
var fetchItems = function() {
$.ajax({
type: "GET",
url: "/items",
success: function(items) {
pushItemsToList(items);
},
error: function(error) {
alert("Error fetching items: " + error);
}
});
}
// Click event, adding item to favorites
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
// Load items (or whatever) when DOM's loaded
$(document).ready(function() {
fetchItems();
});
})();
You are using button type "Submit" which usually submit the form. So make that as button and on click of that call the ajax function
Change your button type to type="button" and add onclick action onclick="yourfunction()". and just put ajax inside your funciton.
Replace input type with button and make onClick listener. Make sure you use this input id in onclick listener:
So:
$('#test').on('click', function(event){
event.preventDefault()
... further code
I would also change the id to something clearer.
I have the following ajax jQuery code that on document.ready function downloads a file from ajaxFileDownload.php.
However, I would like it to instead of document.ready function use on submit of a form called reports. So when i click submit on my form name report, then it runs this, I would also like to parse the form field post variable called user_id to the php file.
Any ideas how this can be done?
I added: $('#reports').on('submit', function(e) {
How can I add the user_id post variable?
$(function () {
$('#reports').on('submit', function(e) {
var $preparingFileModal = $("#preparing-file-modal");
$preparingFileModal.dialog({
modal: true
});
$.fileDownload('ajaxFileDownloader.php?' + Math.random(), {
successCallback: function (url) {
$preparingFileModal.dialog('close');
},
failCallback: function (responseHtml, url) {
$preparingFileModal.dialog('close');
$("#error-modal").dialog({
modal: true
});
}
});
return false; //this is critical to stop the click event which will trigger a normal file download!
});
});
Try adding these two lines inside the $.fileDownload block:
httpMethod: 'POST',
data: $(this).serialize()
like so:
$.fileDownload('ajaxFileDownloader.php?' + Math.random(), {
httpMethod: 'POST',
data: $(this).serialize(),
successCallback: function (url) {
$preparingFileModal.dialog('close');
},
failCallback: function (responseHtml, url) {
$preparingFileModal.dialog('close');
$("#error-modal").dialog({
modal: true
});
}
});
That should send all form data to the PHP script.
If you want to send just the one field, you could use $('#user_id') in place of $(this) assuming the field in question has id="user_id".