Button Not Working Without Refreshing Page - c#

I am building a website with some simple functions and I'm running into some issues. I can't provided any sample code because I have no idea where the problem lies and technically the site is not crashing.
The frontend of the site is html and javascript, the backend I'm using ASP.Net and C#.
There's a button on the page, which will trigger a function in javascript. The function will then make a call to the backend aspx file (say, myFunction.aspx) and generate a output file for the user to download.
Everything is working just fine. I was getting the expected result and was able to download the output file with no problem.
I didn't notice the issue until I try to re-run this function.
I hit the button again but it wasn't doing anything (I was also using Httpfox so I know it's not calling anything)
I realize that I wasn't able to run the function again without refreshing the page. After refreshing the page it works just fine.
Can anyone explain why its this way? How can I go about debugging this issue? I don't even know if the problem is with the fontend or the backend.
Thanks for the help.
EDIT
This is how I created the button.
<button dojoType="dijit.form.Button" type="button" onclick ="myJSFunction('uploadForm')">Generate</button>
and this is how the function is calling the asp backend
var myJSFunction= function (formId) {
dojo.io.iframe.send
({
url: 'myURL/myFunction.aspx?parameter=p',
form: dojo.byId(formId),
method: "POST",
handleAs: "text",
load: function (response, ioArgs) {
dojo.byId("timeStamp").value = response;
}
error: function (response, ioArgs) {
alert("Failure:" + response);
}
});
}
EDIT 2
I just notice something interesting.
I have been running in Firefox using HttpFox and was not getting any error message. Then I tried to run it in Chrome using F12 and I'm getting red alerts.
In Chrome, under the Network tab, the status says "canceled", but I was still getting the output.
How could this happen? How can I find where the issue is?

Check your javascript console to see that you don't have any errors on the page. Otherwise post your asp.net markup for the button and the javascript function.
Edit:
Try returning false from your javascript function. This will prevent the default browser behavior from executing (What's the effect of adding 'return false' to a click event listener?)

A workaround might be to unnbind and then rebind the click event on your element so every click is effectively the "first", to avoid anything that dojo or something else may be doing out of your control. I don't know dojo, but based on http://dojotoolkit.org/reference-guide/1.9/dojo/on.html#dojo-on the following should be about right:
var updateHandle;
var myJSFunction= function (formId) {
updateHandle.remove();
dojo.io.iframe.send
({
url: 'myURL/myFunction.aspx?parameter=p',
form: dojo.byId(formId),
method: "POST",
handleAs: "text",
load: function (response, ioArgs) {
dojo.byId("timeStamp").value = response;
updateHandle = on(your.buttonElement, "click", function(){
myJSFunction(formId);
});
}
error: function (response, ioArgs) {
alert("Failure:" + response);
}
});
}
updateHandle = on(your.buttonElement, "click", function(){
myJSFunction("myFormId");
});

Thank you all for the help and suggestion.
I have found the solution to the issue. All I need is a single line to the frontend code.
dojo.io.iframe._currentDfd = null; //add this line
dojo.io.iframe.send
({...
});
Thanks for the help.

Related

Call C# function from Javascript in aspx webform and then reload page

Trying to figure out how to call a c# function in a webform. I tried both ajax and windows.location but could just be off on my path. Trying to send it my c# code at SpeakerList.aspx/update and then gonna attach two variables i have in javascript which shouldnt be too bad. But want it to hit the C# function then reload the page so hoping there is just an easy call im missing.
buttons: {
"Save": function () {
var combo = ASPxClientControl.GetControlCollection().GetByName('DropDownList1');
var value = combo.GetSelectedItem().value;
var billID = $("#billID").val();
window.location = "SpeakerList.aspx/updateRec";
}
You might want to try using WebMethods:
http://aspalliance.com/1922_PageMethods_In_ASPNET_AJAX.all
This allows you to call a function in your page's code behind using JavaScript.
Assuming you are using MVC, you probably want to return a JSON result. An easy way to consume Json within your client webpage is using JQuery. You can return JSON as as the output of a webpage, but I don't recommend it. Create a separate service point that repesents the JSON method.
It is hard to tell what you are actually trying to accomplish, but the normal usage pattern for a JSON method is the supply the parameters as part of the querystring (which you can refactor with routing if you want). The result is then just a JSON packet.
Personally, I like JSON.Net for server side JSON, but you don't actually need this. Look up JSONMethod for examples, etc. that will show you how to do this.
From the browser client, JQuery has a json method, but I personally recommend using the more generic ajax method a JQuery so you can use the handlers for success, error and completion. E.g.
$.ajax({
url: "http:...",
data: queryparm,
cache:false,
timeout:15000,
success: function(data){
jresult = $.parseJSON(data);
...
},
error:function (xhr, ajaxOptions, thrownError)
{
setErrorMsg("Error getting search results: " + thrownError);
}
});
EDIT -- Actually, I've done this exact same thing with webforms too, code is essentially identically (if you use JSON.Net on the server side). You don't have the routing options to make the urls REST compliant, but as an internal json web service, you probably won't really care about that.
As a webpage (.aspx) page, you can use a "postback" this is the simplest method for a web form. You can always declare some hidden fields to use for data passing if you are not passing back a native "control" value. If you don't know how to do this, you need to read a tutorial on using web forms.

Simple ajax clock works in everything except for IE for some reason

Here is my simple ajax function:
var callback = function () {
$.ajax({
url: "/Home/Timer",
success: function (response) {
console.log(response); // Fails, but only in IE10
$("#target").html(response);
}
});
}
setInterval(callback, 1000);
and the Controller/Action:
public String Timer()
{
Debug.WriteLine(DateTime.Now.ToString()); // Shows correctly in all browsers
return DateTime.Now.ToString();
}
which works fine in Opera, Chrome, Firefox, but not IE10 for the weirdest reason. In every other browser, the console logs the current time but in IE10, it keeps logging the same time over and over again. I put a breakpoint on my Timer method, and it hits the method correctly, but somehow when it gets back to the success callback it reports the wrong time. Why would that happen?
cache maybe?
try setting cache:false in the ajax options
In safari and some older browsers, (from what I've experienced till now, cache:false doesnt seem to work sometimes). for a more cross browser compatible solution, you could add a data option to the ajax() call and add a random number generator as a parameter. It would be something like this.
var callback = function () {
$.ajax({
url: "/Home/Timer",
//start random number generator
data : { r: Math.random() }
//end random number generator
success: function (response) {
console.log(response); // Fails, but only in IE10
$("#target").html(response);
}
});
}
This way, everytime a server call happens, a new random number will be generated, and since the data is different from the previous requests, ajax requests wont be cached and will ensure a fresh server call every single time.
edit under package and set cache:false in your CSS and call each intermediate function under main class

#Url.Action inside $.get

I've seen a few posts about this but stills couldn't understand why this is not working
$.get('#Url.Action("Edit","Contacts")', {id: parseInt($(this).attr('id')) } , function (result) {
obviously this does
$.get("/Contacts/Edit/" + parseInt($(this).attr('id')), function (result) {
I've tried with replacements and still getting the proper id but the #Url.Actions appears as a string itself generating weird routes as this one for the former code, seems to me that the url.action is not executed, right?
localhost:53720/#Url.Action(Edit,%20Contacts)?id=23918
Edition: Actually the route generated for that code is
localhost:53720/Url.Action(%22Edit%22,%20%22Contacts%22)?id=23918
the other is for another try I've made
Anyone can tell me why?
Thanks
To have access to HtmlHelpers inside javascript, the javascript code must be inside a View page, and not inside a javascript file
<script>
var url = '#Url.Action("Edit","Contacts")';
console.log(url);
</script>
Looks like #Url.Action is not getting called and the URL is not being returned.
var url = '#Url.Action("Edit","Contacts")';
$.get(url, {id: parseInt($(this).attr('id')) } , function (result)
If JS complains about the above, you can try specifying #: beforehand to let razor take control.

c# Calling Server side method using JQuery

Im trying to call a server method in my aspx.cs to delete all the files in a directory when a user closes the browser.
[WebMethod]
public static void fileDelete()
{
string[] uploadedFiles = Directory.GetFiles(#"C:\Users\Lambo\Documents\Visual Studio 2010\Projects\test\test\testPdfIn");
foreach (string uploaded in uploadedFiles)
{
File.Delete(uploaded);
}
}
======================================================================
EDIT
I've tried the POST method but it still doesn't seem to work. I've changed the URL too.
Over at the client side im using this:
$(function () {
$(window).unload(function () {
alert("Files have been deleted")
jQuery.ajax({ type: 'POST', url: "http://localhost:19642/success.aspx/fileDelete", async: true });
});
});
However it doesnt seem to be working. Are the codes wrong in someway?
To investigate failures of AJAX calls use HTTP debugger (like Fiddler ) to see what requests are made and what responses are received.
My guess is that your Url is wrong and request is made to wrong file. Consider making absolute (or at lest server relative) url.

PageMethods in ASP.NET failed to work if you have ASP.NET Routing Implemented

I have a web method:
[System.Web.Services.WebMethod]
public static string getCharacterstics(int product_id, int lang_id)
{
// code goes here...
}
I want to access it using PageMethods like:
(Provided the condition that i have Enable PageMethods in ScriptManager):
<script type="text/javascript">
$(document).ready(
function () {
$('#characterstics').html("loading");
// '<%= product_id_property %>' , '<%= this.LanguageID %>'
PageMethods.getCharacterstics(0 ,0 , OnSave);
}
);
function OnSave(result) {
}
</script>
I get the error "the http verb post to access path.. is not allowed"
I googled it and search the SO too but does not get any solution regarding to it Based on ASP.NET Routing.
What i believe is that because of asp.net routing the service methods are not accessible.
In addition i think i cannot even use JSON because of asp.net routing too.
Any help is appreciated.
Updated:
If i run the page with this url:
http://localhost:2606/searchdetail.aspx
The web method executed successfully.
Now
I have routing like this:
routes.MapPageRoute("searchdetail", "searchdetail/{ID}", "~/searchdetail.aspx");
routes.MapPageRoute("searchdetail", "searchdetail", "~/searchdetail.aspx");
The set_path() will work only for case 2 i.e without ID but does not work with case 1
if i try
http://localhost:2606/searchdetail
It works fine
but if i try to use:
http://localhost:2606/searchdetail/123
It gives error that object expected.
So set_path() is the option what should i write.
Currently, WebMethods don't work transparently with the Routing framework. There is a work around. You have to access the PageMethods directly by doing the following in your javascript:
PageMethods.set_path('/the/path/to/your/page.aspx');
PageMethods.YourMethod(params, onSuccess, onFailure);
I hope this helps.
I kept running into this myself. With routing enabled, if I added a value to the path, it would start to fail again. This solution is a bit of a hack, but it seems to be working consistently.
Create a server control hyperlink where the navigate url refers to itself, then once the control renders, grab the href and use it for set_path
This gets around the issue of set_path not referring to the correct location if you called
<asp:HyperLink ID="hlPage" runat="server" NavigateUrl="~/user.aspx" ClientIDMode="Static"></asp:HyperLink>
<script>
$(document).ready(function () {PageMethods.set_path($('#hlPage').attr('href'));})
</script>

Categories