Inline jQuery script not working within AJAX call - javascript

I have a issue:
while i call a inline script (wich uses jQuery too) from another page with ajax - it seems, that jQuery is no more defined (?), and I cannot use any of jQuery functions, that should be applied (according to inline script) to content.
It's basically a news list, which holds links to particular news items. I prefer using inline-script at this time, because I won't need this functionality elsewhere.
$.ajax({
url: href,
cache: false,
success: function(html){
$('#fancy_ajax').append($(html).find('.mainContentPadded'));
}
});
As you can see, I'm simply calling a part of another page and appending its contents to page.
When I load full page (not the part of it) - jQuery works as expected (that's why I came across the idea, that it needs to be "rebinded").
Thank you!

So if I understand your question correctly you have some JavaScript contained within the html variable ? If so it will not work, because JavaScript that is retrieved from an AJAX hit is not executed by the browser due to security risks.
I recommend you include the necessary javascript code in your page that is initiating the the Ajax request so that it is already available when you append the new content.
*edit...
monksp added a great link as a comment that shows how to have jQuery do exactly what you want.
Here's also some code to do the same but manually:
<html>
<head>
<title>Test JavaScript JSON</title>
</head>
<script src="https://www.google.com/jsapi"></script>
<script>
google.load('jquery', '1.3.2');
</script>
<body>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON('testjs.json', function(json){
$(document.body).append(json.html);
eval(json.js);
});
});
</script>
</body>
</html>
Here's the content of testjs.json:
{"html":"<p class=\"newelement\">Click me</p>","js":"$(\".newelement\").click(function() { alert($(this).text()); });"}
And finally there are a bunch of existings plugins and other things to include javascript dynamically. I used YUI Get in the past: http://developer.yahoo.com/yui/3/get/

I'm confused by the question, I think. The bit of javascript that you have posted, is that loaded into the page via ajax? Like, you load the page in a browser, then something happens and that javascript gets loaded into the page? That won't work, because any javascript that gets loaded that way won't get executed.
I'd recommend loading it in the originating page's javascript if possible. If not, you could take the results of the ajax request, and walk through it looking for script tags, and eval() their contents as part of your success function. It's not really efficient (or super safe, make sure you absolutely trust where the loaded contents is coming from), but it'll get the job done.

Related

Jquery Document.ready when loaded through AJAX links

I am new here, so please pardon any beginner mistakes.
I am learning jQuery (v1.9.1) along with using jQuery Mobile (v1.3.1). I am encountering two problems when using AJAX links and javascript:
1) When I link pages through the default AJAX linking method that jqm offers, I lose the capability of running any newly loaded javascript on the subsequent pages. i.e. When I go from page1.php to page2.php, can I execute javascript namely something like the following (this code is in page2.php):
<script>
$(document).ready(function(){
$('#form_field_email').focus();
});
</script>
After browsing through bunch of questions here, I believe it is because no new script is evaluated after initial page load. Therefore, I tried to move all my code into on .js file, which I load on page1.php. But sometimes I want to trigger actions on-page-load (as noted above).
Is there any way to achieve this without using eval function?
2) On a similar note, if the id of a DIV on page1.php was 'messageBox', but if I use the same id for another DIV on page2.php, I lose the capability of controlling the newly drawn DIV on page2 as the javascript still points to the old DIV which is no longer visible.
$('#messageBox').show();
Is there a way to use the same name but still be able to point to the elements on the current page.
Thank you for your help.
What you should do is place the code that needs to run after the ajax has loaded in a success callback for the ajax call.
$.ajax({
url: 'http://example.com',
success: function() {
//do something when call completes successfully
}
);

load jquery after the page is fully loaded

I'm looking for a way to load jquery after the page is fully loaded.
well there are lots of questions and answers about it in here, but all describe how to run a script that needs jquery after either page or jquery fully loaded.
What I'm looking for is to load the page and then call jquery and after the jquery is loaded call the functions. something like:
document.onload=function(){
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", 'http://code.jquery.com/jquery-1.7.2.min.js');
//Here I need an event to know that jquery is
//loaded to run stuff that needs jquery
}
Try this:
$(document).ready(function() {
// When the document is ready
// Do something
});
You can also use:
$(window).bind("load", function() {
// Your code here.
});
For your problem, the solution might be to attach CDN hosted by google with certain library:
https://developers.google.com/speed/libraries/devguide
Also, you can add this at the bottom of page (just before </body>):
<script type="text/javascript">
(function() {
var script = document.createElement('script')
script.setAttribute("type", "text/javascript")
script.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js")
document.getElementsByTagName("head")[0].appendChild(script)
})();
</script>
However, this is risky in my opinion. You have an asynchronous call for jquery, thus your jquery has to wait until it loads (ie. $(document).ready won't work in this case). So my answer would be: use a CDN like google suggests; put your javascript on the bottom just before </body>; and, ignore flags from profilers.
It is advised to load your scripts at the bottom of your <body> block to speed up the page load, like this:
<body>
<!-- your content -->
<!-- your scripts -->
<script src=".."></script>
</body>
</html>
You can either use .onload function. It runs a function when the page is fully loaded including graphics.
window.onload=function(){
// Run code
};
Or another way is : Include scripts at the bottom of your page.
You can try using your function and using a timeout waiting until the jQuery object is loaded
Code:
document.onload=function(){
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", 'http://code.jquery.com/jquery-1.7.2.min.js');
document.getElementsByTagName("head")[0].appendChild(fileref);
waitForjQuery();
}
function waitForjQuery() {
if (typeof jQuery != 'undefined') {
// do some stuff
} else {
window.setTimeout(function () { waitForjQuery(); }, 100);
}
}
My guess is that you load jQuery in the <head> section of your page. While this is not harmful, it slows down page load. Try using this pattern to speed up initial loading time of the DOM-Tree:
<!doctype html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="">
</head>
<body>
<!-- PAGE CONTENT -->
<!-- JS -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$(function() {
$('body').append('<p>I can happily use jQuery</p>');
});
</script>
</body>
</html>
Just add your scripts at the end of your <body>tag.
There are some scripts that need to be in the head due to practical reasons, the most prominent library being Modernizr
if you can load jQuery from your own server, then you can append this to your jQuery file:
jQuery(document).trigger('jquery.loaded');
then you can bind to that triggered event.
Include your scripts at the bottom of the page before closing body tag.
More info HERE.
If you're trying to avoid loading jquery until your content has been loaded, the best way is to simply put the reference to it in the bottom of your page, like many other answers have said.
General tips on Jquery usage:
Use a CDN. This way, your site can use the cached version a user likely has on their computer. The // at the beginning allows it to be called (and use the same resource) whether it's http or https. Example:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Using a CDN has a couple of big benefits: it makes it more likely that users have it cached from another site, so there will be no download (and no render-blocking). Further, CDNs use the closest, fastest connection available, meaning that if they do need to load it, it will probably be faster than connecting to your server. More info from Google.
Put scripts at the bottom. Move as much of your js to the bottom of the page as possible. I use php to include a file with all my JS resources below the footer.
If you're using a template system, you may need to have javascript spread throughout the html output. If you're using jquery in scripts that get called as the page renders, this will cause errors. To have your scripts wait until jquery is loaded, put them into
window.onload() = function () { //... your js that isn't called by user interaction ... }
This will prevent errors but still run before user interaction and without timers.
Of course, if jquery is cached, it won't matter too much where you put it, except to page speed tools that will tell you you're blocking rendering.
I have asked this question more than 6 years ago, and any answers I got had some flaws. Later I myself worked out a solution that I have been using for years since then. Now that I came across my own question again and I saw that it has many views, I'd like to share it because I think it may help others.
This problem mainly occurs on Master-Detail type of pages (can be old .master and .aspx pages) or (layout and views in asp.net) or any similar situation maybe on other web development languages, however always there is a master-detail pattern involved.
For the solution, I just add an array at the beginning of my page:
<script>var after = [];</script>
any function that requires jQuery or any other script that would run after this section, instead of running it, I just push it to this array:
after.push(function(){
// code that requires scripts that will load later,
//might be for example a jQuery selector or ...
});
and then at the very end of the page, right before closing the body tag (of course scripts are loaded by now) I run all the functions inside the (here named) after array:
<script>for(var i=0;i<after.length;i++)after[i]();</script>
</body>
I find this way very easy, simple and flawless.

how to refresh a particular div in a page?

Does anyone know how to refresh a particular div in a page, i dont want to load whole page but one certain div. is it posible?
While I'm still in the process of learning myself, I think what you're essentially talking about is AJAX. The jQuery library gives you a number of ways to make AJAX calls, some high level, some low level. Search the jQuery home page for .load() for a high level solution and .ajax() for a lower level solution.
No its not possible, but you can use ajax to update content on the div(not exactly refreshing).
Edit: you can use simple javascript to complete an ajax request. In ajax a request is sent to the server which sends some data back which can be used to update the html inside the div.
www.w3schools.com/ajax/default.asp
It's called jquery. It's a javascript library to make many functions easier to write with less code. Ajax is a part of it and what you use to make Http requests to get dynamic content into a div.
If you dont want to reload the whole page then you may use jQuery Ajax.But using this you can only change the content of div tag without refreshing the whole page
Ajax is your best bet, but it isn't something exclusive to jQuery. if youre not using jQuery anyway, you will find it more efficient to write the scripts yourself instead of loading the entire jQuery library along with your site.
It's Very Easy to Do with jQuery and PHP (AJAX), you can load new value from database or anywhere from webpage you want and also you can set the time interval do check out this link:
http://phphere.blogspot.com/2013/12/how-to-refresh-particular-div-in.html
Here is a way, tell me if it works:
<html>
<head>
<script>
$(document).ready(function(){
$.post(
"anotherpage.php",
{"field":"value"},
function(r){
if(r!==''){
$(".replace").html(r);
}
});
});
</script>
</head>
<body>
<div>Some text</div>
<div class="replace">Default Text</div>
</body>
</html>

Where do I put the $(document).ready()?

I've been trying to add JavaScript to my HTML/CSS, but been running around in circles.
My current set-up is where the html, CSS, and JavaScript files (2 files; my JavaScript code, and jQuery's code) are all separate, but linked to each other via the html page.
So here are my questions:
1) Do I put the link to the jQuery code within the html head? Or within my JavaScript code page?
2) Where does this code go? The html page, or my JavaScript page?
$(document).ready(function(){
//Code here
});
3) Above, by 'code here', they mean JavaScript code, right? Not my html code?
4) I've read about initializing JavaScript code at the bottom of an html page. From what I take though, I don't have to do that with jQuery's .ready function, right?
You should like to your JavaScript files either in the <head> or above the closing </body> tag.
The code can go anywhere really, but I would suggest an external JavaScript page.
Yes
This is correct.
When Javascript code is executing in your browser, all of your included Javascript files and any code you write in-between those "script" tags in the HTML document is going to be executed as though it were all part of one giant file (same namespace). So in some sense, it doesn't matter whether you write your code in the HTML document or whether you write it in an external file that you include - you're free to do either, and it will be executed the same. You can balance maintainability, reusability and convenience (think about what functions you write that you might want to reuse on other pages) and do whichever you feel is best.
To make this concrete - this is one valid way to write your Javascript, if you wanted to write the code inside your HTML file:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
alert('Document Ready!');
});
</script>
</head>
<body>
...
Here's the intro at the jQuery site, for reference:
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
Writing your Javascript code at the bottom of the HTML page was/is a technique for getting it to execute as soon as the document is loaded, which is unnecessary when using jQuery's '$(document).ready' (that's what it does - it abstracts the business of getting Javascript functions to execute on page load, and implements it in a cross-browser way).
See: Introducing $(document).ready() for more.
It doesn't really matter where you place your jQuery code. If you place it in the head tag, it'll automatically load everything. If you decide to place it all in an external JavaScript file, you need to link it with a <script type="text/javascript" src="my_file.js"></script> tag.
The 'code here' part is only for JavaScript. What the code is saying is that when the document is ready, run this function. The function can be whatever you like - whatever you put inside the function will run when the document is ready (i.e. when the webpage is called by the browser).
You don't need to insert it at the bottom of the HTML page - you can do it anywhere. People only insert it at the bottom to optimize their loading speed. It's nonessential.
$(document).ready(function(){
//Code here
});
goes in your javascript file. All javascript code that should be executed once the page has loaded goes where the //Code here comment is.
Perhaps a quick jQuery tutorial would be in order?
Or, you can put your script tag in the bottom of your body, and not have to use the $(document).ready() function.
Put in the head. This is the most stable way and it works. Some people may disagree and say it is slower, etc, but I have found this to always work.
Where you put your code is up to you. You can put in your head with a
<script>Code here</script>
or in a separate file and include it with
<script src="reftomyscript.js"></script>
Yes, put your javascript code in this, either in the head or in a separate file.
Yes, and see (1)

Fetching remote code/text with javascript?

So I'm working on making a dynamic drop down select form and I need for each menu to propagate possible choices from a prebuilt chunk of html (located at, say, http://example.com/menu/choices) is there an easy way to use javascript to fetch the html of a remote page and then plug that in to the page? I know I can use .write() to insert the code, I just don't know how to fetch it.
Thanks!
Actually, you can't use write to insert the code, not once the initial page rendering is complete.
Loading Code
My first read of your question was that you wanted to load code — e.g., JavaScript. Here's how you do that, but see below.
The easiest way to do this is if your code exists at its source location in a JavaScript file all ready for inclusion in a file in the normal way. In that case, all you need to do is create a script element and add it to the document:
var script = document.createElement('script');
script.type = "text/javascript";
script.src = /* ... the URL of the code ... */;
document.body.appendChild(script);
document.body.removeChild(script);
Note that last line, removing the script node immediately after inserting it in the document. Inserting the node is all you need to do, that immediately triggers the process by which the JavaScript file is fetched and interpreted. You can remove the script element immediately (or not, it's up to you).
In the above, I've added the element to document.body because it's convenient and it doesn't matter where you add it. However, most scripts you see doing this will usually add it to the head instead. That's fine too. More in this article, although it's focussed on the Prototype library.
Speaking of libraries, all of the above notwithstanding, if you use a JavaScript library like jQuery, Closure, Prototype, YUI, or any of several others, it will probably make this (even) easier for you.
Update: Did you add the jQuery tag later? I didn't see it originally. With jQuery, if you're loading the script from the same origin as the document, you can use the getScript function:
jQuery.getScript('ajax/test.js');
// Or $.getScript('ajax/test.js');
However, getScript is not the same as the technique above. getScript will be hampered by the Same Origin Policy, whereas adding a script tag is not.
Loading Markup
If you want to load HTML markup and apply it to part of a page, that's easily done with jQuery.load:
$('#someid').load("yoururl.here");
That will replace the contents of the element with the id "someid" with the HTML returned from the given URL. Here's a live example that loads options into a select and another that loads text (a paragraph) into a div. This is easier with a library (like jQuery) because there are some issues around certain elements that libraries usually handle for you.
The thing you want is called AJAX (Asynchronous JavaScript and XML). If you're using jQuery:
$('#my-select-thingy').load('select-options.cgi');
or whatever flavour of server-side you prefer. You should have something like this in HTML:
<div id="my-select-thingy">
<!-- select will go here -->
</div>
and the url above should return something like this:
<select>
<option>Foo</option>
<option>Bar</option>
</select>
You're way better of using jQuery for that. Just look into the Ajax methods and you'll get the hang of it. http://api.jquery.com/category/ajax/
Suppose you have the following HTML markup
<div id="fakeDiv"></div>
you can execute an ajax request like this
$.ajax({
type: "get",
dataType: "html",
url: "http://example.com/menu/choices",
data: {},
success: function(response) {
$("#fakeDiv").html('').html(response);
},
});
to inject the html code returned by your url inside the DIV element.
This is jQuery code. Hope it helps!
Javascript usually can't access other websites for security reasons. If we could load content from wherever we wanted with a script we'd see some pretty rampant chaos. A simple solution is an iframe with the other document or just a section of it.
Does the website have anyway for you to access that info? If you can find an interface you can just get the info and stick in in the document. Otherwise you'd have to do some scraping.

Categories

Resources