Ajax call after postback in jquery function in mvc3 - asp.net-mvc-3

I am having problem for Ajax call from Jquery function after postback in mvc3. The action method mentioned in the ajax section below doesn't get called after postback whereas it works fine before postback.
actually I am trying to get value for textbox. here is my Jquery function..
$("#ddlDiagnosis").change(function () {
alert($("#ddlDiagnosis").val());
var selection = $("#ddlDiagnosis").val();
var datatosend = { selectedValue: selection };
$.ajax({
url: "home/GetDiagnosisICDCode",
type: 'POST',
data: { selectedValue: $(this).val() }, //datatosend,
datatype: 'json',
success: function (data) {
var elements = "";
$.each(data, function () {
$("#txtICDCode").val(this.ICDcode)
})
}
});
});

You need to change URL like this
url: "/home/GetDiagnosisICDCode",
and GetDiagnosisICDCode must be public method.

You cannot force to make ajax calls after a postback as the state of the page is changing after the full postback. So it wont happen. The function which is containing the ajax call should be executed to make the ajax request. For this you may use jquery's $(document).ready(function(){});Encapsulate your method using jquery's Initialization function. In a sequence, say you can make an ajax call first then you can make a full postback. But the reverse is not possible by maintaining the state of the page.

Related

Jquery inside Ajax loaded page does not work

When I use
$('body').html(data1)
or
$('html').html(data1)
in AJAX, then any HTML tag or jQuery function does not work on the loaded page.
$.ajax({
type:"GET",
dataType: 'html',
url: 'hell.php',
success : function(data1) {
alert(data1);// will alert "ok"
$('body').html(data1);
},
});
The events you attached before $('body').html(data1) will not fire simply because the elements previously in the body will not exist anymore.
You have to re-attach the events or use .on() method and attach events directly to document.
better use jQuery live function, when attaching event handlers.
See: http://api.jquery.com/live/
First, define the functionality you want to attach to the loaded elements in a function, e.g.:
function attachEventsAfterAjax(){
$('.aLoadedElement').on('click', function(){
console.log('Yay!');
return false;
});
}
Then, after you've loaded your new content, call that function, e.g.:
$.ajax({
[...],
success: function(data){
// Don't replace the <body> HTML, that's not a good idea
// $('body').html(data);
$('#container').html(data);
// Now attach the functionality!
attachEventsAfterAjax();
}
});

reload page when clicking on current page link, using jQuery Address plugin

I am using jQuery Address plugin, and all my ajax navigation is based on it, and more precisely on internalChange or externalChange events like that
$(document).ready(function() {
initDeepLinking();
});
function linkClicked(e){
var request = $.ajax({
url: e.path,
data: e.queryString,
type: "GET",
dataType: "json",
});
request.done(handleResponse);
return false;
}
function handleResponse(response, textStatus, jqXHR){
$('#main').html(response.responseText);
};
function initDeepLinking(){
$.address.internalChange(function(event){
linkClicked(event);
});
$.address.externalChange(function(event){
linkClicked(event);
});
}
so when i click on a link leading to the current page, nothing happens.
I would like the page to reload when I do that. Any simple options ?
Thanks !
I am having troubles understanding what your question really is:
you don't know how to attach a handler to the link
you don't know what statement can be used to refresh the current page
In order to set a handler you can use some selector. For example, getting the element by class. More about jquery selectors here.
After you have the element, you can attach an event handler for the 'on click' event and do something like this:
window.location.reload(true);

jQuery Mobile transitions and AJAX Polling on a MasterPage

I am trying to use AJAX polling with jQuery to update a span element on a razor MasterPage in ASP.NET MVC3. The page uses the jQuery Mobile 1.0 framework that adorns simple view changes (like navigating from /home to /about) with some sort of "transition" animation.
This is the Javascript code that does the polling, while the "unreadBubble" span is located in the body - both are defined in the MasterPage!
<script type="text/javascript">
$(document).bind("pageinit", function poll() {
setTimeout(function () {
$.ajax({ url: "/Notification/GetUnreadNotificationsCount",
dataType: "json",
success: function (data) {
$('#unreadBubble').text(data.UnreadCount);
poll();
}
});
}, 1000);
});
So, imagine I have a HomeController and a NotificationController that both use the MasterPage and provide an Index view. The AJAX polling works on both views and updates the span every second as expected. As soon as I navigate from one view to another though, the span gets re-initialized with its default value from the MasterPage (empty) and doesn't update anymore. Interestingly the async GetUnreadNotificationsCount method is still called on the NotificationsController repeatedly - the span just doesn't update. I also tried to alert the span tag in JS and it wasn't null or something.
According to the documentation, jQuery Mobile also loads new pages with AJAX to insert this fancy "SWOOSH" transition animation. This seems to somehow disturb the JS/DOM initialization.
Do you have any idea how to resolve this? Should I bind to another event or can I somehow force the span tag to update?
Solution: It was a caching problem! The following did the trick:
Add class="command-no-cache" to your page div add the following JavaScript to the MasterPage:
$(":jqmData(role=page)").live('pagehide', function (event, ui) {
if ($(this).children("div[data-role*='content']").is(".command-no-cache"))
$(this).remove();
});
I would use the pagebeforeshow to actually bind the event, and pagehide to remove the event.
Did you try that instead of initializing only once in the pageinit event?
UPDATE: some code for example,
<script type="text/javascript">
var timer = null;
$(":jqmData(role=page)").bind("pagebeforeshow", function() {
timer = setTimeout(function() {
$.ajax({ url: "/Notification/GetUnreadNotificationsCount",
dataType: "json",
success: function (data) {
$('#unreadBubble').text(data.UnreadCount);
}
});
}, 1000);
});
$(":jqmData(role=page)").bind("pagehide", function() {
if (timer != null){
clearTimeout(timer);
timer = null;
}
});
</script>
Also corrected some other ""mistypes" along the way, have a look and compare to your code!
Hope this helps

Jquery AJAX: How to Change button value on "success"?

I have multiple buttons on one page. Upon click, I track the button id, send the button value to backend php code that returns me updated value by changing the database. I am able to get back everything i need except this: Setting the button value on success!! This is the code i'm using:
$(document).ready(function(){
$("input[type='button']").click(function(){
var selected = $(this).attr("id");
var val = prompt("Enter new value",0);
$.ajax({
url:'updateCostItems.php',
data:{toupdate:selected, updatewith:val},
type:'GET',
dataType:'json',
success:function(json){
$(this).val(json.update);
},
error:function(xhr, status){
alert("Problem");
},
complete:function(xhr, status){
}
});
});
});
I think this is not correct, because the callback is run in the global scope.
Untested, but try just before $.ajax to write var $this = $(this) and then in your callback use $this.val(json.update)
Edit: Updated code snippet to ensure local $this by declaring with var. Other posts suggest using var button = $(this) which is probably better in bigger projects where keeping track of the variables is more challenging - but all the answers are the same really.
The problem is that 'this', inside the ajax request, points to the xhr object, not the button. You should store the reference to the button prior to do the call, like var button = $(this); and later updating it button.val(json.update);
Store the button in a local variable in the outer loop, then refer to that variable in the inner scope of the success handler:
$(document).ready(function(){
$("input[type='button']").click(function(){
var $btn = $(this)
var selected = $btn.attr("id");
var val = prompt("Enter new value",0);
$.ajax({
url:'updateCostItems.php',
data:{toupdate:selected, updatewith:val},
type:'GET',
dataType:'json',
success:function(json){
$btn.val(json.update);
},
error:function(xhr, status){
alert("Problem");
},
});
});
});
$(this) will not refer to the button at the time the success function is called. You will need to pass the button (or the button's id) along as a parameter to your callback. Storing a single global variable is not sufficient since you could potentially click on a 2nd button before the first ajax call returns.

Regular form post/redirect for submit button with Jquery submits for other inputs (validation)

I have a form where I'm using Jquery to submit the form to create a preview output on the right-hand side of my screen (I have some complex inputs and want to use ruby to process them to create the preview).
After the user has completed the form and presses the submit button, I want the form to submit normally (i.e., as if Jquery is not being used). Is there any way of doing this?
I feel like the answer to this is probably really simple and I'm just completely missing something.
Here's how I'm submitting a select button (for validation)
$('#body_message select').change(function() {
$('form').submit();
});
Here's my current code for handling the submit button. When the user clicks the submit button, I change the value of a hidden field with id "message_submit_button" so this submit will be handled differently from the validation submits.
$('#body_message input[type="submit"]').click(function() {
$('#body_message #message_submit_button').val("1");
$('form').submit(function(){
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: XMLHttpRequest.getResponseHeader("Location"),
dataType: "html"
});
return false;
});
});
EDITED:
Using the first part of the answer, I've changed the Jquery on my submit button to the following, and it works as desired:
$('#body_message input[type="submit"]').click(function() {
$('#message_submit_button').val("1");
$('form')[0].submit();
});
You can bypass the jQuery .submit() handler by calling the native form.submit() function, like this:
$('form')[0].submit();
I would change it like this:
$('#body_message input[type="submit"]').click(function() {
$('#message_submit_button').val("1");
var form = $(this).closest("form")
$.ajax({
type: 'POST',
url: form.attr('action'),
data: form.serialize(),
success: XMLHttpRequest.getResponseHeader("Location"),
dataType: "html"
});
return false;
});
Then in your other buttons when submitting...just do nothing and it'll submit normally, that way this handler handles only this submit button, not the other that should do a normal submission.

Resources