How to use base url or php variable in javascript file - javascript

I am new in PHP, i want to use "base_url"(php variable) in javascript file,But right now i am unable to load image,Here is my current code,How can i do this ? Thanks in advance.
$('#site-logo').find('img').attr( {src:'<?php echo base_url(); ?>assets/images/logo/logo_dark#2x.png',width:'151',height:'45'} );

You can create a variable or a constant in the javascript and store the base url there and use the same in the code.
Something along the line of following
var BASE_URL = "<?php echo base_url(); ?>";
$('#site-logo').find('img').attr({src: BASE_URL+'/assets/images/logo/logo_dark#2x.png',width:'151',height:'45'});

Related

How to read global variable from WP-Config.php in JS file

I have defined URL in wp-config file.
DEFINE('URL', 'google.com');
Now i want to access this URL from my JS theme file:
<script> alert(URL); </script>
How to do this?
use localize in functions.php
add_action('wp_enqueue_scripts' , function(){
wp_localize_script('jquery', 'config_var', URL );
});
and in js file => config_var will equal the config variable value
You have to put a bit of your JS in your PHP file (i.e. use script tags to accomplish this). Then do the following:
Place the script in your php file
<script> alert(<?php echo URL ?>); </script>
you can read the php variable inside th js using echo. use like this
var url='<?php echo _URL; ?>';
alert(url);

Set Javascript Variable From PHP Get Variable

I have a page which I have collected two variables, I want to pass these variables to my document ready function. but for some reason.. My alerts for testing are just outputting the line code rather than the result.
just to note the JS script is in another file which is linked to the page.
PHP
<?php
$cardid = test;
$custid = test;
?>
Javascript
$(document).ready(function(){
var custid = '<?php echo($custid); ?>';
var cardid = '<?php echo($cardid); ?>';
alert(custid);
alert(cardid);
});
Put your javascript code into a separate php file under script tag:
<script>
$(document).ready(function(){
var custid = '<?php echo($custid); ?>';
var cardid = '<?php echo($cardid); ?>';
alert(custid);
alert(cardid);
})
</script>
Include this file in your main php file (using the include function).
It is not possible to execute php in a separate .js file.
you aren't assigning anything to your PHP variables:
$cardid = test;
$custid = test;
a value which isn't numeric and isn't in between quotation marks is considered a constant in PHP. and the constant test most likely has no value in your PHP environment.
you wanted to assign a string, i guess, so don't forget the quotation marks:
$cardid = "test";
$custid = "test";
Wrong concept.
Your JS is not parsed by PHP, so your approach will not work.
Lets make it work:
You have to give the Variables to JS with one trick: Write it into the HTML in a script-tag, then you can access them in your JS.
Lets assume, you produce a HTML like this in your PHP:
<body>
<div>Hello World</div>
</body>
Now, write the variables for you JS into it, here is a simple approach:
echo "<script>var myVar1='".$_GET['var1']."';</script>\n";
echo "<body>\n";
echo " <div>Hello World</div>\n";
echo "</body>\n";
Okay, very simple, do not do it like this in real, but you got the concept?
So, that was the trick to do this.
P.S. The same way, you get $_POST Data to your JS ;)
Consider using quote to represent string.
<?php
$cardid = 'test';
$custid = 'test';
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.js"></script>
<script>
$(document).ready(function(){
var custid = '<?php echo($custid); ?>';
var cardid = '<?php echo($cardid); ?>';
alert(custid);
alert(cardid);
});
</script>
PHP code will only be run in files ending with .php. Your.js file is loaded directly and not subject to PHP processing. If you wish to assign values from PHP variables to javascript variables you will need to do so in a script block in your .php file.
For example if you add this to your .php file -
<script type="javascript">
var custid = '<?php echo $custid; ?>';
var cardid = '<?php echo $cardid; ?>';
</script>
Then in your .js file shold look like -
$(document).ready(function(){
alert(custid);
alert(cardid);
});
It is of course possible to run PHP in a .js file. As in the case of running PHP as an Apache module, you can add whatever extensions you want Apache to recognize as PHP scripts, such as:
AddType application/x-httpd-php .php .html .htm .js
starting with php5.3 you could probably get issues so you can try also:
AddHandler application/x-httpd-php7 .php .html .htm .js
AddHandler application/x-httpd-php .php .html .htm .js
AddHandler x-httpd-php .php .html .htm .js
if you still get issues use a 301 redirect or a rewrite rule in your .htaccess, like this for example:
Redirect 301 "^(.*)/dir/example.js$" "http://www.domain.de/dir/example.php" [NC,L,QSA]
if you are on lighttpd go to /etc/lighttpd.conf or on Windoze C:\lighttpd\etc\lighttpd.conf, uncomment the "mod_cgi" line and add this line:
cgi.assign = ( ".js" => "c:/php/php-cgi.exe" )
don't give up just because someone say to you "you can't do this or that" ;-)

write with php code in javascript

<script type="text/javascript">
var id=<?php print''.entry1->id.''?>;
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ajax_unfollow.php",
data: dataString,
cache: false,
});
</script>
there have a error in this line
var id=<?php print''.entry1->id.''?>;
how can i write php code in var id?
this javascript run in a foreach loop.
write like this :
var id= '<?php echo entry1->id;?>';
You can try this
var id = '<?=$entry1->id?>';
You should add a single quotes around your PHP expression.
So, the corrected code should be:
var id='<?php print''.entry1->id.''?>';
Also, another thing:
You should avoid short_open_tag.
So, please use <?php echo $variable;?> instead of <?=$variable;?>.
Because, most of the PHP running servers should have short_open_tags directive off.
So, your PHP code, in this case will be considered as a plain text and will be shown to user.
Without it, whatever generated by the PHP should be considered as a JavaScript variable.
Which should cause an error.
since value of print should be string so you can try this code.
var id="<?php print''.entry1->id.''?>";

pass parameters using variable?

This is a simple syntax question.
I declare a variable:
<script type="text/javascript">
var id_1= '<?php echo $id; ?>';
</script>
And then in a externally loaded js file im trying to call a function using the variable (the external js file is loaded after the ^^ variable declaration:
loadComments(id_1);
The id_1 is being passed literally as 'id_1', not recognizing it should be a variable. What am I doing wrong?
var id_1 = '<?php echo $id; ?>';
Will echo something like this:
var id_1 = '10';
Which is treated as a string in JavaScript. You want to do this instead, so that you assign a number to id_1:
var id_1 = <?php echo $id; ?>;
This will print out something like this:
var id_1 = 10;
The php code is recognized only by a .php file.
Put your code in a .php file and run it on you local server

Partial url in CodeIgniter

Fellow Coders,
so far I have been using the CI url helper to build full urls using base_url() and site_url(). Now I'm trying to access a controller function within some javascript code that will be loaded as a js file.
it's actually an ajax call with a url parameter that should be something like:
url : '/account/check_user'
now unless i prefix the url with the full path as ins http://servername/..... the code fails.
all the code examples i've seen use the short version of the url but i cannot get it to work. I'm sure this is really simple but i'm stuck.
i could pass a hidden form field to the js code but i'd rather not. any ideas?
thanks
Well, I also tend to use absolute URLs and a good practice I always do is declaring a JS variable:
var base_url = "<?php echo base_url(); ?>";
In:
the head section
as the first line of my script tag
if I have a main.js file that holds most of my JS code AND it's always included in my views, then I put that line first thing in the file.
After that, you use it like:
url : base_url + 'account/check_user'
Anyway, the first slash / in your url tells the browser to go to the URL root which would not be the right place to put your url chunk in! for example:
if your CI installation is in ci folder and your URL is: domain.com/ci/contorller/method/
Then your URL will become: domain.com/contorller/method/!!
I'm usually assigning the base_url() to a JS variable right in the head to have it available to all methods. Something like this
<script type="text/javascript">
var baseUrl = "<?php echo base_url() ?>";
</script>
You should actually be using CI's site_url() function. base_url() is useful for generating a URL to a resource (such as script or stylesheet), but site_url() is the best choice when generating a URL to a page within the app itself, such as when making an Ajax request, as described.
So the best code to use would be something along these lines:
<script type="text/javascript">
var site_url = "<?php echo site_url() ?>";
</script>

Categories

Resources