Jquery Ajax post animation during ajax process? - asp.net-mvc

I do ajax post on my mvc app when dropdown change.
$(function () {
$('#meters').change(function () {
var analizor_id = $(this).val();
if (analizor_id && analizor_id != '') {
$.ajax({
url: '#Url.Action("AnalizorInfoPartial", "Enerji")',
type: 'GET',
cache: false,
data: { analizor_id: analizor_id },
success: function (result) {
$('#TableAnalizorInfo').html(result);
}
});
}
});
});
DropDown
#Html.DropDownList("sno", new SelectList(Model, "sno", "AnalizorAdi"), "-- Analizör Seçiniz --", new { id = "meters" })
Can I show a loading image or anything else during ajax process? (between begin - finish event) and Code example?
EDIT
Can I use like this?
success: function (result) {
$('#TableAnalizorInfo').html(result);
}
begin:function(){
//show image
}
complete:function(){
//hide image
}
Thanks.

Of course, the events you are looking for are beforeSend and complete:
if (analizor_id && analizor_id != '') {
$.ajax({
url: '#Url.Action("AnalizorInfoPartial", "Enerji")',
type: 'GET',
cache: false,
beforeSend: function() {
// Show your spinner
},
complete: function() {
// Hide your spinner
},
data: { analizor_id: analizor_id },
success: function (result) {
$('#TableAnalizorInfo').html(result);
}
});
}
or you could do it globally for all AJAX requests on the page using global AJAX event handlers:
$(document).ajaxSend(function() {
// Show your spinner
}).ajaxComplete(function() {
// Hide your spinner
});

Related

JQuery Autocomplete acts wierd once i publish my website

I am using this functionality to fill the JQuery UI with minimum length set to 2. This code works good when I try to select the list through mouse or through keyboard.
But once I publish my code through my virtual machine it does not work. Neither the minimum length works nor the mouse or keyboard selection works.
Please help me here.
function SPAutoComplete(request, response) {
//debugger;
$.ajax({
url: 'Contracts/SearchSpByNumber',
type: 'GET',
cache: false,
contentType: "application/json; charset=utf-8",
data: request,
dataType: 'json',
success: function (json) {
var i = 0;
i++;
// call autocomplete callback method with results
response($.map(json, function (item) {
return {
label: item.SP_NBR,
SPDesc: item.SP_DESC,
ID: item.ElementID
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert('error - ' + textStatus);
console.log('error', textStatus, errorThrown);
}
});
}
$("#SP1").autocomplete({
source: SPAutoComplete,
minLength: 2,
select: function (event, ui) {
// alert('you have selected ' + ui.item.name + ' ID: ' + ui.item.name);
$("#SP1").val(ui.item.label);
$("#SPDesc1").val(ui.item.SPDesc);
$("#SPDesc1").attr("readonly", true);
$("#SP1ID").val(ui.item.ID);
_newDirty = true;
event.preventDefault();
return false;
},
change: function (event, ui) {
debugger;
if (ui.item != undefined || ui.item != null) {
$("#SP1").val(ui.item.label);
$("#SPDesc1").val(ui.item.SPDesc);
$("#SPDesc1").attr("readonly", true);
$("#SP1ID").val(ui.item.ID);
event.preventDefault();
return false;
}
},
focus: function (event, ui) {
debugger;
$("#SP1").val(ui.item.value);
return false;
}
});

select event not working

I try to store an identifier into an hiddenfield when a value is selected with a jquery autocomplete field.
But the select event is never fired and I dont't see why..
here is my code
$(document).ready(function () {
$('#test').autocomplete(
{
source: function (request, response) {
$.ajax({
url: "/Controller/Method", type: "POST", dataType: "json",
data: { Comparaison: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.text, value: item.text, id : item.value };
}));
},
select: function (event, ui) {
alert("selected");
//$("#idProprio").val(ui.item.id);
}
});
},
});
});
The autocompletion is properly working, I can see the values, select one but when I select a value nothig happens..
I believe your curly braces are wrong. select is being set as part of the ajax parameter, not autocomplete:
$(document).ready(function () {
$('#test').autocomplete(
{
source: function (request, response) {
$.ajax({
url: "/Controller/Method", type: "POST", dataType: "json",
data: { Comparaison: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.text, value: item.text, id : item.value };
}));
}
});
},
select: function (event, ui) {
alert("selected");
//$("#idProprio").val(ui.item.id);
}
});
});

Dynamically added form ajax not work

I have a list of div's.
When I click on a button in a div I switch div content with partial view which contain form.
This is code that happens when I click on that button:
#Html.ActionLink("edit", "EditUserLanguage", "UserLanguage", new { userLanguageId = Model.UserLanguageId }, new { #class = "editButton" })
...
$(document).on('click', '.editButton', function (e) {
$.ajax({
url: this.href,
cache: false,
success: function (html) {
var id = $(e.target).closest("div").attr("id");
$("#" + id).empty();
$("#" + id).append(html);
}
});
return false;
});
Html (partial view) that I add has:
#using (Html.BeginForm("UpdateUserLanguage", "UserLanguage", FormMethod.Post, new { id = "updateUserLanagegeForm" }))
{
...
This main view where is the list of div's and where I add this new partial view I have this code:
$(function () {
$('#updateUserLanagegeForm').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert("work");
}
});
return false;
});
}); //update
When I click on submit action method is invoked and I get new partial view returned but not via ajax.
I only get that partial view returned. alert("work"); is never called.
What could be the reason that this ajax call doesn't work?
submit handler is not being attached to form as form gets loaded after dom ready. So change your code to -
$('body').on('submit','#updateUserLanagegeForm',(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert("work");
}
});
return false;
});
This will attach handler to form even if it is added dynamically.

Asp.net Mvc jquery ajax?

I have links like following.
Deneme Müşteri 2
Deneme Müşteri 2
I want to use jquery ajax post like this:
$(".customer_details").click(function () {
$.ajax({
url: $(this).attr("href"),
type: 'POST',
beforeSend: function () {
},
complete: function () {
},
success: function (result) {
$("#customer_operations_container").html(result);
},
error: function (result) {
alert("Hata!");
}
}); //end ajax
});
Or this:
$(".customer_details").click(function () {
$("#customer_operations_container").load($(this).attr("href"));
});
And Action Method
public ActionResult _EditCustomer(int CustomerId)
{
// get customer from db by customer id.
return PartialView(customer);
}
But I cant do what I wanted. When I click to link, PartialView does not load. It is opening as a new page without its parent. I tried prevent.Default but result is the same.
How can I load the partialView to into a div?
Note: If I use link like this <a href="#"> it works.
Thanks.
Maybe the problem is with the actionresult, try with Content to see if that changes anything.
public ActionResult _EditCustomer(int CustomerId)
{
// get customer from db by customer id.
return Content(customer.ToString());
}
Try one of these...
$(".customer_details").click(function (e) {
e.preventDefault()
$.ajax({
url: $(this).attr("href"),
//I think you want a GET here? Right?
type: 'GET',
beforeSend: function () {
},
complete: function () {
},
success: function (result) {
$("#customer_operations_container").html(result);
},
error: function (result) {
alert("Hata!");
}
}); //end ajax
});
Or
$(".customer_details").click(function (e) {
e.preventDefault();
$("#customer_operations_container").load($(this).attr("href"));
});
Or
$(".customer_details").click(function (e) {
e.preventDefault();
$.get($(this).attr("href"), function(data) {
$("#customer_operations_container").html(data);
});
});
If none of this works, check if there's any js errors
The problem is when you click on the link you already start navigation to it. So just use e.preventDefault() or return false from the click method to prevent the default behavior
$(".customer_details").click(function (e) {
e.preventDefault();
...
}
This should help you out:
$.ajax({
url: $(this).attr("href"),
type: 'POST',
beforeSend: function () {
},
complete: function () {
},
success: function (result) {
$("#customer_operations_container").html(result);
},
error: function (result) {
alert("Hata!");
}
}); //end ajax
return false;
The only thing you where missing is the prevention of A tag working. By returning false your custom event is called and the default event is not executed.
Try this
$(function(){
$(".customer_details").click(function (e) {
e.preventDefault();
});
});
Using ready event
Demo: http://jsfiddle.net/hdqDZ/

how to redirect to a view on $.AJAX complete - asp.net mvc 3

Ok..i want to redirect a user after the validation check using $.AJAX to a peritcular view... how do i do that ? .. pleae help...
here is my $.AJAX code... EX: i want user redirected to "/Home/Movies" controller action...
if not logged in stay on the same page...
<script type="text/javascript">
$('#btnLogin').click(function () {
var email = $('#Email').val();
var Password = $('#Password').val();
var postdata =
{
"Email": email,
"Password": Password
};
$('.Loading').fadeIn(50);
$.ajax({
url: '#Url.Action("CheckLogin","Home")',
data: postdata,
success: function (msg) {
var data = msg.split(':');
$('#Result').html(data[0]);
$('.Loading').fadeOut(50);
},
error: function (data) {
$('#Result').html(data);
$('.Loading').fadeOut(50);
}
});
});
</script>
here is my controller action which is used for checking Login details...
public ContentResult CheckLogin(Users checkuser)
{
if (db.CheckUserLoginDetails(checkuser.Email, checkuser.Password))
{
return Content("Login Successful:" + checkuser.Email);
}
else
{
return Content("Login UnSuccessful");
}
}
also how can i pass a returned results from this view to another view.. in this exmaple if the user is logged in i want to show his email id on the redirected page which is lets say "/home/Movies"
thx in advance
Show your loading image before ajax request, and hide on success or error handlers.
add <div class="loading">Loading...</div> to your markup
$('.loading').fadeIn(50);
$.ajax({
url: '#Url.Action("CheckLogin","Home")',
data: postdata,
success: function (msg) {
$('#Result').html(msg);
$('.loading').fadeOut(50);
},
error: function (data) {
$('#Result').html(msg);
$('.loading').fadeOut(50);
}
});
Take a look at the ajaxStart() and ajaxStop() event handlers in jQuery. You could use these to show and hide a layer with a gif-animation.
http://api.jquery.com/ajaxStart/
http://api.jquery.com/ajaxStop/
use beforSend and complete attributes.
$.ajax({
url: '#Url.Action("CheckLogin","Home")',
data: postdata,
success: function (msg) {
$('#Result').html(msg);
},
error: function (data) {
$('#Result').html(msg);
},
beforeSend: function() {
$("body").append("<div class=\"ajaxLoader\" id=\"ajaxLoader"\"><div class=\"ajaxAnimation\"></div></div>");
$("#ajaxLoader").hide();
$("#ajaxLoader").fadeIn('fast');
},
complete: function() {
$("#ajaxLoader").remove();
}
});
And specify animation with css
.ajaxAnimation {
background-image: url('images/ajax-loader.gif');
background-repeat: no-repeat;
background-position: center center;
}

Resources