ajaxSubmit and Other Code. Can someone help me determine what this code is doing? - asp.net

I've inherited some code that I need to debug. It isn't working at present. My task is to get it to work. No other requirements have been given to me. No, this isn't homework, this is a maintenance nightmare job.
ASP.Net (Framework 3.5), C#, jQuery 1.4.2. This project makes heavy use of jQuery and AJAX. There is a drop down on a page that, when an item is chosen, is supposed to add that item (it's a user) to an object in the database.
To accomplish this, the previous programmer first, on page load, dynamically loads the entire page through AJAX. To do this, he's got 5 div's, and each one is loaded from a jQuery call to a different full page in the website.
Somehow, the HTML and BODY and all the other stuff is stripped out and the contents of the div are loaded with the content of the aspx page. Which seems incredibly wrong to me since it relies on the browser to magically strip out html, head, body, form tags and merge with the existing html head body form tags.
Also, as the "content" page is returned as a string, the previous programmer has this code running on it before it is appended to the div:
function CleanupResponseText(responseText, uniqueName) {
responseText = responseText.replace("theForm.submit();", "SubmitSubForm(theForm, $(theForm).parent());");
responseText = responseText.replace(new RegExp("theForm", "g"), uniqueName);
responseText = responseText.replace(new RegExp("doPostBack", "g"), "doPostBack" + uniqueName);
return responseText;
}
When the dropdown itself fires it's onchange event, here is the code that gets fired:
function SubmitSubForm(form, container) {
//ShowLoading(container);
$(form).ajaxSubmit( {
url: $(form).attr("action"),
success: function(responseText) {
$(container).html(CleanupResponseText(responseText, form.id));
$("form", container).css("margin-top", "0").css("padding-top", "0");
//HideLoading(container);
}
}
);
}
This blows up in IE, with the message that "Microsoft JScript runtime error: Object doesn't support this property or method" -- which, I think, has to be that $(form).ajaxSubmit method doesn't exist.
What is this code really trying to do? I am so turned around right now that I think my only option is to scrap everything and start over. But I'd rather not do that unless necessary.
Is this code good? Is it working against .Net, and is that why we are having issues?

A google search for
jquery ajax submit
reveals the jQuery Form Plugin. Given that, is that file included on your page where the other code will have access to the method? Does this code work in Firefox and not IE?

Seems like there was too much jQuery fun going on. I completely reworked the entire code block since it was poorly designed in the first place.

Related

How to wait until HTML file loads?

In a page I am working on I replace the HTML code in a DIV with different HTML, then using Javascript I insert additional HTML into a DIV the new code using innerHTML.
If that is confusing, the original HTML contained a form, the HTML that replaced it contains the response to the form's Submit, and the code I want to insert is the information from the form.
This seemed to work as long as I had alert code in the script, which I use to check the progress as I debug this. Once I removed the all of alert lines the insert would fail. I figure it has to do something with the asynchronous nature of page rendering, so I think I need to find a way to make sure the new HTML code has loaded before I try writing to the DIV it contains.
In the code below the script fails at show_member_info unless I uncomment the preceding alert line.
function handle_join(X)
{
do_trace('handle_update');
get_member_info();
send_emails(X);
do_trace('clear content');
document.getElementById("members_content").innerHTML='';
document.getElementById("members_image").innerHTML='';
do_trace('load content');
Load_HTML('members/joinConf.html','members_content');
// alert('show_member_info');
show_member_info();
show_trace();
}
How do I determine when the new HTML has loaded and is ready to be manipulated?
Thanks, Mike
The question is a bit dry, but from what i can understand the problem is that you are not awaiting Load_HTML and that's causing some issue with show_member_info.

FlowRouter without page reload

I am following this example https://kadira.io/academy/meteor-routing-guide/content/rendering-blaze-templates
When I click on my links the whole page is being reloaded. Is there any way to load only the template part that is needed and not the whole page?
Edit: Also I noted another problem. Everything that is outside {{> Template.dynamic}} is being rendered twice.
Here is my project sample. https://github.com/hayk94/UbMvp/tree/routing
EDIT: Putting the contents in the mainLayout template and starting the rendering from there fixed the double render problems. However the reload problems happen because of this code
Template.mainLayout.events({
"click *": function(event, template){
event.stopPropagation();
console.log('body all click log');
// console.log(c0nnIp);
var clickedOne = $(event.target).html().toString();
console.log('This click ' + clickedOne);
//getting the connID
var clientIp = null // headers.getClientIP(); // no need for this anymore
var clientConnId = Meteor.connection._lastSessionId;
console.log(clientIp);
console.log(clientConnId);
Meteor.call("updateDB", {clientIp,clientConnId,clickedOne}, function(error, result){
if(error){
console.log("error", error);
}
if(result){
}
});
}, // click *
});//events
Without this event attached to the template the routing works without any reloads, however as soon as I attach it the problem persists.
Do you have any ideas why this code causes such problems?
EDIT 2 following question Rev 3:
event.stopPropagation() on "click *" event probably prevents the router from intercepting the click on link.
Then your browser performs the default behaviour, i.e. navigates to that link, reloading the whole page.
EDIT following question Rev 2:
Not sure you can directly use your body as BlazeLayout target layout.
Notice in the first code sample of BlazeLayout Usage that they use an actual template as layout (<template name="layout1">), targeted in JS as BlazeLayout.render('layout1', {});.
In the tutorial you mention, they similarly use <template name="mainLayout">.
That layout template is then appended to your page's body and filled accordingly. You can also change the placeholder for that layout with BlazeLayout.setRoot() by the way.
But strange things may happen if you try to directly target the body? In particular, that may explain why you have content rendered twice.
Original answer:
If your page is actually reloaded, then your router might not be configured properly, as your link is not being intercepted and your browser makes you actually navigate to that page. In that case, we would need to see your actual code if you need further help.
In case your page does not actually reload, but only your whole content is changed (whereas you wanted to change just a part of it), then you should make sure you properly point your dynamic templates.
You can refer to kadira:blaze-layout package doc to see how you set up different dynamic template targets in your layout, and how you can change each of them separately (or several of them simultaneously).
You should have something similar in case you use kadira:react-layout package.

DefaultButton and DefaultFocus in Internet Explorer 11

I have an ASP.NET page that contains an iframe. Inside that iframe, there is a form with a DefaultFocus and a DefaultButton set, as shown below.
<form id="Form1" method="post" runat="server" defaultfocus="txtSearchPhrase" defaultbutton="btnSearch">
When viewing this page in IE11, all of the content inside of the iframe appears to be shifted off the left side of the screen by about 100px or so. This does not happen in any other browser, including IE10.
If I remove the DefaultButton and DefaultFocus from the form, the problem disappears. I can then use Javascript to manually hookup the default button and focus, but since I have many different pages that are potentially rendered inside the iframe, it's not ideal to have to change each and every one of those pages.
Does anyone know what's causing this or if there's a better way to address it?
I looked into this and found some interesting things.
First, when you include DefaultFocus or DefaultButton on a form in ASP .NET WebForms, ASP .NET will automatically emit two things:
The definition of a WebForm_AutoFocus method.
A call to this method, which looks something like: WebForm_AutoFocus('defaultFocusElementID'); It does this for both DefaultFocus and DefaultButton settings, though I'm not sure why it needs to do this for the DefaultButton setting.
The WebForm_AutoFocus method attempts to call the scrollIntoView method on the element, but only if the browser is detected as a "non MS DOM" browser. Strangely enough, IE11 is not considered an MS DOM browser, at least as far as this method is concerned. So the scrollIntoView method is designed to run on browsers which are not IE.
I suppose one could argue the bug is with the implementation of the scrollIntoView method in IE11, but it could also be viewed as a bug in the MS JS library which detects whether the browser is an MS DOM browser. I'm not sure - either way, I blame Microsoft. :)
I recommend not using DefaultFocus and DefaultButton from a philosophical perspective because these are Microsoft-specific things, and when you can keep your code away from Microsoft-specific things, you usually should. Especially when using the "Microsoft way" is totally broken. Rather, try something like this (if you're using jQuery):
<form data-defaultfocus="search">
<asp:TextBox ID="search" />
</form>
<script type="text/javascript">
// jQuery on document ready
$(function() {
var form = $('form'),
defaultButtonID,
defaultFocusID;
if (form.data('defaultfocus')) {
defaultFocusID = form.data('defaultfocus');
$('#' + defaultFocusID).focus();
}
if (form.data('defaultbutton')) {
defaultButtonID = form.data('defaultbutton');
form.on('keypress', function(event) {
if (event.keyCode === 13) {
__doPostBack(defaultButtonID, '');
}
});
}
});
</script>
This is not tested code, but you get the idea. Then you can go through and use data-defaultbutton and data-defaultfocus on your form elements instead of the Microsofty way of doing it, and it will actually work, and if it doesn't, you can fix it, because you control the code!
I hope this helps.
Update
I found this Microsoft KB article which discusses a .NET 4 patch. Issue 2 on this page appears to address an issue which might be the one you described.
When you access an ASP.NET-based webpage by using Internet Explorer 11, the webpage renders the content incorrectly.
Note This issue occurs because Internet Explorer 11 is not recognized as Internet Explorer by ASP.NET.
I haven't tried it out yet, but it seems like this would fix it.

jquery .load( ) and trigger function AFTER new content loads? just like JavaScript onload event

Using jquery, I am swapping some content in a web page by use of jquery's .load() function. I want to trigger an event immediately once the content has actually been loaded, but not before and not after. I'm up for any graceful solution! Why? In this instance, I'm doing the old "fade out, swap content, fade in" approach. My problem? I want to fade back in AS SOON AS the new content is loaded.
Caveats:
Using a callback function as in $('#object').load(url, callback) triggers as soon as .load() function successfully executes (before the content is actually loaded). Useless here.
Using a timed delay for fading back in is not a graceful solution. Very "clunky", especially for those with faster Internet connectivity.
JavaScript's onload event trigger does not work, as the element that .load() is altering has already loaded into the HTML DOM.
jquery's .ready() function also does not work, as the actual element is already loaded.
I do not want to create an onload or .ready() sub-container element, because that's a workaround for what I'm actually trying, though it might be as graceful or more.
How can I fire a function when (and only when) the new .load() content is finally loaded, just like JavaScript's onload event does? Thanks much.
EDIT As it turns out, the jquery .load() function is working flawlessly, and I'm approaching this wrong.
Once the .load() function completes successfully, it calls any "callback" function included by the programmer, just like any other jquery function that accepts a callback as one of its "arguments".
The .load() function is complete once it either errors or successfully begins the HTML replacement and loading of new content, but that is IT! The content will then take however long it takes to load, but your .load call is already complete before that. Therefore, expecting the callback to run after the .load content has loaded will only disappoint you. ;)
I hope others can learn from this just as I did, including those who thought what I thought was the case. Proof: as stated in the jquery ajax .load page, the callback is executed when the request completes, not when the load completes. Eureka. Whoops. /EDIT
Try using a different method rather than load(), I would suggesting using get(). Something like this may be more useful to you...
var jqxhr = jQuery.get(url,vars);
jqxhr.success(function(data){
# This will only be called once the remote content has been loaded in
# The data will then be stored in the data param and can be used within your site
});
jqxhr.error(function(data){
# Something went wrong, never mind lets just handle it gracefully below...
});
I hope this is a solution to your problem!
For more information see http://api.jquery.com/jQuery.get/
I have quickly created this function below that may be of help to you... its not refined!
jQuery.fn.loadNewData = function() {
var object = jQuery(this);
var jqxhr = jQuery.get(arguments[0]);
// check for success
jqxhr.success(function(data) {
// load the data in
object.html(data);
});
jqxhr.error(function(){
alert('Failed to load data');
});
}
Using this you can call how similarly to how you would call the load() function.
jQuery('#object').loadNewData(url);
I think you might be misinterpreting what you are seeing. Depending on the browser you are using you won't see the new elements in the browser if you pop up an alert in the callback because it won't rerender the DOM until you cede control back to the browser. That doesn't mean you can't grab the new elements from the DOM and start fading them in. Take the following jsfiddle: http://jsfiddle.net/ttb55/8/ in Chrome it will show the first div when the second alert is up, then fade in the second div. In IE it won't show the first div when the second alert is up, this is the state I think you are in after load during the callback, but it still works once you hit ok because everything was in the DOM as promised.
Upon reading the jQuery docs pages for jQuery.get() and jQuery.load(), the callback argument is quoted as the following:
"A callback function that is executed if the request succeeds."
Let me stress the terms "request" and "succeeds". The request may succeed, but that does not mean that the content is loaded. Same problem as .load() — the functions aren't built the way I was thinking.
If I want to trigger an event once the new content finally loads, I'll need to take a different approach.
I could use the JS onload event, and trigger it by completely replacing an HTML element (having the replaced code contain an onload property). EDIT: Note that using HTML iframe elements is pretty awful, primitive, and "clunky". I just need to find a better way to trigger a function as soon as loading the new content finishes.
Also, I could use jQuery to check the .ready() state of new content, but ("AFAIK" / as far as I know) that will only work if the checked content is a new HTML element, not a preexisting HTML element whose interior content is changed. The jQuery .ready() status of any preexisting element will (AFAIK) already be shown as "ready" despite if new content is loading. Perhaps I am wrong about this, and I would like to be corrected if so.
Unless otherwise notified, this answer will be marked as the correct one. The original question was mistaken that .load() was all I needed. Cheers!

Asp.net and JavaScript pop up windows

I am writing an intranet application and am considering the use of a pop up window. I am not worried about accessibility since it's an intranet app.
The scenario is such as I need to be able to have the same code be used in a server page as well as in the middle of a process; which is why I decided when using it in the middle of the process, it's best to have it as a pop up window to running out of the real estate on the screen.
Any thoughts on this? I am hesitant to use a pop up window in such a manner as I usually only use it for error messages.
I don't completely understand what you're trying to do, but I think a popup window might be somewhat of an issue if the user's browser automatically blocks popup windows. Plus, if you were trying to run a process in the popup window, the user could close it and no longer have a way to check on the process.
Would it be possible to use Ajax to call back to a web service that gives the page information about the process? You could give the user a way to make the Ajax call to check on the status of the process or just have it continually polling in the background.
Edit:
You said you weren't too familiar with Ajax. For the most part, there are libraries to handle all the of hard details. I'll recommend jQuery because that's what I've been using for a while now.
If you go the Ajax route you'll be able to contain everything on one page and make the updates you need to make when the Ajax call is successful. Depending on how you write the code, it should be pretty reusable if you do it right. It really depends on how specific the your needs on each page.
Take a look at the jQuery documentation though. It may have what you need already built into it. Otherwise, someone else might be able to suggest some reasons why their favorite JavaScript library works better for what you're trying to do.
I think you might want to do something like this:
Inside of the parent page:
<input id="btnShowModal" runat="server" type="button" value='Show Modal' onclick="ShowModal()" />
function ShowModal()
{
var retVal = window.showModalDialog("MyPopup.aspx?param1=value","","center=yes;dialogWidth=200px;dialogHeight=200px;status:0;help:0")
if(retVal != "" && retVal != undefined)
{
//This code will be executed when the modal popup is closed, retVal will contain the value assigned to window.returnValue
}
}
Inside of the modal popup:
<input id="btnSave" runat="server" type="button" value='Save' onclick="Save()" />
function Save()
{
window.returnValue = "Whatever you want returned to the parent here"
window.close()
}
The usual argument against popup windows is that they are unreliable. The user may have disabled script initiated popups, I know I have.
In a controlled environment, such as an inranet, you may be able to be guaranteed that this is not the case, but even so, why risk it, there is an alternative.
Instead of popping up a new window just insert a new, absolutely positioned <div> into the document and insert your content into that using ajax or even an <iframe>. There are lots of examples/libraries on the web.
Thickbox for jQuery for example. There are of course scripts that don't require libraries.
I generally use a div with a z-index and absolute positioning; the .show() can be written and called on demand, it would have a button to .close(), and AJAX can make it seem modal so it must be clicked to close if you so desire. Then again, I hate messageboxes.
I was trying to avoid AJAX, simply because I have never used and don't have the time frame to learn it now. However, I am not totally opposed to it.
In short what I need to do is for the pop up window interact back with the page. Imagine that on the page I am building the links of the chain. Each link has unique properties. When user clicks on "ADD LINK" button, I was thinking have a pop up window with the little form and a Save button. The only issue with this is that a pop up needs to interact with the page; we need to know when something has been saved or not saved.
A div on the same page is one way. A pop up is yet another way. Another catch is that this code (adding new link) needs to be reusable, because I am also going to have a page that just creates new links.

Resources