Toggle partial view with AJAX - ajax

In my MVC-project I have this code for rendering a partial-view:
Method:
public ActionResult ShowArtCollection()
{
var model = new ViewModel();
model.ArtWorks = db.ArtWorks.ToList();
return PartialView("_artcollection", model);
}
AJAX:
$("#btnArt").click(function () {
$.ajax({
url: '/Home/ShowArtCollection',
dataType: 'html',
success: function (data) {
$('#artworks').html(data);
}
});
});
I would like my #btnArt to be able to toggle the partial view. I mean that when the _artcollection is rendered by the click of the button, the next click should "unrender" the view. Any tips on how to achieve this?

you can put a flag and check if rendered next time unrender on click:
var rendered = false;
$("#btnArt").click(function () {
if (!rendered) {
$.ajax({
url: '/Home/ShowArtCollection',
dataType: 'html',
success: function (data) {
$('#artworks').html(data);
rendered = true;
}
});
} else {
$('#artworks').html("");
rendered = false;
}
});
this will do the trick for you.

Related

Show Button after ajax function success

I want to show a button "Reload Game" after function success instead of this bootstrapDialog box
I need this button to fit over my <div class="tilting"></div> Instead of showing somewhere else on page
You need to use below code inside the success method,
document.getElementsByClassName("tilting")[0].innerHTML="<button type="button">Reload Game</button>";
If you are using jQuery Ajax try it below way,
function loadDoc() {
$.ajax({
type: 'POST',
url: 'APUC',
data: 'productName=' + productName,
dataType: 'html',
cache: false,
success: function (result) {
document.getElementsByClassName("tilting")[0].innerHTML="<button type="button">Reload Game</button>";
},
});
}
If you are using pure Ajax, try it like this:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementsByClassName("tilting")[0].innerHTML="<button type="button">Reload Game</button>";
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}

Ajax serialize with extra data MVC

I use a webgid so to display records that have to do with the user. I load this webgrid in a partilal view after the user clicks on an ajax actionlink.
#Ajax.ActionLink(" ", "AddUserElements", "Users", new { username = item.UserName }, new AjaxOptions() { UpdateTargetId = "add_research"}, new { #class = "glyphicon glyphicon-link" })
In this webgrid I have a delete action. When I click the delete a modal appears so to ask for verification. I click on yes and the record is being deleted but the webgrid in the partial view doesn't being refreshed. To update the partial view I use in my ajax code
$("#add_research").load('/Users/AddUserElements');
I tried to pass the username with serialize to controller but no lack
My ajax code
$(function () {
$.ajaxSetup({ cache: false });
$("a[data-modal]").on("click", function (e) {
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
keyboard: true
}, 'show');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
$('#progress').show();
var data = $(this).serialize() + '&' + $.param({ 'username': '#Model.UserName' }, true);
$.ajax({
url: this.action,
type: "POST",
data: data,
cache: false,
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
$('#progress').hide();
$("#add_research").load('/Users/AddUserElements');
} else {
$('#progress').hide();
$('#myModalContent').html(result);
bindForm();
}
}
});
return false;
});
}
My controller
public ActionResult AddUserElements(string username)
Any idea?
thank you

Opposite of PreventDefault() : Continuing ActionLink logic

<%: Html.ActionLink("Print", "Print", "Print", New With {.id = Model.ID}, New With {.target = "_blank", .class = "print"})%>
How to return to my actionlink's functionality once preventDefault is called? ( the _blank page is not being opened on return)
$('#NameOfButton').bind('click', function (e) {
e.preventDefault(); // Stop click event
//Gather Data
var data = $(this).parents('form').first().serialize();
//Check Data , if saved to DB continue Click functionality
$.ajax({
url: '<%:Url.Action("Get")%>',
cache: false,
type: 'POST',
data: data,
success: function (result) {
if (result.Success == true) {
//return;
return true;
} else {
//do nothing
console.log('false');
}
}
});
});
Solution:
$('#NameOfButton').bind('click', function (e) {
e.preventDefault(); // Stop click event
//Gather Data
var el= $(this);
var data = $(this).parents('form').first().serialize();
//Check Data , if saved to DB continue Click functionality
$.ajax({
url: '<%:Url.Action("Get")%>',
cache: false,
type: 'POST',
data: data,
success: function (result) {
if (result.Success == true) {
window.location.href = el.attr('href');
} else {
//do nothing
}
}
});
});
You can trigger the event again:
$('#NameOfButton').bind('click', function (e, skip) {
if (skip) return; // check param
e.preventDefault(); // Stop click event
//Gather Data
var data = $(this).parents('form').first().serialize();
var el = $(this);
//Check Data , if saved to DB continue Click functionality
$.ajax({
url: '<%:Url.Action("Get")%>',
cache: false,
type: 'POST',
data: data,
success: function (result) {
if (result.Success == true) {
console.log('true');
el.trigger('click', [true]); // trigger same event with additional param
} else {
//do nothing
console.log('false');
}
}
});
});

show ajax-loader.png on a MVC3 form submit in a Jquerymobile application

I have a mobile application with MVC3 and Jquerymobile. At form submission (with ajax function) I want to display loading icon (ajax-loader.png) while submit and redirect.
Thanks!
my ajax function:
$("#add").click(function () {
$.validator.unobtrusive.parse($('form')); //added
if ($("form").valid()) {
var IDs = new Array($("#SelectedProduct").val(), $("#SelectedAccount").val(), $("#SelectedProject").val(), $("#SelectedTask").val(), $("#date").val(), $("#duration").val());
$.ajax({
url: '#Url.Action("SaveLine", "AddLine")',
type: 'post',
data: { ids: IDs },
dataType: 'json',
traditional: true,
success: function (data) {
if (data.success == true) {
$("#ajaxPostMessage").html(data.Success);
$("#ajaxPostMessage").addClass('ajaxMessage').slideDown(function () {
window.location.href = '#Url.Action("Index", "AddLine")';
}).delay(1800)
}
else {
$("#ajaxPostMessage").html(data.Error);
$("#ajaxPostMessage").addClass('ajaxMessage');
$("#ajaxPostMessage").show();
}
}
});
}
return false;
});
I would do something like this:
Ajax = {
Submit: function() {
Ajax.Loading();
//ajax stuff
//Ajax.Message('form complete, blah blah');
},
Loading: function() {
$('#ajax').html('ajax-loader.png');
},
Message: function(msg) [
$('#ajax').html(msg);
}
}

How can I validate form and then execute additional code if successful

I cannot figure out how to merge the following separate pieces of code:
$(document).ready(function () {
$("#signupForm").validate();
});
and
$(document).ready(function () {
$("#btnSignup").click(function () {
$.ajax({
type: "POST",
dataType: 'json',
url: "/Newsletter/Signup",
data: $('#signupForm').serialize(),
success: function (response) {
if (response.success) {
$('#signupMessage').show(0);
}
else {
showValidationErrors(response.Data);
}
}
});
return false;
});
I need the first part to execute first, and if it validates the form successfully, then I need to exectute the second part.
I believe that you can use valid().
Pseudo code;
$(document).ready(function () {
$("#signupForm").validate();
$("#btnSignup").click(function () {
if ($("#signupForm").valid()) {
// ajax query
}
return false;
});
});
Does that work? I haven't checked it.
Here is a somewhat general way I use.
$('form').submit(function(e){
if (!$(e.target) && !$(e.target).valid()) {
return;
}
// Ajax call here.
$.ajax({ type: "POST",... });
});
Lastly, you could abstract the logic into an object for a more OOP approach
var formHandler = {
onSubmit: function(e){
if (!$(e.target) && !$(e.target).valid()) {
return;
}
// Ajax call here.
$.ajax({ type: "POST",... });
}
}
$('form').submit(formHandler.onSubmit);

Resources