jquery datatables fnAddData from dialog form ajax not working - ajax

I have a datatable defined at document ready as follows
$(document).ready(function() {
var oTable = $('#systemgoals').dataTable({});
I have a dialog with form and a button with the following function
buttons: {
"Add System Goal": function() {
var formfilled = true;
$("form#add_systemgoal :text, form#add_systemgoal :file, form#add_systemgoal :checkbox, form#add_systemgoal select, form#add_systemgoal textarea").each(function() {
if($(this).val() === "")
formfilled = false;
});
if(formfilled === true){
$('form#add_systemgoal .error').remove();
var formdata = $('form#add_systemgoal').serialize();
$.ajaxSetup({async: false});
$.ajax({
type: "POST",
url: '/admin/systemgoals/systemgoalupdate?format=html',
data: formdata,
success: function (data) {
var obj = $.parseJSON(data);
if(obj.success){
$(oTable).dataTable().fnAddData( [
obj.inserted.goal_id,
obj.inserted.value,
obj.inserted.status,
obj.inserted.points_per_action,
obj.inserted.created,
obj.inserted.due,
obj.inserted.expires ]);
}
}
});
}
the ajax is fine the form posts the correct values respond but the fnAddData returns error
ReferenceError: oTable is not defined
Any advice appreciated
thank you

You didn't set your oTable as a global variable that why oTable on your dialog is not define, if you want to define it on your script do something like:
var oTable;
$(document).ready(function() {
oTable = $('#systemgoals').dataTable({});
And on your dialog
oTable.fnAddData( [
obj.inserted.goal_id,
obj.inserted.value,
obj.inserted.status,
obj.inserted.points_per_action,
obj.inserted.created,
obj.inserted.due,
obj.inserted.expires ]);
}
or just simply do
var oTable = $('#systemgoals').dataTable().fnAddData...
Best Regards

Related

How to use SweetAlert success with OK button?

I have created a SweetAlert using the code below. After I used this, the result was shown BUT I am not pressing OK yet, already jumped to URL that I set.
This is a SweetAlert script I created (I save in my script when I want to use then I take it from because I'm using Laravel framework).
<script type="text/javascript">
function showSuccessSwal(message) {
Swal.fire(
'Success',
message,
"success"
);
}
function showErrorSwal(message) {
Swal.fire(
'Error',
message,
"error"
);
}
</script>
And this is a script I'm using:
<script type="text/javascript">
$('#somthing-form').submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: 'POST', // GET, POST, PUT
url: form.attr('action'),
data: form.serialize(),
success: function(result) {
showSuccessSwal(result.message);
window.location.href="{{ route('something.index') }}";
},
error: function(xhr) {
var errorString = '';
var errors = xhr.responseJSON.errors;
Object.keys(errors).forEach(function(key) {
var error_message = errors[key];
$.each(error_message, function(key, value) {
errorString += value + '\n';
});
});
showErrorSwal(errorString);
}
});
});
</script>
I want the result to work like this:
I press a submit button.
Display a SweetAlert with an OK button.
Wait for the user to press the OK button then go to the URL I set (not straight jump to URL before I press OK button).
you need to call the swal before you call the ajax
swal({
title: 'Are you sure to go ahead?,
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, please!'
}).then(function(result) {
if (result.value) { // when you click `yes, please!`
$.ajax({
type: 'POST', // GET, POST, PUT
url: form.attr('action'),
data: form.serialize(),
success: function(result) {
showSuccessSwal(result.message);
window.location.href="{{ route('something.index') }}";
},
error: function(xhr) {
var errorString = '';
var errors = xhr.responseJSON.errors;
Object.keys(errors).forEach(function(key) {
var error_message = errors[key];
$.each(error_message, function(key, value) {
errorString += value + '\n';
});
});
showErrorSwal(errorString);
});
}
});

Sending data to controller using Ajax

I have a form that contains different fields for user to fill in and also allow user to attach image. Below is my code to send data to the controller, I can see the image in my controller but I am not sure how to access rest of form data in controller:
$(function () {
var ajaxFormSubmit = function () {
var $form = $(this);
var data = new FormData();
var files = $("#File").get(0).files;
if (files.length > 0) { data.append("File", files[0]); }
else {
common.showNotification('warning', 'Please select file to upload.', 'top', 'right');
return false;
}
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: data,
processData: false,
dataType: "html",
contentType: false
};
$.ajax(options).done(function (data) {
$('#ProdList').html(data);
});
return false;
};
$("form[data-ajax='true']").submit(ajaxFormSubmit);
});
My controller :
public ActionResult Create(PostViewProduct postProduct)
{
//code......
}
PostViewProduct model shows only image fields with data rest showing null:
Do I have to add each field using formdata.append() or is there better way to send all the data to controller and then access the data in controller.
Thanks
Try this:
var data = new FormData($(this)[0]);
instead of var data = new FormData();
Try following, this will put the data in right format if all input is within the form.
data = $form.serialize();
You basically need to send the files in FormData along with other form element data.
$(function () {
var ajaxFormSubmit = function () {
var fdata = new FormData();
$('input[name="Image"]').each(function (a, b) {
var fileInput = $('input[name="Image"]')[a];
if (fileInput.files.length > 0) {
var file = fileInput.files[0];
fdata.append("Image", file);
}
});
// You can update the jquery selector to use a css class if you want
$("input[type='text'").each(function (x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
var frmUrl = $(this).attr('action');
$.ajax({
type: 'post',
url: frmUrl,
data: fdata,
processData: false,
contentType: false,
success: function (e) {
console.log(e);
}
});
return false;
};
$("form[data-ajax='true']").submit(ajaxFormSubmit);
});
Assuming your view model has a property called Image of type HttpPostedFileBase for accepting the posted file and your form has an input for that
public class YourViewModel
{
public HttpPostedFileBase Image { set;get;}
//Your other existing properties
}
and your form has an file input tag with name "Image".
<input type="file" name="Image" />

Jquery ready function with click and ajaxForm calls

I m really new working with JQuery and I have an error in my code. The next piece of code was working perfect when a user click a "Button", it load a file in a content div.
$(document).ready(function() {
$('.Button').click(function() {
var href = $(this).attr('href');
if( typeof href != "undefined" && href != ""){
$.ajax({
url: href,
dataType: 'text',
success: function(data) {
$('#content').html(data);
ultXML = href;
}
});
}
});
});
But now I m trying to use JQuery Form plugin (with this example http://www.malsup.com/jquery/form/) And it doesnt work (the ajaxForm call), I cant understand how to merge the next code in my orignal code. I try many ways, for example making 2 ready function but it also doesnt work,
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
Where I must put the next piece of code in my original ready function? How can meger both?
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
Like this, work?
$(document).ready(function() {
$('.Button').click(function() {
var href = $(this).attr('href');
if( typeof href != "undefined" && href != ""){
$.ajax({
url: href,
dataType: 'text',
success: function(data) {
$('#content').html(data);
ultXML = href;
}
});
}
});
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});

jQuery UI Dialog Validation

I know this is a common problem. I've been looking at the various solutions proposed on this site and elsewhere but cannot hit upon something that works in my situation.
Here is my script:
$(function () {
$('a.editPersonLink').live("click", function (event) {
loadDialog(this, event, '#personList');
$.validator.unobtrusive.parse('#editPersonContainer');
});
$(".deleteButton").live("click", function(e) {
e.preventDefault();
var $btn = $(this);
var $msg = $(this).attr("title");
confirmDelete($msg,
function() {
deleteRow($btn, $target);
});
});
});
function loadDialog(tag, event, target) {
event.preventDefault();
var $loading = $('<img src="../../Content/images/ajaxLoading.gif" alt="loading" class="ui-loading-icon">');
var $url = $(tag).attr('href');
var $title = $(tag).attr('title');
var $dialog = $('<div></div>');
$dialog.empty();
$dialog
.append($loading)
.load($url)
.dialog({
autoOpen: false
,title: $title
,width: 800
,modal: true
,minHeight: 200
,show: 'slide'
,hide: 'clip'
});
$dialog.dialog( "option", "buttons", {
"Save": function () {
var dlg = $(this);
$.ajax({
url: $url,
type: 'POST',
data: $("#formData").serialize(),
success: function (response) {
$(target).html(response);
dlg.dialog('close');
dlg.empty();
$("#ajaxResult").hide().html('Record saved').fadeIn(300, function () {
var e = this;
setTimeout(function () { $(e).fadeOut(400); }, 2500);
});
},
error: function (xhr) {
if (xhr.status == 400)
dlg.html(xhr.responseText, xhr.status); /* display validation errors in edit dialog */
else
displayError(xhr.responseText, xhr.status); /* display other errors in separate dialog */
}
});
},
"Cancel": function() {
$(this).dialog("close");
$(this).empty();
}
});
$dialog.dialog('open');
};
Right up near the top I am trying to cause the form to recognise the validation from the partial view on the dialog via the statement:
$.validator.unobtrusive.parse('#editPersonContainer');
editPersonContainer is the name of the div containing the data in the partial view loaded into the dialog.
The bottom line is that the validation is not recognised. Am I making the call to validator.unobtrusive.parse in the wrong place, or am I missing something else here?
I ended up changing my script to use the techniques described here
Validation now works on my jQuery UI dialogs.
Hi I came up to your question as I was looking for the same.
I include this before the ajax call to validate on client side:
if (ModelState.IsValid) {}
I make an article with the full project on
Validation client/Server JqueryUI Dialog

how to make ajax call in Jquery's delegate()

I have a delegate function of JQuery to remove a row of a grid which is anchor tagged remove, as below
$('#MyGrid').delegate('a.remove', 'click', function() {
// e.preventDefault();
var tr = $(this).closest('tr');
var htmlstring = tr.find("td").eq(0).html();
alert(htmlstring);
jQuery.ajax( //$.ajax( also not working
{
type: "POST",
url: "UploadDocuments/Removefile",
data: "removefile=" + htmlstring,
success: function(){
tr.remove();
}
});
});
this is where i am making delegate call in success function of JQuery
success: function(result) {
var htmlString = [result];
for (i = 0; i < htmlString.length; i++) {
$('#MyGrid tbody').append('<tr><td>Remove</td></tr>');
}
},
Now i want to make ajax call as shown but it is not hitting once i click remove ,but is loading initially.Also i need to pass the data i.e the name of the deleted row.How can i get that value?
could any of you guys help me out! got stucked !! ;)
thanking you,
michaeld
Try this where IndexOfNameColumn points to the name column index.
$('#MyGrid').delegate('a.remove', 'click', function() {
// e.preventDefault();
var tr = $(this).closest('tr'); //line#3
var htmlstring = tr.find("td").eq(IndexOfNameColumn).html();
jQuery.ajax( //$.ajax( also not working
{
type: "POST",
url: "UploadDocuments/Removefile",
data: "removefile=" + htmlstring //file name from line#3
});
tr.remove();
});
try this code-
$('#MyGrid').delegate('a.remove', 'click', function() {
// e.preventDefault();
var tr = $(this).closest('tr').find("td").eq(0).find('a').text().replace(/"/g,"").trim(); //line#3
var $this = $(this);
jQuery.ajax(
{
type: "POST",
url: "UploadDocuments/Removefile",
data: "removefile=" + tr //file name from line#3
success: function(){
$this.closest('tr').remove();
}
});
});

Resources