How to pass PHP value to external JavaScript file - php

I am trying to pass my variables from my main page to external JS file. Please see my code.
Main page:
<script type="text/javaScript">
$(document).ready(function(){
var add_project_link="<?= base_url().'add_project/show_form'; ?>";
var add_agent_link="<?= base_url().'agent/add_agent';?>";
});
</script>
External JS
$(document).ready(function(){
alert(add_project_link);
alert(add_agent_link);
});
I got:
uncaught referenceError add_project_link is not defined.
I thought the external JS would catch the variable declared in main page. Any thoughts? Thanks a lot!

Before you call your external JavaScript file, define your variables using PHP:
<script type="text/javascript">
var site_url = '<?php echo site_url(); ?>';
var current_url = '<?php echo current_url(); ?>';
</script>
<script type="text/javascript" src="file.js"></script>
In your external file.js you can now use site_url as a variable.

Take your php generated variables out of document ready. They are not accessible anyhwere else in your code due to closure of the ready event function they are in

What I would do is to store those variables to something easily called by JS later.
<input type="hidden" id="hidden_var" value="<?= base_url().'add_project/show_form'; ?>" />
var add_project_link = $('#hidden_var').val();

You just write in the head tag
<script type="text/javaScript">
var add_project_link="<?= base_url().'add_project/show_form'; ?>";
var add_agent_link="<?= base_url().'agent/add_agent';?>";
</script>
Then load your External JS after the script above

best way is to to store those path in some tags like
<span id="site_url" style="display:none;"><?php echo site_url(); ?></span>
<span id="current_url" style="display:none;"><?php echo current_url(); ?></span>
then you can access this this using jquery like
$('#site_url').html();
$('#current_url').html()

the simplest thing to do is to bring the script into a script tag on the php page
you can go down the URL string variable route, but it's unnecessary I think

Related

How to pass a PHP variable to a .JS file using JQUERY?

I'm a JQUERY begginner. I'm trying to pass a PHP variable to a js file so that i can use it in JQUERY! But found no resource to learn to do so. I'm able to pass a JQUERY variable to a different php file but I couldn't pass PHP variable to a Jquery file. Is really possible to do so?
function.php:
<?php $variable = $fetch['username']; ?>
app.js : How can use this variable in app.js file below?
$(document).ready(function(){
var flwbtn = $(".findrowpplfollowbtn");
flwbtn.click(function(){
var selectflwusername = $(this).parent().prev().last().find(".findpplrowusername").text();
$.post("../php/flw.php",{flwusernameselected:selectflwusername})
});
});
Echo it to HTML temaplate. If it's some structure/array use for example json format.
<script>
<?php $variable = $fetch['username']; ?>
var js_variable = <?php echo json_encode($variable); ?>
</script>
or
echo some hidden element like
<input type="hidden" id="custId" name="custId" value="<?php echo($fetch['username']); ?>">
and grab if with Jquery like
<script>
$( "#custId" ).value();
</script>
with your code
JS:
$(document).ready(function(){ var flwbtn = $(".findrowpplfollowbtn");
flwbtn.click(function(){
var selectflwusername = $(this).parent().prev().last().find(".findpplrowusername").text();
$.post("../php/flw.php",{$( "#custId" ).value()})
});
});

how to php variable value assign as java script

<script>
var id=`$`php;
</script>
I've added php variable store as JavaScript.
but some thing wrong in my code. what wrong with there please help me
You need PHP tags around the variable name and you need to use echo to print out the value
<script>
var id = <?php echo $whatever; ?>;
</script>
Use quotes if it's a string
<script type="text/java script">
var id='<?php echo $id;?>';
</script>
Try in this way
<script>
var id=<?php echo $var;?>
</script>
Try this
<script>
var id= <?php echo $php;?>;
</script>

Php vars within javascript

I have a bit of code to record a certain action
$('#record').click(function(){
$.get("../confirm.php", { "id": '<?php echo $record; ?>' }, function(data){});
});
Which works fine, but i don't want the page to be full of javascript and such as i have other things like this on it too, so i am trying to move it to a js file.
In the php file
<script type="text/javascript">var record = "<?= $record ?>";</script>
<script type="text/javascript" src="jsfile.js"></script>
In the js file
$('#record').click(function(){
$.get("../confirm.php", { id: record}, function(data){});
});
But it doesnt want to play ball, any ideas how to do this?
Make 'record' as class of div and assign php variable $record as its id.Use event.target.id to get variable $record from div.
<div class="record" id="<?php echo $record;?>">
Your code here
</div>
And Use this
$('.record').click(function(event){
var record=event.target.id;
//your code here
});
If I may a suggestion to you. Set in the view on the element the ID. Then when the action is clicked, get the id for the data.
Example:
<input type="text" name="inputName" id="<?php echo $record; ?>" class="btnToRecord" />
$('.btnToRecord').click(function(){
var clickedElement = $(this);
$.get("../confirm.php", { id: clickedElement.attr("id") }, function(data){});
});
Edit: Correction for $(this) was pointing to the get instead to the element, putting in a var will fix the problem

javascript variable to php variable

I need to assign javascript client Date (examp. - 2012/02/03 16:00:00) to php variable. Any idea how? I was trying to use this lines and changing them in million different ways. But I just cant get it.
Today = new Date();
var date = ????
var date = "<?= $date ?>";
I solved it this way:
<input id="date" type="hidden" name="date">
<script type="text/javascript">
document.getElementById('date').value = Date();
</script>
But thank you very much all.
Add an input in your form
<input type="hidden" name="clientDate">
if you are using jquery add this to set the client date input when the user submits the form
$(YOUR_FORM_SELECTOR).on("submit", function() {
$("[name=clientDate]").val(new Date());
});
If you want to go with vanilla javascript follow this answer
you can't simply assign a javascript variable to a php variable. php runs on the serverside and is executed before javascript.
you can however submit an ajax call with the value of your javascript variable to a php script.
you might wanna have a look at jquery's post function.
$.post("test.php", { yourDate: date } );
in your PHP script you'll be able to access the date with $_POST['yourDate']
you can also use a form and a hidden field as you say in your comment.
in this case you can use (assuming you're using jQuery)
$('#id_of_input').val(date);
This will convert js variable to php variable and php variable to js variable
<script>
function jstophp(){
var javavar=document.getElementById("text").value;
document.getElementById("rslt").innerHTML="<?php
$phpvar='"+javavar+"';
echo $phpvar;?>";
}
function phptojs(){
var javavar2 = "<?php
$phpvar2="I am php variable value";
echo $phpvar2;
?>";
alert(javavar2);
}
</script>
<body>
<div id="rslt">
</div>
<input type="text" id="text" />
<button onClick="jstophp()" >Convert js to php</button>
<button onClick="phptojs()">Convert php to js</button>
PHP variable will appear here:
<div id="rslt2">
</div>
</body>
Demo: http://ibence.com/new.php

Call jQuery var in php function

Is it possible ?
Here is example :
<script>
var id=$(this).val();
$('#region').append(< ? php get_region(#####) ?>);
</script>
I need to call "var id" instead of #####
If you know what the id of "this" is going to be before the page is rendered on the browser (and THEN the javascript code will be run), then you can do the following:
<script>
<?php $id = $whatever_the_id_is; ?>
$('#region').append(<?php get_region($id); ?>);
</script>
If you don't know what the id will be of "this" before rendering the page, then you need to use ajax to run the get_region() function server side and return the string you're looking for.
in my understanding, php is loaded first on the server, and then goes to client side ex. javascript (which includes jquery). You can obtain a copy of php variable in client side very easily, by either embedding a hidden variable. ex.
<input type="hidden" value="<?php echo $a; ?>" />
or
<a title="<?php echo $a; ?>" />
You can also do this,
<script language ="javascript"> var global_variable="<?php echo $a; ?>"; </script>
However, php function can not refer to javascript variable.

Categories