I've got this javascript code:
$(document)
.load(function(){
$.post(
'result_source.php?term='+<?php echo $_REQUEST['term']; ?>
);alert('abc123');
});
and it doesn't alert('abc123');. If I remove the
+<?php echo $_REQUEST['term']; ?>
it does alert('abc123').
Thanks
You need to take the PHP part out of the concatenation. The PHP is effectively pasted in to the javascript page before it is processed, so unless your $_REQUEST['term'] is the name of a javascript variable you are using, it will cause errors.
Change it to: $(document).load(function(){$.post('result_source.php?term=<?php echo $_REQUEST['term']; ?>');alert('abc123');});
Bear in mind this won't work inside external javascript files, unless you create an .htaccess or something to configure the server so it parses .js files as PHP before outputting to the browser
PHP will not run in an external JavaScript file unless you create a .htaccess file or configure the server so it parses .js files as PHP before outputting to the browser.
If you put that in a file(with a .php extension), in <script> tags, it will work, though.
Related
Actually i am writting a php script to link some javascript files in my multiple sites.
Example : site_dir1/js/jquery.1.4.2.js and
site_dir2/js/jquery.1.4.2.js
In this case, in the document_root location i have a file called "jquery/jquery.inc.php which has the follwing code
$jq_142 = "<script type='text/javascript' language='JavaScript' src='jquery-1.4.2.min.js'></script>";
I will use this code to make require my php file anywhere i want
<?php require $_SERVER['DOCUMENT_ROOT'].'/jquery/jquery.inc.php' ?>
And the reputation of jquery file keeps only one copy in my following location.
$_SERVER['DOCUMENT_ROOT'].'/jquery'
My doubt is still my javascript files are not loaded where ever i call the files.
I am little messed. how to fix it? any better solution?
If you're going to do this you need to give the script an absolute path rather than a relative one.
When you include it in index.php, the browser will look at /jquery.js for the file. When you include it in /folder/page.php, the browser will look check /folder/jquery.js.
See how it changes depending on where you are in the website? You need to tell it to look at a specific place, like:
$jq_142 = "<script type='text/javascript' language='JavaScript' src='http://example.com/scripts/jquery-1.4.2.min.js'></script>";
This means that no matter where you are in your site, the browser will check http://example.com/scripts/jquery-1.4.2.min.js for jQuery.
Finally, I found my page.php script have loaded my jquery.inc.php file. But the jquery file linking script has been coded inside quotes as follow :
$jq_142 = "<script type='text/javascript' language='JavaScript' src='jquery-1.4.2.min.js'></script>";
So it's couldn't be displayed. And i found this jquery.inc.php is not called by .html files. Only for .php files. I couldn't find any alternative solution for this problem.
I have linked by using the absolute path of my unreplicated jquery library files from jquery/jquery-xxx.js directly.
I have this change request to move all my inline javascript to an external file. I tried a simple copy-paste to a new file, but no luck. I'm getting error at the following line:
var grp_list = <?php echo json_encode($arr_grp); ?>; and
url: "<?php echo $_SERVER['PHP_SELF']; ?>"
I have atleast 20 such occurrences. How do I replace these php variables in external javascript??
I checked lot of forums but did not find any solution.
Thanks a lot for your help!!
Well, you have JavaScript dinamically "assembled" in your PHP script. The easiest solution is to forget about translating the variables. Instead, put all JS code, including the PHP portions, in a PHP file which will pretend to be a JS file, using a custom header. So, your "JavaScript" file will be like this:
<?php
// Send a custom header, so that it will be interpreted as a js file.
header("Content-Type: application/javascript");
?>
JavaScript and PHP mixed code will go in here, with no modifications
Save this file as something like "javascript.php". Then, in your main HTML or PHP file, include it as:
<script src="javascript.php"></script>
That's it! The javascript.php file will be interpreted as a PHP file in the server and retrieved by the browser as JS. Only pay attetion on the kind of processing the PHP in the javascript file does: it may depend on the context you had in the main script, so additional adjustments may be necessary.
In short, you can't pass the PHP variables directly to an external JS file without some work in PHP generating the files, then sending custom headers to treat the file as JavaScript (edit: see post by Marcovecchio if this sounds like a likely solution)... a quick solution is to pass the variables inline so they are global, then use them inside your external file. This will allow for the majority of your JavaScript to be in external files, but also allow you to pass your variables from PHP to JS.
By no means is this the best solution, but it's more than likely the easiest to get working.
Here's an example:
<script type="text/javascript">
var grp_list = <?php echo json_encode($arr_grp); ?>;
var url = "<?php echo $_SERVER['PHP_SELF']; ?>";
</script>
<script type="text/javascript" src="external.js"></script>
During a site scraping, I discovered several scraped functions in JavaScript that I need to modify because the code uses a relative path:
/UserControl/bla
I need to modify it to use absolute path:
www.domain-name.com/UserControl/bla
The problem is, those functions written in a separate file included by the scraped page. So far I can only stream that file using the PHP function file_get_contents(), change the part I need using preg_replace, and insert that script in the head section of the scraped HTML. I don't have access to modify the included JavaScript file because it's on a server I don't have access to.
Is that the right way to do this?
What I do in this cases is to declare JavaScript global variables with the objective to be constant values, then, I can access this variables from my included JS files, for example:
<script>
Globals = {
absoluteUrlPrefix: "<?= getAbsoluteUrlPrefix(); ?>"
};
</script>
<script src="myjsfile.js"></script>
on myjsfile.js
...
var absoluteUrl = Globals.absoluteUrlPrefix+"/UserControl/bla";
...
preg_replace is an option, if it's just to show the web pages on your machine, you could also insert a base-path tag:
http://www.w3schools.com/tags/tag_base.asp
I'm learning all this web programming stuff after years writing .EXE Windows programs so bear with me.
I developed a basic .php and mysql website that works fine.
But I went to add javascript code to my index.php and I don't think the javascript code is executing.
My index.php has the form:
<?php
require_once blah blah
call_my_php_functionBlah();
?>
Then I added this code inside the php blocks of the '<\?\php' and "\?>" as follows:
<script type="text/javascript">
// some known-good javascript code that displays an image
</script>
Nothing showed up.
So I thought "ah-HAH, I blew it, all I need to do is -- move the javascript code outside
of the php block, at the bottom of index.php, and surely I'm good to go."
And still, Nothing showed up.
I checked the source of my 'known-good' javascript code and it said 'embed this javascript code
in your HTML file' so I thought "wow, I guess I need an index.html or something here."
So my questions:
1) should my index.php be able to run the javascript block of code?
I'm guessing 'No because index.php executes on the server and javascript runs on the client machine.'
2) How should I architect this if I want to keep my index.php, whose code works fine and I don't want to mess with it?
I'm thinking that this is an extremely basic client/server, php and javascript script organization issue that every web programmer knows how to handle, but like I said, I'm new to all this. I read in the archives about .htaccess etc. etc. but I
bet there's an easier way, and I'm not sure if the stuff I read applies.
the file name extension is completely irrelevant
PHP executes on the server and doesn't care at all about any Javascript
code inside <?php ?> tags must of course be valid PHP code to be executed by PHP
your browser receives whatever the result of your PHP execution is
you can use PHP code to output Javascript or simply have Javascript on the same page outside of <?php ?> tags
only whatever the browser receives matters, so use View Source
look at the browser's Javascript Console to debug client-side Javascript problems
Then I added this code inside the php blocks of the '" as follows:
Dont add your script inside the php block bring it outside php block.
After you are done with script you can reopen php block and write php again
index.php can run javascript, just that You need to echo the javascript code to put it in the page.
Anything that appears inside your php open/close tags has to be echoed or printed to be rendered to the html page. Anything outside your php open/close tags should appear in your html page but whether it works correctly or not is another matter not necessarily related to your php. The php interpreter doesn't run your javascript code, however, so it can't just sit inside your php tags.
Javascript will run inside .php file.
But you have to write outside the tags.
Eg:
index.php
<?php
echo "Helloooooo";
?>
<script>
function TestingMyFirstScript()
{
alert(1)
}
</script>
Javascript will execute in a PHP file but not inside of a PHP block. It executes in the server, yes and anything coming from PHP should be printed out to see. You should have the JS code outside of the PHP block and it can be anywhere in the page e.g.
It depends how to mix/match the code but of course keep it clean and easy to read (and debug).
<?php
// code here
?>
<script type="text/javascript">
// JS here
</script>
<?php
// some more code here
?>
Answer to both of your question is that you dont have to create a separate html file to execute your JS code. You can have HTML, JS, and PHP code in the same file. PHP code inside the PHP tags will be processed on the server and replace with HTML. The server generated HTML will be combined with other HTML present on the .php file and sent to the browser as one HTML.
There must be some error in the JS code which is causing the script to fail.
<?php
require_once blah blah
call_my_php_functionBlah();
?>
<script type="text/javascript">
// some known-good javascript code that displays an image
</script>
<?php
// other php code
?>
Most of the above comments should help you with your PHP + JS problem. However, if you are still getting errors with your output, try using:
alert("breakpoint 1");
//some code
alert("breakpoint 2");
throughout your Javascript function (it will show you where the code is failing). Good for beginners debugging. Also check out http://www.jslint.com/
I've been developing my site with the site directory structure as
www
img
javascript
include
index.php
Now I want to change it to
www
index.php
dir1
dir2
...
themes
theme1
img
javascript
include
index.php
At the theme level index.php, earlier I've my paths to javscript files as javascript/file1.js or so.
Now I've changed the paths to <?php echo THEME_PATH . "javascript/file1.js"?>
This includes the js files, however my problem is when I reached inside the js file.
For example, in one script.js file, I've a jquery method called as
$('#pop-con').html('<p><img src="img/ajax-loader.gif" width="220" height="19" /></p>');
I can't use php inside the js file. So how do I change the paths similar to the php implementation above??
Relative paths
Probably one of the easiest ways to solve it is using relative paths.
In your case you will need to be one directory up (../), so it would be:
$('#pop-con').html('<p><img src="../img/ajax-loader.gif" width="220" height="19" /></p>');
You can have a small <script> on your pages that creates a global variable to store the "THEME_PATH" value:
<script>
window['THEME_PATH'] = '<?php echo THEME_PATH?>';
</script>
Then your JavaScript files can just look for the global variable and use it to construct paths. I keep such code in a global template header that's used for all the pages in my application. There really are only a very small number of things like that to worry about; in my application I think there are like 4 or 5 items of information like that to communicate with included .js files.
Solution, in case anyone else need it.
I put the following code in my theme level index.php file
<script>
window.themePath = "<?php echo $site_info[theme_style_path]; ?>";
</script>
And use the javascript global variable to append the path.
The source of the Javascript is irrelevant for the purposes of HTML being embedded within the page. What matters is the location of the page the HTML is embedded within.
For instance, if you load a page from example.com/index.php, and some Javascript loaded from example.com/js/script.js inserts some HTML into the main page, then image path references are going to be relative to /, as that's where the page was loaded from, not from /js.
As for embedding PHP in JS, you're right - but you can have PHP emit a .js file trivially:
<?php
header('Content-type: text/javascript');
?>
var settings = <?php echo json_encode($SETTINGS_ARRAY); ?>;
would generate perfectly valid Javascript, even thought it came from a PHP file.