Return a JSON result after deleting an item - ajax

I'm developing a web application with MVC 3 and want to return a message to the user after he has deleted an item successfully.
MyWallController method looks like this:
[HttpPost]
public ActionResult DeleteAlbum(Guid albumId)
{
try
{
this.albumService.DeleteAlbum(albumId);
return Json(new { success = true, msg = "Album successfully deleted" }, JsonRequestBehavior.AllowGet);
}
catch (FPSException e)
{
return Json(new { success = false, msg = e.Message });
}
catch (Exception)
{
throw new HttpException(500, "Error while deleting album");
}
}
The link:
<a class="open-DeleteAlbumDialog" href="http://localhost:2941/MyWall/DeleteAlbum?albumId=0f49b1ad-8ec1-4fca-b8e2-28bdbf47824e">Delete</a>
The JavaScript:
$(function () {
$(document).on('click', '.open-DeleteAlbumDialog', function () {
var answer = confirm('Are you sure you want to delete this album?')
if (answer) {
$.post(this.href, function (data) {
if (data.success) {
// do something
} else {
// do something else
}
});
}
else return false;
});
However the function defined inside post is never called and what I get is a "the resource cannot be found". But the item has been deleted successfully.
All kinds of help is appreciated.

Your link is still working. You need to preventDefault:
$(function () {
$(document).on('click', '.open-DeleteAlbumDialog', function (e) {
e.preventDefault();
var answer = confirm('Are you sure you want to delete this album?')
if (answer) {
$.post(this.href, function (data) {
if (data.success) {
// do something
} else {
// do something else
}
});
}
});

Related

Bootstrap Selectpicker not refreshing

When a user clicks the edit icon the contents of a selectpicker are updated then refreshed. Then the selectpicker's value is updated, then refreshed again, but for some reason it is not updating with the selected value.
Everything works fine when I manually enter in the the same code in the console.
$('#IncWidgetId').val(864)// the value used when breaking in console
$('#IncWidgetId').selectpicker('refresh')
I have ensured that the selectpicker is updated with the new option values along with confirming the deferred is firing in the proper order.
As a double check, I also have separated the .selectpicker('refresh') to make sure it didn't try to fire before the option was selected due to async, but it is still not updating the selectpicker with the selected value.
$(document).on('click', '[id^=EditWidgetId-]', function () {
var id = $(this).attr('id').split('-')[1];
var mfg = $(this).data('mfg');
var widgetid = $(this).data('widgetid ');
var mfgSelect = $('input[name=mfg][value="' + mfg + '"]');
mfgSelect.prop('checked', true);
$.when(LoadWidgets(mfg)).then(function () {
console.log('then function');
$('#IncWidgetId').val(widgetid );
}).done(function () {
console.log('done function');
$('#IncWidgetId').selectpicker('refresh');
});
$('#modalWidgetNew').modal('show');
});
function LoadWidgets(mfg) {
var r = $.Deferred();
console.log('before ajax');
r.resolve($.ajax({
url: '/Widgets/FilterWidgetsDropdown',
type: 'GET',
cache: false,
data: { mfg: mfg },
success: function (partial) {
$('#IncWidgetDDArea').html(partial);
$('#IncWidgetId').selectpicker('refresh')
},
error: function (x, e) {
if (x.status == 0) {
alert('You are offline!!\n Please Check Your Network.');
} else if (x.status == 404) {
alert('Requested URL not found.');
} else if (x.status == 500) {
alert('Internel Server Error.');
} else if (e == 'parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if (e == 'timeout') {
alert('Request Time out.');
} else {
alert('Unknow Error.\n' + x.responseText);
}
}
})).done(function () {
console.log('after ajax');
return r.promise();
});
}
What am I missing?
There was such an issue in old versions of this plugin.
Try to destroy it and initialize again. Something like this:
$('#IncWidgetId').selectpicker('destroy');
$('#IncWidgetId').selectpicker();

How do I include an Ajax validator before sending

I managed to make this code to submit a form, it works fine, but I can not implement a validator does not need it, but it shows no message just does not send the form is empty.
I searched but could not quite do it. Can anyone help me?
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#newsletter').submit(function(){
var dados = jQuery( this ).serialize();
jQuery.ajax({
type: "POST",
url: "newsletter_cadastrar.asp?f=1",
data: dados,
success: function( data )
{
$('#resultado-form-newsletter').html(data);
}
});
return false;
});
});
</script>
<input id="nomenewslbase" name="nomenewslbase" type="text">
<input id="emailnewslbase" name="emailnewslbase" type="email">
Thank you for your attention.
If you are looking for applying jquery validation rules then you can do it like:
<script type="text/javascript">
function ValidationRules() {
}
ValidationRules.prototype.initializeSaveValidators = function() {
jQuery.validator.addMethod("csProjectName",
function(value, element) {
if ($.trim($('#txtProjectName').val()) == "") {
if ($.trim($(element).val()) != '')
return true;
else
return false;
} else
return true;
}, "Project Name is required");
jQuery.validator.addMethod("csDescription",
function (value, element) {
if ($.trim($('#txtDescription').val()) == "") {
if ($.trim($(element).val()) != '')
return true;
else
return false;
}
else
return true;
}, "Description is required");
};
ValidationRules.prototype.enableSaveValidators = function () {
jQuery.validator.classRuleSettings.csProjectName = { csProjectName: true };
jQuery.validator.classRuleSettings.csDescription = { csDescription: true };
};
ValidationRules.prototype.disableSaveValidators = function () {
jQuery.validator.classRuleSettings.csProjectName = { csProjectName: false };
jQuery.validator.classRuleSettings.csDescription = { csDescription: false };
};
jQuery(document).ready(function () {
var validationRules = new ValidationRules();
validationRules.initializeSaveValidators();
validationRules.enableSaveValidators();
$("#btnsubmit").click(function () {
applyjQueryValidation();
return false;
});
});
function applyjQueryValidation() {
var isValid = $('#newsletter').valid();
//here you can manually check for some extra validations
if (isValid==true) {
alert("valid");
//here is you ajax call
}else{
alert("invalid");
}
}
</script>
Also, you need to include jquery.validate.js
Here is the JSfiddle working example.

AJAX POST request never completes. Data posts to server

I am sending a post request via AJAX. The data successfully posts but the AJAX call never completes. Backbone on the front; Node on the back. I am including the save function from my backbone view and the express route.
save: function(event) {
event.preventDefault();
console.log( 'You signed up for ' + this.model.get('name'));
var name = this.model.get('name');
var courseDay = this.model.get('courseDay');
var time = this.model.get('time');
var location = this.model.get('location');
jQuery.post("/test/signups", {
"name" : name,
"courseDay" : courseDay,
"time" : time,
"location" : location,
}, function (data, textStatus, jqXHR) {
console.log("Post response:");
console.dir(data);
console.log(textStatus);
console.dir(jqXHR);
});
}
Route:
app.post('/test/signups', isLoggedIn, function (req, res){
User.findOne({'_id': req.user.id }, function(err, user) {
if (err)
return done(err);
if (user) {
user.signup.name = req.body.name;
user.signup.courseDay = req.body.courseDay;
user.signup.time = req.body.time;
user.signup.location = req.body.location;
user.signup.modified = req.body.modified;
user.update({$push: { "signup" :
{ name: user.signup.name,
courseDay: user.signup.courseDay,
time: user.signup.time,
location: user.signup.location,
modified: user.signup.modified
}
}},{safe:true, upsert:true},function(err){
if(err){
console.log(err);
} else {
console.log("Successfully added" + user.signup);
}
});
}
});
});
Your server side code needs to send a response. Try something like below. Note I try to cover all cases of an error, user not found, and user found.
app.post('/test/signups', isLoggedIn, function (req, res){
User.findOne({'_id': req.user.id }, function(err, user) {
if (err) {
return res.status(500).send(err);
}
if (user) {
user.signup.name = req.body.name;
user.signup.courseDay = req.body.courseDay;
user.signup.time = req.body.time;
user.signup.location = req.body.location;
user.signup.modified = req.body.modified;
user.update({$push: { "signup" :
{ name: user.signup.name,
courseDay: user.signup.courseDay,
time: user.signup.time,
location: user.signup.location,
modified: user.signup.modified
}
}},{safe:true, upsert:true},function(err){
if(err){
return res.status(500).send(err);
}
console.log("Successfully added" + user.signup);
res.send(user);
});
} else {
res.status(404).send();
}
});
});

Prevent Kendo grid popup edit from closing on Error

I am trying to handle the server error when creating/updating/deleting item from kendo grid. But when a error is thrown, the kendo grid closes no matter what.
function kendo_error_handler(e) {
if (e.errors) {
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
showErrorMessages(key, message);
});
//this does not work
var grid = this;
gird.one("dataBinding", function (e) {
e.preventDefault();
});
}
}
Does anybody have any other solution? e.preventDefault() doesn't work either.
This worked for me. Just in case anybody needs this.
function kendo_error_handler(gridName) {
return function (e) {
if (e.errors) {
var grid = $('#'+gridName).data("kendoGrid");
grid.one("dataBinding", function (ev) {
ev.preventDefault();
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
showErrorMessages(key, message);
});
});
}
else {
$("#errorContainer").text("");
}
}
}
is it cause it says " gird.one(" instead of "grid.one("

AJAX Form Validation to see if course already exist always return true

I want to validate my course name field if the course name inputted already exist using AJAX, but my ajax function always return the alert('Already exist') even if i inputted data that not yet in the database. Please help. Here is my code. Thanks.
View:
<script type="text/javascript">
var typingTimer;
var doneTypingInterval = 3000;
$('#course_name').keyup(function(){
typingTimer = setTimeout(check_course_name_exist, doneTypingInterval);
});
$('#course_name').keydown(function(){
clearTimeout(typingTimer);
});
function check_course_name_exist()
{
var course_name=$("#course_name").val();
var postData= {
'course_name':course_name
};
$.ajax({
type: "POST",
url: "<?php echo base_url();?>/courses/check_course_name_existence",
data: postData,
success: function(msg)
{
if(msg == 0)
{
alert('Already Exist!');
return false;
}
else
{
alert('Available');
return false;
}
return false;
}
});
$("html, body").animate({ scrollTop: 0 }, 600);
return false;
}
</script>
Controller:
function check_course_name_existence()
{
$course_name = $this->input->post('course_name');
$result = $this->course_booking_model->check_course_name_exist($course_name);
if ($result)
{
return true;
}
else
{
return false;
}
}
Model:
function check_course_name_exist($course_name)
{
$this->db->where("course_name",$course_name);
$query=$this->db->get("courses");
if($query->num_rows()>0)
{
return true;
}
else
{
return false;
}
}
You could use console.log() function from firebug. This way you will know exactly what the ajax returns. Example:
success: function(msg) {
console.log(msg);
}
This way you also know the type of the result variable.
jQuery, and Javascript generally, does not have access to the Boolean values that the PHP functions are returning. So either they return TRUE or FALSE does not make any difference for the JS part of your code.
You should try to echo something in your controller and then make your Javascript comparison based on that value.

Resources