Why is my javascript function not found by the page it is embedded in? - asp.net

I have a page that has a simple javascript in the header portion of the page:
<script type="text/javascript">
function doLogout() {
var conf = confirm("Really log out?");
if (conf === true) { //changed == to === for boolean comparison
$.post("logout.aspx");
}
}
</script>
It uses jQuery to do an AJAX post to my logout page. The only issue right now is that when I click on the link (logout) to fire this function, nothing happens. I checked FireBug's console, and it told me that the function is not defined. This has happened to me before, but I think I botched a bunch of code to fix it sometimes.
Does anyone know the proper way to fix this issue?
Edit
After doing a lot of googling and trying different things, I found this very concise and informative post. Apparently, as the linked article states, the way the script is referenced in the web site is important as it won't run properly otherwise! Hopefully this information will be useful for more people.

This can also occur if there is a syntax error earlier in your javascript code. Often this will just be interpreted as the function not existing (nor any function AFTER the error). Check the code above this code (if there is any) and this code for syntax errors.
A way to tell if the cache error is it is to open Firebug and view the Script source. If the page was cached, you won't see your code. If it loaded but has syntax errors, the code will show, though it won't "find" it.

Things to test:
1) Can you call this function from something else? Like add a <script> at the bottom of the page to call it?
2) Does the page validate? Sometimes I get screwy javascript errors if there is some busted HTML like a missing </b>
3) I've been starting to wrap my javascript in <![CDATA[ ]]> just incase I've got goofy chars in my javascript.
4) I assume you've tested this in other browsers and have the same behavior, right?
5) If you haven't installed it already, install the Web Developer firefox addon. It has a nifty toolbar menu that will disable the cache for you so everything reloads.
6) As weird as it sounds, I once hit a javascript issue that was because of how my text editor was saving UTF-8 files. I forget the details, but it was adding some byte-order-mark or something that upset the browser.

I've had this occur when the page had been cached and so it didn't load the new script in. So to fix it clear all private data from Firefox. Not sure if that helps but it sure happened to me a bunch.

Other ideas for you to test:
is the function defined in the DOM tab in FireBug?
if you call doLogout() from the FireBug console, what happens?
I assume this is not the only script on that page. Make sure that some later script is not modifying doLogout to something else

I had the same issue and tried all that's been suggested here without success.
The only way I fixed it was by discovering that in the <script src="jquery.js"> tag I was using in the head of the page I forgot to close it with its </script> causing the page to ignore all Javascript functions. So please check that your includes look like:
<script src="jquery.js"></script>
I hope that helps. Ross.

If you are using DevExpress controls these links may help you: How to register and execute a JavaScript downloaded to the client via a callback and How to register and execute a JavaScript downloaded to the client via a callback (standalone JS file) and Executing javascripts from user controls dynamically created through ASPxCallback panels

The issue might occur if you have NoScript. You should check and make sure it's not blocking said script.

I had this issue and discovered the problem was just a wrong case letter inside the name.
Call: filterCheckbox()
vs
function filterCheckBox() {}
problem: lowercase "box" vs uppercase "Box".
So check if the name is exactly the same.

Related

Contact Form 7 on_submit is not working

I am trying to show an alert when the form is submitted.
I added this code to "Additional Settings" on Contact Form 7 plugin (Version 4.2.2)
on_submit:"alert('Submitted');"
Nothing appears.
No errors nor warnings at console
No errors nor warnings at firebug
I guess no Javascript conflict since Contact Form 7 succesfully
sends emails
I am sure that form is "submitted" because i can see Contact
Form 7 form validation errors
Any ideas how to solve or debug further this issue?
It is not easy to take a guess without seeing the source code but I feel happy today.
Is your form working at all?
If not, it is probable that Contact Form 7’s JavaScript is not functioning on your site.
I’ll show you a few possible causes for this.
JavaScript file is not loaded
This is the cause that I’ve been seeing the most recently. This is due to your template, which is missing calling functions for queuing JavaScript. The functions required are wp_head() and wp_footer(), and they are in header.php and footer.php, respectively, in most correct themes.
Conflicts with other JavaScript
Many plugins and themes load their own JavaScript. Some of them may have been created incorrectly and therefore conflict with other plugins. In most cases, you can find JavaScript errors with Firebug, an add-on for Firefox, when such conflicts occur.
HTML structure is not valid
Like other JavaScript, Contact Form 7’s JavaScript traverses and manipulates the structure of HTML. Therefore, if the original HTML structure is not valid, it will fail to work. You can check whether your HTML is valid or not with an HTML validator. I recommend the W3C Markup Validation Service for use in such a case.
My advice is to use CF 7 default way of implementing your idea - we'll call it:
"1. Best option".
At WP Dashboard, go to Contact (CF7) and choose your form and go to the tab called "Additional Settings".
There, you can add similar code like this:
on_sent_ok: "alert('sent ok');"
on_submit: "alert('submit');"
If you set on_sent_ok: followed by a one-line JavaScript code, you can tell the contact form the code that should be performed when the mail is sent successfully. Likewise, with on_submit:, you can tell the code that should be performed when the form submitted regardless of the outcome.
On both of the actions, you can use every kind of JS code like you would in your .js file:
on_sent_ok: "some js code here"
You can use it to call functions like this:
on_sent_ok: "your_function();"
Or write some code (this one redirects to thank you page):
on_sent_ok: "document.location='/thank-you-page/';"
2. And another option is to handle it with jQuery:
Contact Form 7 is keen to emit a number of Javascript events that bubble up to the document object. In version 4.2 they can be found in contact-form-7/includes/js/scripts.js. If you're using jQuery you can access those events like this:
$(document).on('spam.wpcf7', function () {
console.log('submit.wpcf7 was triggered!');
});
$(document).on('invalid.wpcf7', function () {
console.log('invalid.wpcf7 was triggered!');
});
$(document).on('mailsent.wpcf7', function () {
console.log('mailsent.wpcf7 was triggered!');
});
$(document).on('mailfailed.wpcf7', function () {
console.log('mailfailed.wpcf7 was triggered!');
});
EDIT:
Some of these jQuery options are used but somehow deprecated so if you encounter problems, try using eg. 'wpcf7:mailsent' instead of 'mailsent.wpcf7'.
The same format goes for other option, actually all the options are observable in the mentioned file:
wp-content/plugins/contact-form-7/includes/js/script.js
do you have any link for us to further check this? It's pretty hard like this.
But: "I am sure that form is "submitted" because i can see Contact Form 7 form validation errors" -> is it server-validation or frontend-validation? Maybe it is NOT send?
All the best
I think something is blocking your popup.
Try debugging using "console.log", so you can eliminate this as a potential issue:
on_submit:"console.log('Submitted');"

Upgrading to new asynchrous Google Analytics code - should you do it?

I had read somewhere and have now forgotten that upgrading to the new asynchronous code will not enable one to track actual clicks for downloading items when user stays on the same page and that for tracking that you need to use the old version of GA code.
My question is, is that still the case and does anyone have any other reasons for not upgrading to use the newer asynchronous tracking?
thanks
Hmm...are you sure the "old" version of GA automatically tracked downloads? AFAIK GA never automatically tracked download links, that you always had to attach GA code (like a _trackEvent call) to your links yourself. But in any case, it's pretty easy to do it yourself, so it's really not a big deal. Plus, you get lots of benefits upgrading, and one day it may not even be an option to stick with the old version...
If you have jQuery you can for example do this:
// file types you want to consider a download
var downloadFileTypes = ['pdf','doc','docx','mp4'];
$(document).ready(function() {
$('a').filter(function() {
var ext = $(this).attr('href').split('.').pop().toLowerCase();
return ( $.inArray(ext, downloadFileTypes )>-1 );
})
.click(function() {
_gaq.push(['_trackEvent', 'Downloads', $(this).attr('href')]);
});
});
If you do not have a framework like jQuery, you can still do this easy enough with .getElementsByTagName() and using regular loops and conditions instead of the jQuery conveniences like .filter and .inArray
edit: Some things to note about that example:
the jQuery code was an example to hook the GA code to standard links pointing to the file types you specify in downloadFiletypes. It will only apply to links that exist at the time the code is executed. If you have links that may be dynamically generated on the page later, consider looking into .on() instead of .click()
you will need to make tweaks to matching links you want to consider downloads if they do not point to regular files with extensions. For instance, some websites have a controller script that expects a parameter with an ID and it dynamically serves up a pdf or whatever..if your files are like this, you will have to alter the logic to look for that instead.

ckeditor load html code in the editor asp.net

I am trying to load html file in CKEditor in asp.net but for some reason I don't know how to put the html code from the code behind file.
CKEditor1.FilebrowserBrowseUrl = url;
CKEditor1.BasePath = url;
CKEditor1.Text = content;
none of that helped
Any advice? Thanks in advance, Laziale
I'm not sure which version you are using, but let's suppose that it's 3.x. I was playing around with the control and didn't find any possible way of doing this from code behind. However, I managed to make it work like this:
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "fckInitialization", #"
window.onload = function () {
var oEditor = CKEDITOR.instances['" + txtPost.ClientID + #"'];
oEditor.insertHtml('<strong>This is a bold text.</strong>');
};
", true);
I tried it in IE 8 and the last version of Mozilla (I think it was 9) and it worked. I also tried the same thing, but instead of window.onload I used the jQuery $(document).ready() and it worked only in IE. The reason is that you have to wait for everything to load in order to use the functions from the CKEditor API. I played with Firebug and the insertHTML worked.
If you are using 2.x, you can see somewhere in Google the same approach, but with a different API. I just can't find the link right now.
Another problem will be here, as you may figure out, that if you want to initialize a long text, you will have to write everything in a script, which is not really nice.
Maybe a possible solution for you will be to convert the HTML to BBCode first and then just set the Text property. This, of course, depends on the way you use the control, because BBCode does not contain all possible tags, but you can always modify the bbcode plugin of CKEditor to meet your needs. And I tested it and it works.
PS. Probably you can do it with the JavaScript method and an AJAX call.
Hope this helps!
Assuming ckeditor is being initialized from a textarea field, you can simply populate the body of the textarea.

Chrome Extension: Communication iframe <-> Content Script

Well, a often discussed thing. But I can't get it work. What has to be done:
The Content or Background Script has to communicate with the iframe et vice versa.
The iframe is under my hand, so there is everything possible.
I tried a lot. It doesn't work at all. For instance: If I deploy the content script on every page with allFrames=true via (manifest). Ok, makes sense. The iframe is created later so the trigger won't be called. So let's do this: create the iframe and afterwards sending an executeScript request:
chrome.tabs.executeScript(tabinst.tab_id, { allFrames: true, file:'frame.js'}, function() {
console.log("done");
});
But that doesn't work either. Has anyone a solution to communicate with an XDM iframe and a chrome extension?
PS: How nice it would be if the chrome extension would allow postMessage on iframe
EDIT1:
The code doesn't get injected in the iframe. Scenario:
The file "file.js" has a simple foo function in it. I now apply it with the above statement 2 seconds after the iframe was created and showed. This function foo is not available in the iframe...but is in the content script. The ReferenceError is thrown by trying to execute foo within the iframe (by click).
So, it's not a timing thing. And it doesn't matter if I apply the Scripts via manifest and all_frames true. If that would work, the content_script would be available. But is not.
EDIT2:
#serg
Yeah, thanks, that works! I just got through it. My problem was, that I assumed that when the callback of chrome.tabs.executeScript is called, the requested script is ended and the including DOM manipulation finished. But that's actually not the case. It takes some time till the script in the iframe and the containing listener is ready.
So I had to send a chrome.extension.sendRequest from that script in the iframe and then start some code out of the background listener to manipulate the iframe. Thanks for your help.
PS: It's also possible to do it without "all_frames": true. It just takes some time till the dynamic iframe is ready. With a timeout it works. For the most cases, this is not useful, but maybe someone has another user interaction first.
PPS: I still can't see why it's possible like this, and not possible to send postMessage events. But maybe somewhen this will works.
I just tested and content script is getting injected into dynamically created iframes (I used manifest). I think the problem is you are trying to access content script's function within iframe, which is not allowed.
Inside your iframe you can't just do:
<a onclick="contentScriptFunction()"></a>
You need to be adding event listener from within the content script:
$("a").click(contentScriptFunction);

How to load a js file with javascript

I want to get over a nasty problem that shows up yesterday during a demo to a client. We're using jquery, loading it from google api. But yesterday, our ISP begin to cause some problems, and didn't load jq.js properly.
So, what I really want is to load a local file from the server if google api has an extrange behaviour (not that it's going to happen often, but at least doing local demos we won't get harmed again).
I know that <script type="txt/javascript" src="googleapi"> somejs </script> executes somejs when file in src doesn't load, but don't know any way to get the file load there.
Thanks in advance
inside you can put the following lines:
var localScript = document.createElement("script");
localScript.type = "text/javascript";
localScript.src = "localJQ.js";
document.body.appendChild(localScript);
Teaching granny to suck eggs possibly, but why not just use a local copy on the demo machine always?
Edit :
I was a bit jumpy. The solution given by peirix is correct. I'll just use his code, to not let the wrong solution pollute this area. You can do
var localScript = document.createElement("script");
localScript.type = "text/javascript";
localScript.src = "localJQ.js";
document.body.appendChild(localScript);
to load javascript dynamically.
Even this is prone to race conditions, however, if there are scripts in your page that depend on this script. Use with care.
This presentation - Even Faster Websites - elaborates on more techniques to load external files through javascript.
This isn't directly answering your question, but JQuery's creator John Resig has an interesting blog post about executing the script tag contents when there is also a src attribute.

Resources