jQuery and Ajax on Form submit - parse POST data - javascript

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".

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

jQuery Ajax submitting form multiple times

I am new to Ajax. I am currently submitting a form into my database using jQuery AJAX but it sends the same data multiple times in my database.
Here's my Ajax code :
$(document).ready(function () {
var id_js;
$(document).on('click', '.btn-success', function () {
id_js = $('#ID_TXT').val();
$('form').submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function (response) {
$('#result').html(response);
}
});
return false;
});
});
});
Also I have tried .one() and .stopImmediatePropogation() but still no results
I see both form submit and Ajax call are doing the same work. If you are going to post the data only with AJAX call then form submit is not required.
I hope this works well for you.
$(document).ready(function () {
function postDataToServer() {
var id_js = $('#ID_TXT').val();
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function (response) {
$('#result').html(response);
}
});
}
$(document).on('click', '.btn-success', postDataToServer);
});
The submit handler shouldn't be inside the click handler. Every time you click on the button, it adds another submit handler. So when you finally submit the form, it will submit it as many times as you clicked on the button.
If you want to ensure that the form isn't submitted until you've clicked on the button, add a test in the submit handler.
$(document).ready(function() {
var id_js;
$(document).on('click', '.btn-success', function() {
id_js = $('#ID_TXT').val();
});
$('form').submit(function(e) {
if (id_js !== undefined) {
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function(response) {
$('#result').html(response);
}
});
} else {
alert("You need to click on the success button first");
}
return false;
});
});

How to get a value from Ajax call to be used in a Bootbox button's function?

I am using Bootbox for my modals and I am having trouble in showing the form validation errors from an Ajax call to the modal. The callback function for the submit button on my modal calls the add_college function to submit the form via Ajax.
When there are validation errors, the modal is populated with validation errors. The problem is that the modal closes regardless if there are validation errors or not. I want the modal to not close only when there are no validation errors.
I know I can just return false in the callback function on my button when there are validation errors to not close it but I have no way of knowing if there are validation errors since I cannot return a value in the Ajax call since it is asynchronous. What is the proper way of doing it?
Here is my code:
$('#new-college-btn').click(function () {
bootbox.dialog({
title: "New College",
message:
''// <Insert long HTML form here>
,
buttons: {
add: {
label: "Add",
className: "btn btn-primary",
callback: function () {
var form_data = {
college_name: $('#college-name').val(),
college_initials: $('#college-initials').val(),
username: $('#username').val(),
password: $('#password').val(),
confirmation_password: $('#confirmation-password').val()
};
add_college(form_data);
}
},
cancel: {
label: "Cancel",
className: "btn btn-default"
}
}
}); // end bootbox dialog
});
function add_college(form_data) {
console.log(form_data);
$.ajax({
url: 'admin/add_new_college',
type: 'POST',
data: form_data,
dataType: 'JSON',
success: function (response)
{
if (response.error) { // there are form validation errors
// populate modal with validation errors here
} else {
// other data processing here
Result.success('College Successfully Added!');
}
},
error: function () {
console.log("fail");
}
});
}
If you want to control when the dialog closes, make sure the callback for your "submit" button always returns false. Then, in the done() (and probably fail()) callbacks for the ajax function, call bootbox.hideAll() to close the dialog (along with any other dialogs you may have opened).
If you want to only close the current dialog, do something along this line:
var dialog = bootbox.dialog({
/* rest of your options... */,
buttons: {
submit: {
label: "Submit",
callback: function() {
var data = [];
$.post('/url', data)
.done(function(result, status, jqxhr){
// if everything went well...
dialog.modal('hide');
})
.fail(function(jqxhr, status, error){
// etc.
});
return false;
}
}
}
});
Basically, create a reference to the dialog, which you can then use inside of the ajax callback.

Why doesn't the browser render a response from the controller?

When an POST is made to the controller, the controller responds with exactly what I want the browser to render. But the browser does not render the response. I've verified the response is good in Fiddler.
The code below shows what I think is relavent code. The controller action method that returns the response, part of the template that has the mvc helper code, javascript/jquery code that fires the ajax call with the form inputs.
I want to use the FormCollection. Why doesn't the browser render the response and what can I do to fix it?
BoMController
public ActionResult GetBillOfMaterialsView(FormCollection frmColl){
// snipped out model interaction
return PartialView("~/Views/Project/Index.cshtml", project);
}
Index.cshtml
#using (Html.BeginForm("GetBillOfMaterialsView", "BoM", FormMethod.Post, new {id = "frmGetBom"})) {
// selProj input select code removed for brevity
}
function submitGetBoM() {
var frmGetBom = $('#frmGetBom');
$.ajax({
type: 'POST',
url: frmGetBom.attr('action'),
data: frmGetBom.serialize()
});
}
$(document).ready(function() {
$('#selProj').selectmenu( {
select: function(){submitGetBoM()}
}).addClass("overflow");
});
Invoking $.ajax alone doesn't append the response from the server to the document, you have to use the success callback to manually fetch the response and append it.
For example:
$.ajax({
type: 'POST',
url: frmGetBom.attr('action'),
data: frmGetBom.serialize(),
success: function(response) {
$('#someContainerId').html(response);
}
});
Alternatively, use load() that is a shorthand to the above:
$('#someContainerId').load(frmGetBom.attr('action'), frmGetBom.serializeArray());
See Documentation
Your client code doesn't do anything with the returned values from the server:
function submitGetBoM() {
var frmGetBom = $('#frmGetBom');
$.ajax({
type: 'POST',
url: frmGetBom.attr('action'),
data: frmGetBom.serialize(),
success: function() { alert('ok'); }
});
}
This would popup an alert on success.

New Javascript being loaded but old Javascript being called. MVC

I have 3 partial views with JS using JQuery in each to post a form and open a new partial view when the form is posted.
What I am finding is that the first time the JS fires it works fine but if I then go to post the form on the new page, I calls the function from the previous page.
The code:
$('#selector').click(function (e) {
var actionName = $(this).attr("id")
e.preventDefault();
e.stopImmediatePropagation();
alert("page1 js being called")
$('#page1Form').submit(function () {
$.ajax({
url: 'Dashboard/Page1/',
data: $(this).serialize(),
type: 'POST',
success: function () {
$.ajax({
url: 'Dashboard/LoadPartial',
data: { viewName: actionName },
type: 'GET',
success: function (d) {
$('#partial').html(d);
}
});
},
});
});
$('#page1Form').submit();
});
The second partial view has a function the same as that but only with the relevant selectors etc and for some reason the previous pages JS is being called as the alert alert("page1 js being called") is appearing in the browser!
Thanks in advance.
If you're loading partial views that means the entire page isn't being refreshed, and as a result the already loaded scripts will still be there. You'll need to remove the event handlers that correspond to the page1 content before adding the new content in:
$.ajax({
url: 'Dashboard/LoadPartial',
data: {
viewName: actionName
},
type: 'GET',
success: function (d) {
$('#selector').off('click'); // remove the click event handler
$('#page1Form').off('submit'); // remove the submit event handler
$('#partial').html(d); // add your new content
}
});

Categories