Is it possible to load Jquery in the body of a page - javascript

I am using code-igniter, and some of my views require jquery. Because they must be used in multiple places they must call jquery in their file, however since they are referencing an external file, calls to $(document.ready) are evaluated before loading jquery and therefore fail. Is it possible to put jquery in the body and still have it load before an javascript is evaluated. Or alternatively, is the some way to pass the fact that jquery is required back through code-igniter into the headers, which were callled before the file in question.
In a view:
echo $this->import->js('jquery.js','jquery');
echo '<script type="text/javascript">
$(document).ready(function(){$(\'div#login.rounded\').corner();})
</script>';
You can view the page at: http://formulator.codingproject.net/content/login/
NOTE This page actually resides on my home machine, so it is expected that the recaptcha fails.

I guess the answer is yes. you can load the jQuery.js in your body. But you have to write your script tags only after jQuery.js declaration, if not you may end up with errors :)
PS : please correct me If I'm wrong :)

jQuery should really be called in the head element. Here's how you'd do that conditionally (untested).
In your controller, each function that needs jQuery should have:
$data['need_jquery'] = true;
$this->load->view('header');
In your header view:
<head>
<? if($need_jquery) { ?>
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" /></script>
<? } ?>
</head>

It looks like you are using PHP? If so, create a static method that returns that string, but only if it hasn't already been included this request. Then you can ensure that it's only being included once.

My website is the same way. What I do is I have one header that is loaded on all pages. In that header I do if($this->uri->segment(2) == 'controller'). Then I load jQuery and certain scripts if needed for that controller.

I think it will be fine if jQuery will be included in the tag of every page, besides, you can use the minified version of jQuery which is not so heavy.

Uh, maybe I'm wrong. But when I view your source code and follow where the jquery file is: http://www.formulator.com/assets/scripts/jquery/jquery.js I get a "page cannot be found" error. So I'm guessing this could be the problem. Maybe the way your php outputs it isn't including the correct domain/subdomain?

Related

Include PHP variables directly into js files

I would like to use js code, which works with php variables.
My situation now:
mainFile.php
<?
$myPHPvar = 1234;
?>
<html>
<body>
MY CONTENT
<script>
var myJSvar = <? echo $myPHPvar; ?>
</script>
<script src="myFile.js"></script>
</body>
</html>
myFile.js
// Here some js code where I access the myJSvar, which was set by $myPHPvar before
console.log(myJSvar);
This works ! But I would like to change this structure. I would like to move the myJSvar definition out from main file into the jsFile.
But If I move this line var myJSvar = <? echo $myPHPvar; ?> into the myFile.js it will not work, because this is not an php file.
Not I thought that this could be a solution:
I rename the myFile.js to myFile.php and change the code like this:
// Here some js code where I access the myJSvar, which was set by $myPHPvar before
<script>
var myJSvar = <? echo $myPHPvar; ?>
console.log(myJSvar);
</script>
and in the mainFile.php I changed <script src="myFile.js"></script> to include('myFile.php');
This works !
BUT:
First question of all: Is this a good idea to do it like this?
Second: The "problem" now: All my files are now php files, also the files, which includes mainly js code. That's not very beautiful, because now I can't see on the first view, which is an js file and which is a php file.
Thank you for your support !
Using PHP, echo the values to hidden HTML fields on the page.
When you know the page is done loading, read them back out using JavaScript.
Note, Ideally, you'd just make the data a separate AJAX/xhr/fetch call to a URL (JSON or XML formatted data is nice for this), but as a stop-gap, hidden fields will do the trick for basic PHP pages.
Similarly, you can echo some inline JavaScript (tags and all) and reference the variables elsewhere. This approach will work but is often referred to as "spaghetti code" because the intertwined front-end (JavaScript) and back-end (PHP) code makes for tricky debugging and does not scale well to larger code projects... months or years after, developers will find themselves scratching their heads as to where code lives, how it's generated, where new code should be placed, etc.
You can do it like this. And there's nothing really wrong with it. You have to bring the data to the client browser somehow. You can do this with: 1. set php variables in the DOM 2. XHR call or 3. cookies
This can be achieved by generating the JS file dynamically... You can create a PHP file that would generate the JS dynamically like:
Note: THIS METHOD IS HIGHLY NOT RECOMMENDED. THIS IS FOR YOUR INFORMATION AND KNOWLEDGE ONLY.
myFile.php (The JS equivalent file)
console.log(123)
Your HTML file
<script type="text/javascript" src="a.php"></script>
But this is highly not recommended because JS files are static resources that can be cached. Using this method would request the JS file every time the page loads (where it will only be transferred at first load only if its static).
The best method is to keep the dynamic variables in your HTML and then include your static JS files which will use these variables.

Js Function not defined when I use php include

I used to write JS inline in my footer but since it's getting too much I want to write it in an external file and include the file in the footer then.
I'm currently using
<?php include "https://example.com/myjs.php"; ?>
in the footer.
In that Php file which is mainly js with a few php expressions, I'm defining all the functions first and afterwards I'm calling some of them functions "onload" with
jQuery(document).ready(function() {
// functions....
});
I've put everything inside
<script></script>
The thing is that I get an error showing the functions I'm calling arent defined. However, when I just paste the code in the footer template inside
<script> </script>
tags it works fine.
I'm assuming that the error is with the tags and inlcude...
What am I doing wrong?
EDIT:
I am using WP functions which are based on logged in user id and page id. Do these might cause the errors?
I'm using wordpress with jQuery.
Since it's a remote URL, all php scripts will be executed before inclusion into your file. So how about
echo file_get_contents("https://example.com/myjs.php");
I could solve the problem:
I defined the php vars in JS before the script within the footer.php. Credits to: Access PHP var from external javascript file
Then I just replaced the php vars wih the js vars and included it with html as script.
Works like a charm now,
thanks anyway for all the help!

Load all <script> tags from a different page

I'm hooking into a separate page (same domain) and pulling it into the current page using $.load, which would be fine, if I was doing it for the whole page, but I'm not, I'm just doing it for the JavaScript code in that page. I was wondering if it's possible to load all the script tags from said page into the current page?
I'm currently using the below code:
var newMessageURL = $('#lnkCompose a').attr('href');
$('#hiddenScriptLoad').load(newMessageURL);
Is said page on the same domain or do you have access to it? You will run into trouble with the cross domain origin policy otherwise.
If you do have access, the only way is to parse the html using a regex statement or html parser and pull the scripts manually.
This sounds like a very hacky approach though and I'm not really sure why you'd want to do this.
If you have access, get the page contents and then use the below to get the script tag sources.
text.match( /<script src="scripts\/(.*?)\.scripts\.js"><\/script>/g )
Credit Javascript regex to get src url between script tag
var newMessageURL = $('#lnkCompose a').attr('href');
$('#hiddenScriptLoad').load(newMessageURL);
The above code will load all the contents you have in the second file and it will also import any javascript codes you have there. But the codes you'll have in second file will not work and wont get into action unless you call to them from first page using a function call or in any other manner.
If you just want to separate your js codings and html and have them in two separate files, it would be better to use PHP to import the second file into the first one and in this way, when the page is loaded in the client browser, it will render it as it was just a single file containing both contents. Ex..
<?php
include("script_file.js");
?>
And also if you want get only the js part of the second file use something like this
<?php
$Vdata = file_get_contents('path/to/YOUR/FILE.php');
preg_match_all("'<script(.*?)</script>'si", $Vdata, $match);
foreach($match[1] as $val)
{
echo $val;
}
?>

JavaScript with json call working in head but not if in separate .js file [duplicate]

I am just wondering if it's possible to use external JS file that contains PHP code.
my external JS
$(document).ready(function(){
$('#update').click(function(){
var tableVal={};
// a bit of php code I need in JS
var search_city=<?php echo $_SESSION['search_city'];?>';
$.post('<?=base_url()?>/project_detail/pub', {'tableVal':tableVal},function(message)
})
})
})
my view page
<script type="text/javascript" src="<?= base_url();?>js/external.js"></script>
The JS doesn't work as I assume that the PHP code in JS is the problem. Any thoughts? Thanks a lot.
You can do it by either renaming you js file to php and using this link in script tag src (as pointed in other answers)
While this may seems a good and easy way there is many reason not to do this.
Caching (your generated script will not be cached, this may be changed but require additional work)
Memory consumption (every request to this generated js file will require php)
You can simply changed to something like this to get it done (in a better way, IMO):
<script type="text/javascript">
var Settings = {
base_url: '<?= base_url() ?>',
search_city: '<?= $_SESSION['search_city'] ?>'
}
</script>
<script type="text/javascript" src="<?= base_url();?>js/external.js"></script>
Than content of your js became something like this:
$(document).ready(function(){
// I assume that not using search_city in your sample code
// and some syntax errors, is just by mistake...
$('#update').click(function(){
var tableVal={search_city:Settings.search_city};
$.post(Settings.base_url+'/project_detail/pub',
{'tableVal':tableVal},
function(message){
console.log(message);
})
})
})
quite a common thing to want to do, just rename your js file to "external.js.php" (i use that method, but as long as it ends in php it doesn't matter what you use really) then just change the src url in your script tags and away you go.
Dont forget you may need to include function and config files into the javascript for that base_url() function to work.
Unless you need php for a lot of things in your js file, I'd suggest you don't do as mentioned above and not rename your js file to php to have it parsed. JS files are best served as static.
One thing you can do is have a script at the top of your php document where you assign your base_url variable as a global to be used by all your js:
In your page, before including any js
<script type="text/javascript">var base_url = "<?= base_url();?>";</script>
<script type="text/javascript" src="<?= base_url();?>js/external.js"></script>
In your js file
$(document).ready(function(){
$('#update').click(function(){
var tableVal={};
// a bit of php code I need in JS
var search_city=<?php echo $_SESSION['search_city'];?>';
$.post(base_url+'/project_detail/pub', {'tableVal':tableVal},function(message)
})
})
})
I believe it is possible, but as Brian mentioned you have to let the preprocessor know it needs to process it. You can either tell it to use php to handle .js files (Not recommended) or simply use a .php file for your javascript, then use:
<script type="text/javascript" src="<?= base_url();?>js/external.php"></script>
This should be okay because the mime type is still javascript so it will be interpreted that way. I've never actually tried this, so it is a guess, but I believe it should work.
Just a quick idea, that could help some people:
I think (never tried) there is also a way to ask the web server (Apache, etc) to let JS files be handled as PHP content.
Advantages:
No need to rename your JS files to .js.php
Takes advantage of caching
Can be applied only to a specific folder (not to every JS file of your website)
Withdraws:
Do not forget that those "php" files are "cached" somewhere, so don't rely on the fact that files are generated every time.
Server resources: as said in other answers, make sure to use such a trick only when it's really not possible to put PHP code outside of the JS files (using ajax queries for instance), or on files that don't load the server too much.

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