Jquery Ajax Post is not calling action method - asp.net-mvc-3

function CreateModalDialogWindow(urlPath) {
$.ajax({
url: '#Url.Action("Popup","Project")',
type: 'POST',
async: false,
success: function (data) {
debugger;
$('#dialog').html(data).dialog({
autoOpen: true,
width: 400,
resizable: false,
modal: true
});
},
error: function(){
alert('Error!');
}
});
return false;
}
I wanted to call an actionmethod using ajax post. Here is the action method
[HttpPost]
public PartialViewResult Popup()
{
return PartialView("~/Views/Shared/Project/Popup.cshtml");
}
Please let me know what is wrong in the above code.

There might be different reasons why the action method is not being called:
you have some javascript error
you never call the CreateModalDialogWindow function
you call the CreateModalDialogWindow in the click of a link or form submit but you forgot to cancel the default action of this button by returning false.
So start by first calling this code in the document ready to see if it works:
<script type="text/javascript">
$(function() {
$.ajax({
url: '#Url.Action("Popup", "Project")',
type: 'POST',
success: function (data) {
$('#dialog').html(data).dialog({
autoOpen: true,
width: 400,
resizable: false,
modal: true
});
}
});
});
</script>
Now if you put a breakpoint in your controller action it should normally be hit. I would recommend you using a javascript debugging tool such as FireBug which will help you see any possible javascript errors and see the exact requests/responses being sent during AJAX requests.
You will also notice that I have removed the async: false switch because this makes synchronous calls to the server freezing the web browser during the execution of this request and thus you are no longer doing AJAX.

Related

Generating File with Ajax Fileupload

My app is an MVC .NET 4.0 application.
My application is fairly straightforward. I open an text file and uploaded it to be processed and returned as an excel file. This works as expected.
The excel file is returned via an actionresult controller. There are no errors. It works the way I want it to.
The problem is that when I call ajaxStart with blockUI it works. However, upon returning the file, the ajaxStop or ajaxSuccess is never fired to turn off the spinner after the file result is displayed with a message - do you want to open the file or save it or cancel.
I'm using jquery fileupload, blockUI and jquery 1.9.1.
$('#fileupload').fileupload({
dataType: 'json',
type: 'POST',
url: fileuploadpath,
autoUpload: true,
beforeSend: function () {
$.blockUI({
timeout: 0,
message: '<h1><img src="../images/ajax-loader.gif" /> Processing...</h1>'
});
},
complete: function() {
//$.unblockUI();
},
done: function (e, data) {
//$('.file_name').html(data.result.message.Name);
//$('.file_type').html(data.result.message.Type);
//$('.file_size').html(data.result.message.Length);
$('.file_msg').html(data.result.message.Error);
},
success: function (data) {
$.unblockUI();
$('.file_msg').html(data.result.message.Error);
}
});
and here is the basics of the file return in the action controller:
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
return File(fileoutput, "application/vnd.ms-excel");
Everything works just great. The area I'm scratching over my head is - why isn't the spinner being turned off after the file return? Am I missing something? I've tried binding ajaxStop and ajaxStart to the document but that does not work. ajaxStart gets fired but upon the file return, ajaxStop is being ignored.
Remove the 'done' and 'complete' event and use this format for your ajax call:
$(document).ready(function() {
$('#fileupload').fileupload({
dataType: 'json',
type: 'POST',
url: fileuploadpath,
autoUpload: true,
timeout:60000,
beforeSend: function () {
$('#loader').show()
},
success: function (data) {
$('#loader').hide()
//$('.file_name').html(data.result.message.Name);
//$('.file_type').html(data.result.message.Type);
//$('.file_size').html(data.result.message.Length);
$('.file_msg').html(data.result.message.Error); //??? you are passing the error here
},
error: function(jqXHR, textStatus, errorThrown) {
$('#loader').hide()
if(textStatus==="timeout") {
alert("A timeout occurred");
} else {
alert("This is an other error");
}
}
});
});
NOTE: seen you have trouble with the blockUi, I have here used a other approach.
TIMEOUT:
I have set an extra parameter 'timeout' and set this to 60 sec. You coul set this to '0' which will be unlimited but it will be better practice to give it a limited value.
Place this in your HTML and give it a style of 'display:none' and an id.
<h1><img id="loader" src="../images/ajax-loader.gif" style="display:none"/> Processing...</h1>'

Overlapping Issue on Ajax Call: Success

I am facing with overlapping problem after Ajax Call. I am using a plug-in called "Nerve Slider" for my grid layout(as you see in here (on the far right)).
After I did this:
<script type="text/javascript">
$(function(){
$('.kategori-link').click(function(){
$.ajax({
type: 'POST',
url: '<?php echo base_url('tr/main/index'); ?>',
data: {kategori:'ucak-bileti'},
dataType: 'html',
success: function(data){
var result = $('<div />').append(data).find('.iAmTest').html();
$('.iAmTest').html(result);
//console.log(result);
},
error: function(){
alert("Sorry! Something went wrong!");
}
});
return false;
});
});
All grids (Each grid has Image, Header, Info as you see in the link above) which I got after database interaction are overlapped! What do you think causes this to happen?
Thank you!
EDIT
Plug-in Scripts:
$(function(){
$(".slider-wrapper").nerveSlider({
sliderWidth: "100%",
slideTransitionSpeed: 700,
slideTransitionEasing: "easeInOutExpo",
slidesDraggable: true,
sliderResizable: true,
sliderFullscreen: false
});
});
$(function(){
$(".cnt-slider-wrapper").nerveSlider({
sliderAutoPlay: false,
slideTransitionSpeed: 700,
slideTransitionEasing: "easeInOutExpo",
slidesDraggable: true,
sliderResizable: true,
sliderFullscreen: false,
showPause: false
});
$(".iAmTest").puzzleGrid({
// options...
});
});
This may or may not work, I have not tested this.
While not a clean solution, you can call $(window).trigger("resize"); after your $('.iAmTest').html(result); line. The plugin script has a function called setuppanels(); that is attached to the window resize event. That re-initialises the content.

jsFiddle testing jQuery AJAX request with echo

The following code is alerting 'undefined' and not appending the html from the response data as I expected. Does anyone know why?
JavaScript:
$(function() {
$('.document').on('click', '.ajax', function(e) {
e.preventDefault();
// ajax request
$.ajax({
async: true,
cache: false,
type: 'post',
url: '/echo/html/',
data: {
html: '<p>This is echoed the response in HTML format</p>',
delay: 1
},
dataType: 'html',
beforeSend: function() {
console.log('Fired prior to the request');
},
success: function(data) {
console.log('Fired when the request is successfull');
$('.document').append(data);
},
complete: function() {
console.log('Fired when the request is complete');
}
});
});
});​
HTML:
<div class="document">
<a class="ajax" href="#">Fire an AJAX request</a>
</div>​
Example jsFiddle: http://jsfiddle.net/L6bJ2/3/
The HTTP method is specified with by type rather than method, so you should be using;
type: 'post',
Because you've specified the response type as HTML, you get a String passed in the data parameter of the success callback; but it looks like you're expecting JSON as you're trying to use data.html. Instead, use data directly;
success: function(data) {
console.log('Fired when the request is successfull');
$('.document').append(data);
},
With these changes, you'll find it works: http://jsfiddle.net/L6bJ2/6/
Live Example is here
https://stackoverflow.com/a/34940340/5361795
use beforeSend or complete callback functions in ajax call,
Source ShoutingCode

MVC 3 Client side validation on jQuery dialog

I am showing lots of form using jquery dialog and I wish to add in client side validation on it. I read through some examples, saying that mvc 3 already somehow support jquery client side validation, but I tried by including the necessary script, and my form like this:
#using (Html.BeginForm("CreateFood", "Home", FormMethod.Post, new { id = "formData" }))
{
#Html.ValidationSummary(false, "Please fix these errors.")
When i try to submit my form without fill in the required field, I still dint get any message. Can anyone give me more idea / explanation / examples on this??
Really needs help here... Thanks...
UPDATE (add in the script for my dialog)
$createdialog.dialog("option", "buttons", {
"Cancel": function () {
//alert('Cancel');
$createdialog.dialog('close');
},
"Submit": function () {
var frm = $('#formData');
$.ajax({
url: '/Food/CreateFood',
type: 'POST',
data: frm.serialize(),
success: $createdialog.dialog('close')
});
}
});
Once dropped, open dialog:
// Once drop, open dialog to create food
options.drop = function (event, ui) {
// Get the ContainerImgName which food dropped at
var cimg = $(this).attr('id');
// Pass in ContainerImgName to retrieve respective ContainerID
// Once success, set the container hidden field value in the FoodForm
$.ajax({
url: '/food/getcontainerid',
type: 'GET',
data: { cImg: cimg },
success: function (result) { $('#containerID').val(result); }
});
clear();
$.validator.unobtrusive.parse($createdialog);
$createdialog.dialog('open');
};
I've faced the same problem, solved with:
$(name).dialog({
autoOpen: true,
width: options.witdth,
heigth: options.height,
resizable: true,
draggable: true,
title: options.title,
modal: true,
open: function (event, ui) {
// Enable validation for unobtrusive stuffs
$(this).load(options.url, function () {
var $jQval = $.validator;
$jQval.unobtrusive.parse($(this));
});
}
});
of course you can add the validation on the close event of the dialog, depends on what you're doing, in my case the popup was just for displaying errors so I've performed validation on load of the content. (this pop up is displaying am Action result)
For every dynamically generated form you need to manually run the validator once you inject this content into the DOM as shown in this blog post using the $.validator.unobtrusive.parse function.

Disable Button while AJAX Request

I'm trying to disable a button after it's clicked. I have tried:
$("#ajaxStart").click(function() {
$("#ajaxStart").attr("disabled", true);
$.ajax({
url: 'http://localhost:8080/jQueryTest/test.json',
data: {
action: 'viewRekonInfo'
},
type: 'post',
success: function(response){
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
},
error: errorhandler,
dataType: 'json'
});
$("#ajaxStart").attr("disabled", false);
});
but the button is not getting disabled. When I remove $("#ajaxStart").attr("disabled", false); the button gets disabled.
While this is not working as expected, I think the code sequence is correct. Any help will be appreciated.
Put $("#ajaxStart").attr("disabled", false); inside the success function:
$("#ajaxStart").click(function() {
$("#ajaxStart").attr("disabled", true);
$.ajax({
url: 'http://localhost:8080/jQueryTest/test.json',
data: {
action: 'viewRekonInfo'
},
type: 'post',
success: function(response){
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
$("#ajaxStart").attr("disabled", false);
},
error: errorhandler,
dataType: 'json'
});
});
This will ensure that disable is set to false after the data has loaded... Currently you disable and enable the button in the same click function, ie at the same time.
In your code, you just disable & enable the button on the same button click,.
You have to enable it inside the completion of AJAX call
something like this
success: function(response){
$("#ajaxStart").attr("disabled", false);
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
},
I have solved this by defining two jquery functions:
var showDisableLayer = function() {
$('<div id="loading" style="position:fixed; z-index: 2147483647; top:0; left:0; background-color: white; opacity:0.0;filter:alpha(opacity=0);"></div>').appendTo(document.body);
$("#loading").height($(document).height());
$("#loading").width($(document).width());
};
var hideDisableLayer = function() {
$("#loading").remove();
};
The first function creates a layer on top of everything. The reason the layer is white and completely opaque, is that otherwise, IE allows you to click through it.
When doing my ajax, i do like this:
$("#ajaxStart").click(function() {
showDisableLayer(); // Show the layer of glass.
$.ajax({
url: 'http://localhost:8080/jQueryTest/test.json',
data: {
action: 'viewRekonInfo'
},
type: 'post',
success: function(response){
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
hideDisableLayer(); // Hides the layer of glass.
},
error: errorhandler,
dataType: 'json'
});
});
I solved this by using global function of ajax
$(document).ajaxStart(function () {
$("#btnSubmit").attr("disabled", true);
});
$(document).ajaxComplete(function () {
$("#btnSubmit").attr("disabled", false);
});
here is documentation link.
The $.ajax() call "will not block" -- that means it will return immediately, and then you enable the button immediately, so the button is not disabled.
You can enable the button when the AJAX is successful, has error, or is otherwise finished, by using complete: http://api.jquery.com/jQuery.ajax/
complete(XMLHttpRequest,
textStatus)
A function to be
called when the request finishes
(after success and error callbacks are
executed). The function gets passed
two arguments: The XMLHttpRequest
object and a string categorizing the
status of the request ("success",
"notmodified", "error", "timeout", or
"parsererror"). This is an Ajax Event.

Resources