Jsonp callback function not working? Am I doing this wrong? - javascript

So I'm totally new to this, but jsonp seemed so simple, I'm just trying to make a web app using dashcode. I need to put twitter json data on a page of my web app. This is what I tried.
I put this code in index.html
<script src="http://twitter.com/users/USERNAME.json?callback=handleResponse"/>
Then I created a javascript file
function handleResponse(responseJson){
alert(responseJson.status.text);
}
When I put the javascript file as the datasource I get an error saying it is not valid JSON or XML. As I said I am new to this, so I might be doing it completely wrong.

You code works, at least in Chrome, with one small tweak - see http://jsfiddle.net/nrabinowitz/jJTQn/1/
<script type="text/javascript">
function handleResponse(responseJson){
alert(responseJson.status.text);
}
</script>
<script type="text/javascript"
src="http://twitter.com/users/Pogue.json?callback=handleResponse"></script>
The small tweak is closing the script tag properly (script tags can't be self-closing, for reasons I'm apparently too lazy to Google). Wouldn't hurt to throw type="text/javascript" in there too.

You need to make sure the handleResponse function is defined before the external jsonp call.
(Also your script tag is invalid)
<script>
function handleResponse(responseJson){
alert(responseJson.status.text);
}
</script>
<script src="http://twitter.com/users/USERNAME.json?callback=handleResponse"></script>

Click on “Widget Attributes” in the left-hand source pane. Under “Network / Disk Access”, make sure that “Allow Network Access” is checked. Without this checked your widget won’t be able to make any AJAX requests.

Related

How to make external javascript link with variable version parameter (changeable parameter)

I want other web sites to link to js file from my domain, like this:
<script language="javascript" src="http://mySite/jsfile.js"></script>
To avoid the cache problem then I need to add a version parameter to the JS file.
But if the version parameter is static then they have to keep updating the link with every new version, so I need a "CHANGEABLE" parameter like this:
<script language="javascript" src="http://mySite/jsfile.js?new Date().getTime()"></script>
How to do that?
in other way: HOW TO MAKE THEM ALWAYS GET THE LATEST VERSION OF MY JS FILE WITHOUT THE NEED TO RE-UPDATE THE JS URL IN THEIR PAGES.
Thanks in advance for your help :)
You can write your <script> tag with js:
<script language="javascript" src="http://mySite/jsfile.js?new Date().getTime()"></script>
with:
<script>
document.write("<script language="javascript" src="http://mySite/jsfile.js?k=" + Date.now() + "'><\/script>");
</script>
this way its posible to add some number or timesamp after your jsfile.
I would make a script, which call my api. Get the lastest js script code, And include it on site,
this way, it's doesn't matter if it's cached the url for the script.
First, Make a .js file, which use Jquery getScript to get and execute. the script you won't have cached .
get the people to use this. then whenever the site is loaded, it get's a new version of the script from your server.
Jobs done.
Im not providing anycode, since, it's more or less using the Jquery getscript. and the docs for that, is better then any sample i could make.

Javascript running from html but not php

I've read a similar question here, but can't seem to get around it in this case, so would appreciate any clarification. I have a page in php that runs several instances of JavaScript that work on cue on localhost. However one particular instance of JavaScript (that makes an arrow hide when it scrolls beyond 10px) does not run, but when i run the same from an html version of the same php page, the arrow action works as desired. Why is this the case? Here is the code of the page in jsfiddle (exactly the same is used for respective sections in the php page.)
To clarify i have added this bit of JavaScript in the following manner at the end (after footer, before body end) of the index.php file (along with other blocks of JavaScript which work as desired for their respective targets):
<script type="text/javascript">
$(window).scroll(function () {
if ($(this).scrollTop() > 10)
document.getElementById('arr_downpoint').style.visibility = 'hidden';
else
document.getElementById('arr_downpoint').style.visibility = 'visible';
});
</script>
I have added jquery as follows (and it works for all other instances on the php page except for the arrow):
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
Lastly, there are no console errors. Would like to know why only this block of JavaScript isn't working from php, but works from HTML (while the other JavaScript instances work fine on both php and HTML), and how to find out what's wrong?
RESOLUTION: Just found that I'd erroneously added # while assigning arrowpoint id. That's why the script couldn't do anything with the arrowpoint, since <a> now had a # as part of its name. sorry about that careless oversight, for the time it may have taken to consider.
If you are trying to load the page directly from the file (your page url start with 'file://...') the problem is that the browser is trying to load jquery using the same protocol (file instead of http) because you didn't specify a protocol for the external files (the src attribute starts with '//', which mean something like "use the same protocol of the current page"). You can verify if this is the reason behind your problem, opening the browser console looking for errors like:
GET file://code.jquery.com/jquery-1.11.3.min.js net::ERR_FILE_NOT_FOUND
GET file://code.jquery.com/jquery-migrate-1.2.1.min.js net::ERR_FILE_NOT_FOUND
Uncaught ReferenceError: $ is not defined
To fix this problem, you should always run you html from a server (like Apache with PHP, as you already did) or you can write the external scripts url including the protocol (but this can cause other problems if you will run your page under https)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

javascript stream wrapper, intercept JS file contents

In PHP there's a function called stream_wrapper_register. With that i can get the file contents of every PHP file that is about to be included. So that basically gives me control over the 'code' that will get parsed.
I was wondering if there's something like this in javascript too? So suppose i include my file:
<script type="text/javascript" src="js/myfile.js"></script>
My code in that file then sets up the stream wrapper (suppose this is available in JS too). Now i want to be able to get the file contents of every other javascript file that will be included:
<script type="text/javascript" src="js/somefile.js"></script>
<script type="text/javascript" src="js/someotherfile.js"></script>
But this ofcourse must happen before before the browser actually executes those files.
So is there a way to intercept that somehow?
$.ajax("/path/to/javascript.js").done(function(source) {
eval(transmogrifySourceCode(source));
});
I used the jQuery syntax because AJAX-style gets are much easier that way, and you'll have to provide your own transmogrifySourceCode function to edit the source before you load it.
I do wonder why you'd want to do, that, though. You should be in full control over your input source, so why not just excise the code you don't want on the server?
No, you can't. Alone for security reasons you won't be allowed to get every script's content.
For Opera, there is a special BeforeScript event which can be listened to from local user scripts.
So there is no (good) way to detect (dynamically added) <script> elements in a page and prevent them from loading and executing a script. Yet you could load the script files by ajax, respecting the same-origin-policy (!), and evaling their modified contents as #DavidEllis suggested.
Elsewise, you need to proxy all script inclusions over your server and modify them there.

Cross-site javascript problem

I'm developing a JavaScript API service. Main html page looks like this:
<html>
<head>
<script type="text/javascript" src="scripts/logic.js"></script>
<script type="text/javascript" src="scripts/jquery-1..."></script>
<script type="text/javascript" src="http://mydomain/api/main.js"></script>
</head>
...
</html>
In the main.js script I load another script from mydomain. I'm doing it by adding script tag ([script.. src="http://mydomain/api/getsomedata.js?callback_id=3434&someparams=..."]). Loaded script imediatly calls API callback function: MyApi.processCallback(...). Everything works ok.
But when I'm trying to load another mydomain script from local file (logic.js), I recive very strange situation: all script global objects are undefined. There is no MyApi object or jQuery $ object which were visible during previous call. So I can't call MyApi callback function.
Perhaps it is because of security restrictions. Anti-XSS, or something similar. I tried to add a X-XSS-Protection header, like in all Google JavaScript APIs. But it did not help.
I don't use IFRAMES.
The problem can be solved exactly, since many cross-site JavaScript API's are working (Google Maps API, etc.) on the same idea.
What is happening in your script?
If you are doing Ajax calls back to the domain, your script will fail with a Same Origin security error. If you need to do communication with your server from another domain, than you need to use JSONP to do it. If you are working with only modern day browser you can get away with CORS.

Calling external .js from ASP.NET MVC

I'm JavaScript newbie. What I'd like to be able to do is to call a function from .js file sitting in ASP.NET MVC project's scripts folder.
The function is:
function myfunction() {
alert("HELLO");
}
...and it resides in file brfix.js
On a viewpage I call it like this:
<script src="../../Scripts/brfix.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
myfuntion();
});
</script>
But the code doesn't work. However, if I place js-code directly onto the viewpage, it works, like this:
<script type="text/javascript">
$(document).ready(function() {
alert("HELLO");
});
</script>
How to call a file-based js function? Could some JavaScript-Big-Kahuna help me out? =)
If that code is pasted directly from your source code, you have a typo so that'd be why it doesn't work!
your function is called myfunction(), but you're calling myfuntion()
you should enable js errors in your browser when developing. You don't say which browser you're using. For IE it's in Tools - Options - Advanced. Uncheck the "disable script debugging" options. In firefox I'd use something like FireBug as Dror says, if memory serves there are things that appear in the event of a javascript error. If you are still having problems I would try installing Fiddler2 (in IE) and building a request for the js file and see what comes back.
Another option would be to put a debugger; call just before you call your function, you should then be able to step through the javascript.
It may be that the reference to the external file is wrong:
<script src="../../Scripts/brfix.js" type="text/javascript"></script>
Make sure the reference is correct.
You can try by using view source to see the actual location ../../Scripts/brfix.js gets translated to in the final page.
You can also try with FireBug of FireFox.
If your mvc site is the root site in iis you can start the script src with a slash to get to the scripts. otherwise you can use an asp:ScriptManager to include the scripts
As other posters have mentioned, there is a typo. However...
Check out the Url.Content() method for referencing your site content. (images, scripts, etc...) Using ../.. isn't reliable, especially if you have varying levels of depth in your URLs or your application lives in a subdirectory.
Here's a helper I use in most of my projects, for example:
public static string Script(this HtmlHelper Html, string url)
{
UrlHelper Url = new UrlHelper(new RequestContext(Html.ViewContext.HttpContext, Html.ViewContext.RouteData));
string html = "<script type=\"text/javascript\" src=\"{0}\"></script>";
return string.Format(html, Url.Content(url));
}
And here it is being called:
<%= Html.Script("~/public/js/blah.js") %>
I had the same problem and it turned out that I had a few js files that weren't being found. If your MVC project structure is the default VS setup and your View page is in Home for example, then I think below will find the file:
<script src="../Scripts/brfix.js" type="text/javascript"></script>
But even if that one is found other js files not being found caused my $(document).ready not to work. Check your page in Firefox's Firebug, if a file isn't found you will see html markup with a message saying a resource could not be found, located underneath the offending reference. Once I resolved all the js references then my $(document).ready worked.
Strangely VS was telling me it couldn't find the js files when the references were correct, and wasn't flagging the problem when the references were incorrect.

Categories

Resources