jQuery load() function doesn't work - javascript

I am new to the world of JavaScript and I'm trying to use the function load() to insert another html file. It' a little bit hard to explain, here is the code:
<script>
$(document).ready(function() {
$('#main').click(
function(){
$('#news').load('today.html');
}
); //end click
}); //end ready
</script>
Can you help me? I'm not using a web server.
Thanks

Why it Doesn't Work
Browser security restrictions can block you from using AJAX functions with content that is accessed through the file:// protocol (i.e. from a local file on your computer, without a web server).
Solution
I run a web server on my pc so that I can avoid all of these problems - back when I was working on a Windows PC, I used WAMP. These days, I use Linux (with Apache, PHP and MySQL) on my computer so I can work in an environment that is closer to the server.

I do not believe the code you have presented has any faults in any way. I believe it is to do with your loading of the JQuery library, as with the following code I achieved these results:
index.html
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
$('#main').click(
function(){
$('#news').load('news.html');
}
); //end click
}); //end ready
</script>
</head>
<body>
<p id="main">HELLO</p>
<p id="news">NEWS</p>
</body>
</html>
news.html
<html>
<head></head>
<body><h1>HELLO STACK OVERFLOW!!!</h1></body>
</html>
Before click:
After click:
However, when I was building this example I first tried using the Google APIs version of JQuery and found that I could not currently connect to the API. Therefore I believe the solution to your problem is to go to this website: http://code.jquery.com/jquery-1.11.1.js and copy and paste everything into a text file called 'jquery.js'. Then add the following to the head tag of your main HTML file:
<script src="jquery.js"></script>
Make sure that 'jquery.js' is in the same directory as the main HTML file of your project otherwise this will not work. Hope this helps :)

You can find error message in load(url,fnResponse) response is success or fail
also check this jquery-load-method
$(document).ready(function() {
$('#main').click(
function(){
$('#news').load('today.html', function( response, status, xhr ) {
if ( status == "error" ) {
alert( "Sorry but there was an error: " + xhr.status + " " + xhr.statusText );
}
});
}
); //end click
}); //end ready

Related

Trying to use youtube api on html page

Here is my code:
<!DOCTYPE html>
<html lang="en" >
<head>
<script type="text/javascript">
function showResponse(response){
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
function onClientLoad(){
gapi.client.load('youtube','v3', onYouTubeApiLoad);
}
function onYouTubeApiLoad(){
gapi.client.setApiKey('MyActualKey');
search();
}
function search(){
var request = gapi.client.youtube.search.list({
part: 'snippet'
});
request.execute(onSearchResponse);
}
function onSearchResponse(response){
showResponse(response);
}
</script>
<title></title>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
</head>
<body>
<div id="response"></div>
</body>
</html>
This code is from Codecademy, and I thought I can use it on an html page and it would work.
I got an API key from google and I set my Youtube data api v3 setting to enabled in my google developers console, but this code gives me a blank page.
What am I doing wrong?
There are a few missing pieces, code snippets which codecademy likely took for granted but which are essential when placing it in your own server outside of their app. First of all, you need a line that actually loads the gapi library from google. You can put this in your code, just before the closing :
<script src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
In short, this will get the library from Google's servers, and when it's loaded the library will automatically call your onClientLoad method, kicking off your app.
Next, you say you have an API key; make sure you put that key into your code by replacing this:
gapi.client.setApiKey('MyKey');
with this:
gapi.client.setApiKey('{WHATEVER_YOUR_ACTUAL_KEY IS');
Finally, as the commenters mentioned, your body is empty, so when your code executes the showResponse method there's no place to put what comes back. Add this:
<div id="response"></div>

How do i remote include a javascript file in Titanium appcelerator and use the functions of that file?

I am required to remotely include into my appcelerator project, a javascript file available at a particular link, and use the function declared in that file to process some data.
What i would like to achieve is something like the following in html -
<script src="https://some-link/Data.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var testVariable = someMethod(localdata);
});
//use testVariable as necessary
</script>
//someMethod() is declared in remotely available Data.js
I am a newb at Appcelerator and im not really able to follow some of the threads i have come across, so some detailed help would be really appreciated. Thank you in advance.
Well according to me , you should first understand few points first :
You want to include a remote file hosted at some server , now as the Titanium code converts to native code at compile time , you cannot include Titanium API's from remote file.
If you want to include a remote file , then only option which I see is loading that file in webview.
Now coming to your problem , as you said that you want to fetch some data only from remote server by triggering some JS function from remote file. So following is what would I do :-
a/ Create a hidden webview in my main window with a EventListener of webview. Something like :
var webview = Titanium.UI.createWebView({url:'localHtmlFile.html'});
//event listener to handle the response from webview
Ti.App.addEventListener('fromWebView', function(e)
{
var testVariable = e.data;
});
b/ In localHtmlFile.html file :
<!DOCTYPE html>
<html>
<body>
<script src="https://some-link/Data.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var testVariable = someMethod();
//respond the fetch data to the main window via fireEvent
Ti.App.fireEvent( 'fromWebView', { data : testVariable } );
});
</script>
</body>
</html>
PS : This is just a logic to begin with , you have to edit code according to your requirements

Loading a text file through AJAX gives restricted URI error

I mentioned i read the suggested link ...and Could not able to understand the
suggestion .."Use Greasemonkey to modify Pages and start writing some
javascript to modify a web page
I am loading a text file with $.ajax. When running the code on Firefox, I get the following error:
Error: ["Access to restricted URI denied" code: "1012" nsresult: "0x805303f4 (NS_ERROR_DOM_BAD_URI)" location: "<unknown>"]
Here's my code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("button").click(function () {
$.ajax({ url: "demo_test.txt",
success: function (result) {
$("#div1").html(result);
},
error: function (abc) {
alert(abc.statusText);
},
cache:false
});
return false;
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>
I've already read the following questions:
firefox reading web page from local JS file -- access to restricted URI denied, code: 1012, nsresult: NS_ERROR_DOM_BAD_URI
Error: [Exception... "Access to restricted URI denied" .... while calling $.ajax method
It was suggested that file system should not be used, so changed the URL to http://demo_test.txt, but that did not solve the issue.
I also heard that it might be because of a cross domain issue. If so, what exactly is meant by that, and how should I solve the problem?
Browser security prevents the code from running. You are better off running a local server such as IIS or Apache.
You can change your browser to run local content by changing a browser config
Firefox
Go to about:config
Find security.fileuri.strict_origin_policy parameter
Set it to false
I finally seems to Get it working . Here is working Script
$("button").click(function(){
$.ajax({url:"http://localhost/demo_test.txt",success:function(result){
$("#div1").html(result);
}});
});
Workaround : put the html file and text file on local server (IIS) New Site .

Head.js weird action

I'm trying to use head.js. Getting some weird action. Below works but if I comment out "alert('hi')" in the script in the BODY, then the head.js doesn't seem to work.
So I tried commenting out all the head.js stuff and used a standard tag for each JS library. And it works as expected. But when using Head.js, it fails if the "alert('hi')" is commented out. Obviously, for production, I want to remove this alert but then I get this error message: "ReferenceError: $ is not defined" ... ??? But if I uncomment out the alert, then it all works and pulls data from the DB ???
Any thoughts?
<head>
<title></title>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/headjs/0.99/head.min.js">
</script>
<script type="text/javascript">
head.js(
/* root level */
"http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js",
"http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js",
"/assets/scripts/external/_references.js",
"../../assets/scripts/external/jquery.unobtrusive-ajax.min.js",
"../../assets/scripts/external/jquery.validate-vsdoc.js",
"../../assets/scripts/external/jquery.validate.min.js",
"../../assets/scripts/external/jquery.validate.unobtrusive.min.js",
"../../assets/scripts/external/knockout-2.3.0.js",
"../../assets/scripts/external/modernizr-2.6.2.js",
"/assets/css/Index.css",
"assets/css/OrangeCounty.css"
);
</script>
</head>
<body>
<div id="list"></div>
<script>
alert('hi');
$.getJSON("http://localhost/webapi/api/ccc", function (result) {
$.each(result, function (i, field) {
$("div").append(field.Code + " " + field.Country1 + "<br/>");
});
});
</script>
</body>
The alert() stalls the script execution enough for jQuery to actually load. Head.js loads the scripts in parallel and doesn't block, so you have to use it with a callback:
head.js(..., function() {
// Your code
});
Or put that code into a separate script file and put it after jQuery in your head.js call.

jQuery $.load() functioning on personal webserver, but not production webserver

EDIT: I have discovered that this is a 405 error. So there is something going on with the webserver and handling POST methods.
I am having a strange occurrence. I have identical javascript code on both my test environment and production environment.
The test environment functions, and the production does not. Here is my identical code.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jquerytools.org/1.1.2/jquery.tools.min.js"></script>
<script type="text/javascript" src="./js/jquery.scrollTo-min.js"></script>
</head>
<body>
<div class="content" id="content">
<a id="changeText" href="test.html">Change</a>
</div>
<script>
$(document).ready(function() {
$("#changeText").live('click', function(){
var url = $(this).attr("href");
$("#content").load(url, {var1:Math.random()*99999},function(){
alert(url + " loaded");
});
$.scrollTo("0%", 400);
return false;
});
});
</script>
</body>
</html>
Both environments report that
alert(url + " loaded");
is happening. But only my test environment actually displays the change.
The production webserver has "test.html" available in the correct location.
Are you sure the scrollTo script is being included on the production server ( or am I misinterpreting what you mean by change ) ? Perhaps try a root relative path instead of './js'? I would check Firebug's script tab to ensure it is being included.
405 errors mean that the URL you're sending to isn't expecting you to send the data in that manner. For example, if you're sending a POST request to a URL that's only designed to handle a GET request, you'll get this error.
My guess is whatever server you're running on is set up to not allow POST data to be sent to a page with a .html extension, causing the error you're seeing. Try changing the extension to a .php, .aspx, etc, and see if that helps.

Categories

Resources