Javascript in asp.net MVC... Beginner issue - javascript

I created an Asp.Net MVC Internet Aplication and in my Index view of the Home Controller I have this
This is the first line, before the script results.
<script type="text/javascript" src="~/Script/Teste.js"></script>
<br />
This line comes after the script.
In my Teste.js I have this:
document.write("Yes! I am now a JavaScript coder!");
But nothing happens. If I change the src attribute and put some random name src="aaaa", despite the fact "aaaa" doesnt exist, I get no error in runtime.

EDIT
Also, check your path again. The default MVC templates in VS create a folder called Scripts, not Script. ("~/Scripts/teste.js")
Per the comment below, this was not the root cause of the issue, but in other cases can easily bite new JavaScript developers.
Most likely, your document.write function is firing before the document is ready, leading to the appearance that nothing is happening. Try the following in your Teste.js file
window.onload = function ()
{
document.write("Yes! I am now a JavaScript coder!");
//or even better as a test
alert("This alert was called");
}
Check the source of your page as well, it could be the document is being written to, you just can't see it due to markup/page styling.
As for you second issue, there will be no 'Runtime Exception' thrown if you reference a non-existent file. If you are using tools like Firebug or Chrome's developer tools, you should see a request to http://siteDomain/Scripts/aaaa.js with a response of 404, not found.

You generally should avoid using document.write() unless you absolutely have to use it for some reason... I don't think I've ever come across such a situation, and write a lot of Javascript.
Try this:
1) Put this in your HTML:
<script src="/scripts/teste.js"></script>
2) Put this in your JS:
alert('Yes! I am now a JavaScript coder!');
3) Open Chrome since it makes it easy to look for external resources loading and open the Network tab in Developer Tools (click the menu button at top-right, Tools > Developer Tools, Network tab).
4) Run your project and copy/paste the URL in the browser that comes up into this Chrome window, and hit enter.
When your page loads one of 2 things will happen:
A) You'll get the alert box you wanted or
B) You'll find out why it isn't loading because the Network tab will show the browser attempting to fetch teste.js and failing in some fashion, for example a 404, which would indicate you've got a typo in the path, or the script isn't where you thought it was, etc.

Put the following line at the very end of your document. There should not be anything after. Then try to load the page.
<script type="text/javascript" src="~/Script/Teste.js"></script>
Also, try pressing F12 once the page loads to see the source. Check if you script is there.

In MVC, the tilde is used to refer to the root URL of your application. However, it cannot normally parse this information. If you write:
<script src="~/Script/Teste.js"></script>
The lookup will fail, because the ~ means nothing special in HTML. If you're using Razor as your view engine (not ASPX), you need to wrap that call in Url.Content like so:
<script src="#Url.Content(~/Script/Teste.js)"></script>
Doing this will ensure a valid URL is provided to the browser.
With that in mind, you need to check that you have the file name and folder name both correct. You also need to ensure that the file is being deployed with your application. You can do this my opening the properties panel while the file is selected in the Solution Explorer and pressing F4.

Related

Really strange Javascript / PHP Behavior

from a webpage, I want to allow users to create a cvs file on the server and download it, generated by PHP ( header('Content-Description: File Transfer') ).
function download_csv_file(){document.location='?action=download_file';}
It works like a charm. File is created and download start automatically like it should be.
But, if I add any other js events/scripts in the JS function (on the same line on a new line), the file is created on the server, but no download.
Really strange, a simple comment on the next line break the process too... But if the comment is on the same line, it works ! Crazy !!!
function download_csv_file(){
document.location='?action=download_file';
// Simple comment
}
Don't work !
function download_csv_file(){
document.location='?action=download_file'; // Simple comment
}
Works !!!
But if I add real code on the same line (instead a comment) it doesn't work.
Any explanation or idea what I can try or search for ?..
Same behavior in Chrome and Firefox
document.location
tells the browser to go to a different URL. Therefore it stops executing anything at the current URL and navigates to a new one instead. And of course that means that any JavaScript code following that command will be ignored.
N.B. since your new URL happens to download a file, it may be that you can still see the previous page in the background, which may lead you to believe that it's still the current page.
You can potentially get round this by using window.open to visit the download URL in a different tab instead.
P.S. Regarding the issue with comments...did you check for any errors in your browser's Console when that occurred? I can't reproduce the problem: https://codepen.io/ADyson82/pen/dyGYQrd

jquery conflict with my website

I layout'd a page and on my server which is it hostgator works extremely fine, using the jQuery mobile components:
http://brunolustro.com/roger/teste/cadastro.html
But my friend who is programming the page wanted me to insert the newest CDNs from either jQuery and jQuery Mobile:
And this is what the page looks like when I insert those codes:
http://brunolustro.com/roger/test/cadastro.html
Do you know how to fix this?
Regards,
Bruno
When working with JavaScript or jQuery on your website - if something isn't working as you intend - the first thing you should do is check the browser console to see if anything is being logged there.
To check the browser console:
Hit F12 on your keyboard. When the developer tools open, choose the console tab, its placed in the toolbar at the top of the new window.
In the console you will see a few errors in red with error codes (404). A 404 means the requested file wasn't found.
This tells us that your reference to jQuery isn't correct. This could be because the file path you've written isn't correct, or that you haven't deployed those files correctly to your site.
Check your file paths you've referenced and make sure the file is on your server. Once both are correct - the errors should go away.
Here's a link to view more about developer tools: https://developer.chrome.com/devtools#console
Check following files in your "test/js" and "teste/js" folders, because i've got 404 not found error:
jquery-2.0.3.min.js
modernizr-2.6.2.min.js
jquery.mobile-1.4.5.min.map

javascript failing with permission denied error message

I have a classic ASP web page that used to work... but the network guys have made a lot of changes including moving the app to winodws 2008 server running iis 7.5. We also upgraded to IE 9.
I'm getting a Permission denied error message when I try to click on the following link:
<a href=javascript:window.parent.ElementContent('SearchCriteria','OBJECT=321402.EV806','cmboSearchType','D',false)>
But other links like the following one work just fine:
<a href="javascript:ElementContent('SearchCriteria','OBJECT=321402.EV806', 'cmboSearchType','D',false)">
The difference is that the link that is failing is in an iframe. I noticed on other posts, it makes a difference whether or not the iframe content is coming from another domain.
In my case, it's not. But I am getting data from another server by doing the following...
set objhttp = Server.CreateObject("winhttp.winhttprequest.5.1")
objhttp.open "get", strURL
objhttp.send
and then i change the actual html that i get back ... add some hyperlinks etc. Then i save it to a file on my local server. (saved as *.html files)
Then when my page is loading, i look for the specific html file and load it into the iframe.
I know some group policy options in IE have changed... and i'm looking into those changes. but the fact that one javascript link works makes me wonder whether the problem lies somewhere else...???
any suggestions would be appreciated.
thanks.
You could try with Msxml2.ServerXMLHTTP instead of WinHttp.WinHttpRequest.
See differences between Msxml2.ServerXMLHTTP and WinHttp.WinHttpRequest? for the difference between Msxml2.ServerXMLHTTP.
On this exellent site about ASP you get plenty of codesamples on how to use Msxml2.ServerXMLHTTP which is the most recent of the two:
http://classicasp.aspfaq.com/general/how-do-i-read-the-contents-of-a-remote-web-page.html
About the IE9 issue: connect a pc with an older IE or another browser to test if the browser that is the culprit. Also in IE9 (or better in Firefox/Firebug) use the development tools (F12) and watch the console for errors while the contents of the iFrame load.
Your method to get dynamic pages is not efficient i'm afraid, ASP itself can do that and you could use eg a div instead of an iframe and replace the contents with what you get from the request. I will need to see more code to give better advice.

how can I force IE9 to "see" the most current javascript when using the debugger?

I'm using IE9 to debug a web app. I made some changes to the javascript after loading the page. I'm not able to get IE9 to stop on the new code. The message is "The code in the document is not loaded". I can set breakpoints when I'm not debugging, but they won't be valid when I start debugging. I'm using IE7 Browswer Mode, IE7 Document Mode.
Things I've tried:
close dev tools window, re-open
stop debugging, start debugging
Ctrl R in dev tools window (same as Clear Browser Cache button)
Ctrl R on the IE9 web page
Ctrl F5 on the Ie9 web page
Clear browser cache for this domain
Check (set) Always refresh cache from server
Next thing to try (I guess) would be closing IE completely. Is that the fix for this? If so, yuck. It takes me a couple of minutes to set the page up so doing that after every JS change really stinks. I can use FF4 to develop the JS, but the JS issue I'm seeing is specific to IE7 so I have to do it this way.
>> How can I get IE9 (running in IE7 mode) to reliably debug the most current JS from the server?
This issue wasn't related to caching etc. IE9 was hitting a script error (missing closing paren) in the new code and not allowing breakpoints anywhere in the script. IE seemed very quiet about the script error though. Anyway, fixing the script error fixed the issues with breakpoints / caching.
If you have access to the code:
In you javascript file reference add a query string, something like this:
<script src="Scripts/main.js?v=1" type="text/javascript"></script>
And every time you change in the js file change the v value to something else, like that the browser will feel that this is a new file and will get it.
Add this:
window.applicationCache.addEventListener('updateready', function (e)
{
if (window.applicationCache.status == window.applicationCache.UPDATEREADY)
{
window.applicationCache.swapCache();
if (confirm('A new version of this site is available. Load it?'))
window.location.reload();
}
}, false);
I found this solution somwhere in the Net. Sorry, but I don't remember the author. It works for me when I debug Web App with JavaScript in Visual Studio and use IE.
I found this question based on the "the code in the document is not loaded" error message. I'm not using IE7 document mode or any of that, just IE9.
Like jcollum, my issue wasn't related to caching.
I'm using MVC.Net, and someone had set up a piece of javascript to rely on a string in the ViewBag. I changed a couple things, and that ViewBag string disappeared, so the resulting javascript looked something like this:
if(!()) {
// Some code
}
Javascript died right here, and wouldn't process the rest of the code in the block. This was confusing, as it was still trying to execute javascript in a different set of script tags, but which relied on a variable set in the other block it wouldn't load.
So, basically, a syntax error was introduced via strange means, and the debugger refused to load some of the code which came after it. Another lesson on the dangers of ViewBag.

Javascript Datejs

I was looking through some pages when I stumbled across this open source JavaScript date library: Datejs. Now I've been trying to use it but everytime I try any function like:
$(function() { Date.today().toLongDateString() } );
or even only
Date.today().toLongDateString()
withing tags, I get errors when the webpage loads, it tells me Date.today() is not a function but it appears as such in the documentation I've been at this for like almost 2 hours now xD it's driving me crazy and I know I just probably overlooked something...
I loaded the:
<script type="text/javascript" src="assets/js/dia_hora/date_es-MX.js"></script>
Are your script path and filename correct? You wrote:
<script type="text/javascript" src="assets/js/dia_hora/date_es-MX.js"></script>
But according to the "Getting Started" page of the project, it should be:
<script type="text/javascript" src="assets/js/dia_hora/date-es-MX.js"></script>
There are two hyphens in the original file: "date-es-MX.js", not an underscore. Or did you rename the file?
Check if the file correctly loads using Firefox Firebug (network tab) or FiddlerTool if you're using Internet Explorer.
Sounds like the script is not getting loaded. Put an alert('hello'); at the beginning of the script and see if you get that popup when the page loads.
Your path to the javascript file is incorrect.
OR
You have a syntax error in a Javascript file that is being loaded before this one. I believe the browser will stop trying to interpret the rest of the Javascript as soon as an error occurs.
Try having the JS Console open in Chrome or Firefox or Safari - you will get a much better idea of what the error is. JS Console has saved me hours or even days - I remember how I used to get frustrated about not being able to tell what happened when JS silently failed.
But with JS Console it's never a silent fail - you get some hint in the error message however small.

Categories

Resources