I'm playing with JQuery, and I'm trying to fire a Click event on a button, to run off to a handler in my asp.net application, and getting some strange results.
I'll post the code and then explain whats happening :-
$(function () {
$("[id$='btnClaimValidate']").click(callSwapClaimHandler);
function callSwapClaimHandler() {
$.ajax({
type: 'POST',
url: "/handlers/investor-tickets/claimswapvalidator.ashx",
data: {
investorId: $("[id$='hdnInvestor']").val(),
investorTicketId: $("[id$='hdnInvestorTicket']").val(),
originalClaimId: $("[id$='hdnInvestorTicketClaimId']").val(),
newClaimId: $("[id$='txtClaim']").val()
},
dataType: "html",
error: function () {
alert("failure");
},
success:
function (data) {
var $newdiv = data;
$("[id$='divMessageData']").append($newdiv);
}
});
}
});
With the code above, the handler is never called. The event is 100% being fired on click. I've tested by removing the ajax post function, and replaced it with a simple alert("Hello); command to be sure.
What is strange is that if i register the click event to actually execute on DOM load by doing this :-
$("[id$='btnClaimValidate']").click(callSwapClaimHandler());
The handler is fired as the page loads and then works as expected.
By taking off the parenthesis, so that it is only fired on click, the post never actually executes.
I've debugged the browser session, and the function runs, but it never gets to the handler, and no content is returned.
Can anyone explain what's going wrong?
Your comment to #Scarface Ron is the clue. Your page is refreshing as the default button behavior was not stopped. Also just use the function inline in the handler:
$(function () {
$("[id$='btnClaimValidate']").click(function (e) {
// Stop the button actioning!
e.preventDefault();
$.ajax({
type: 'POST',
url: "/handlers/investor-tickets/claimswapvalidator.ashx",
data: {
investorId: $("[id$='hdnInvestor']").val(),
investorTicketId: $("[id$='hdnInvestorTicket']").val(),
originalClaimId: $("[id$='hdnInvestorTicketClaimId']").val(),
newClaimId: $("[id$='txtClaim']").val()
},
dataType: "html",
error: function () {
alert("failure");
},
success:
function (data) {
var $newdiv = data;
$("[id$='divMessageData']").append($newdiv);
}
});
});
});
apologies if I got the closing braces wrong here
The simple explanation here is that your button selector - [id$='btnClaimValidate'] - isn't matching anything at the time it is executed. Hard to say why (you're generating that part of the DOM after the page is loaded? You have a typo?) but you can test this easily enough:
$(function()
{
alert($("[id$='btnClaimValidate']").length);
});
If the value is 0, then this is your problem and you'll have a specific area to investigate further.
Alternately, use your browser's DOM inspector to verify that an event has actually been attached to the button after the load has completed.
If the problem is simply that the button is added to the DOM after the page is loaded, then you might want to consider using a delegated event instead of attaching the handler directly to the button. For instance:
$("document").on("click", "[id$='btnClaimValidate']", callSwapClaimHandler);
This will attach the event to the document (which exists) but mandate that the handler is only called when the event has bubbled up from the button (which may not exist yet when the handler is bound, but probably will later).
Related
I have a element on my page that looks like this
<td><span class="badge badge-danger">Stopped</span></td>
and I want to update it based on things that are going on in the code.
Take this example.. I have a button and that element, and when I click that button I want to start downloading a list of names. Once it's started I want the text inside that span to say "Started" rather than "Stopped" and than once the code finished running aka the list of names has been downloaded, I want it to say "Done" rather than "Started"
And I've been reading back and forth about how to do this and it seems as if I need to implement ajax somehow and I'm not sure how to.
I guess the button would invoke a asp-action="StartDownload" and then it would look something like this..
public ActionResult StartDownload()
{
StartDownload();
return View("WhereSpanIs");
}
private void StartDownload()
{
//Set span text to "Started" some how
//Finished download
//Set span text to "Done" some how
}
For manipulating HTML in the browser when requested by a controller method as in your approach, you would need something like SignalR to enable communication between the server (i.e. controller) and client (i.e. browser).
As you already found out, it's easier using Ajax to update the text in this case (using JavaScript/JQuery). Like in the following example, you could set the text when the button has been clicked, and when the request is complete:
In the view:
<script type="text/javascript">
// call this method on button click
function startDownload() {
// loading, TODO: update the text)
$.ajax({
type: "GET",
url: '#Url.Action("StartDownload", "Home")',
contentType: "application/json; charset=utf-8",
success: function(data) {/* done, TODO: update the text */ },
error: function() { /* error, TODO: update the text }
});
}
</script>
In the (Home) controller:
public ActionResult StartDownload()
{
// TODO: perform the download
return Json(new {status = "OK"});
}
JSON is used to allow the result to be interpretable in JavaScript, although it is not used in this example.
See the Shopping Cart Tutorial for further information.
How can I show a loading Gif animation by using a jquery in asp.net project in Main.Master page? Whenever its taking time, I would like to show this Gif.
I searched on internet but they are showing this loading images for one control only. Thats why i need to keep this jquery at one place (ie: in master page) and want too use it on all content page whenever its taking too much time to load the page (either first time the page loads or button clicked or any event taking time)
$.ajax({
type: "POST",
url: "~/Jobs/ExportJobEntry.aspx",
data: dataString,
beforeSend: loadStart,
complete: loadStop,
success: function() {
$('#form').html("<div id='msg'></div>");
$('#msg').html("Thank you for your email. I will respond within 24 hours. Please reload the page to send another email.")
},
error: function() {
$('#form').html("<div id='msg'></div>");
$('#msg').html("Please accept my apologies. I've been unable to send your email. Reload the page to try again.")
}
return False);
});
$(document).ready(function () {
$(document).ajaxStart(function () {
$("#loading").show();
}).ajaxStop(function () {
$("#loading").hide();
});
});
I used this code but it is not working
You can use jQuery BlockUI plugin. Here is official website, please read documentation
http://malsup.com/jquery/block/
You can do it like this
$(document)
.ajaxStart(function () {
$loading.show();
})
.ajaxStop(function () {
$loading.hide();
});
Then you can define $loading how ever you want
I use an Ajax Toolkit modal pop-up extender to pop-up a form for collecting information from the user. I intend to send the data collected from the user to the code behind for saving into the database on click of the submit button on that form. I found out, however, that the submit button is not posting back to the saver at all.
I do not want to use any client side coding or a web service.
Is it in any way possible to do post back on a modal pop?
There are two solutions of your problem:
Create form with asp:button in a div, initially set it's display none. At the time of popup just make it visible you can set it's position as your requirement. Then after click on submit button it will behave normally and redirect your page.
It is by using jQuery and Ajax. Create a html form and on submit call a JavaScript function
JavaScript function :-
function on_submit(){
var pageUrl = 'your_page_name.aspx'
$.ajax({
type: "POST",
url: pageUrl + "/your_web_method",
data: '{data1:value1, data2:value2}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
make your success code here
}
});
in C#
[WebMethod]
public static void your_web_method(data1, data2)
{
// your code to store value in database
}
Kindly help me to call a non-static method from code behind, using json object.
The following code is used in aspx page:
function columnDropdownScript() {
if (id == "ExpressionsLink") {
var dropdown = document.getElementById("<%=ddlTableNames.ClientID%>");
}
/
/ Configure AJAX call to server on itemChange of ddlTableNames
$.ajax({
type: "POST",
url: "Webtop.aspx/FillColumnDropdown",
data: requestTableParameters,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (id == "ExpressionsLink") {
$("#ddlColumnNames").empty();
}
}
// alert('Check Column DropDown' + msg.d.length);
},
error: DisplayError //Event that'll be fired on Error
});
}
The following code is written in aspx.cs page
[WebMethod]
public static List<string> FillColumnDropdown(string selTableName)
{
//Code to update Selected Columns in table
}
Since you want to call page's instance method I believe that you want to use other page's controls properties or features provided by an ASP.NET platform like ViewState or some other. But when you fire plain ajax request you can't use any of that possibilities.
So the only one option for you to use ASP.NET Ajax. In that case page comes through full life cycle including recreation all page's controls instances on the server, reading ViewState and so on.
Mostly for using ASP.NET you don't need any custom javascript calls because all required javascript provided out of the box.
What do you need it's just add ScriptManager and UpdatePanel controls onto the page, put your dropdown in UpdatePanel and set AutoPostback on it to true. That's all. After that you can use server-side SelectedIndexChanged event habdler of that dropdownlist and it will be fired asynchronously.
For more info about using an UpdatePanel follow this link: Introduction to the UpdatePanel Control
EDIT: by the way: if you need only the Session or Application state or Cache but no page's controls properties and no ViewState you still can use plain ajax calls and static server methods.
Actually the AJAX is quite tricky thing :)
When load the new html from a post function I lose all of my click bindings. I read that i could use live to keep all the bindings but can't find any examples where live is used with post. Here is my code:
$('.GroupHeader').unbind('click').live('click', function (event) {
event.preventDefault();
TemplateEditor.SelectGroupClicked($(this));
});
You should use live to bind your click event handlers, i.e.:
$(selector).live('click', function () {
//...
});
Instead of :
$(selector).click(function () { // or $(selector).bind('click', ...
//...
});
In that way, doesn't matter your elements are replaced, the events will still work, because live works with event delegation.