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.
Related
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()})
});
});
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
The following code works fine, the function load() sends the selected radio button info to the PHP page and display the returned:
<head>
<script>
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('myPHPfile.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
<input type="radio" name="category" value="30" />ButtonC
</div>
<div id="myDiv">Click the button to load results</div>
</body>
myPHPfile.php
<?php
if( $_REQUEST["selectedButtonValue"] )
{
$buttonPHP = $_REQUEST['selectedButtonValue'];
echo "Value button is ". $buttonPHP;
}
?>
I need an alert box message of the returned PHP value, inside the script, as follows:
;
$("#myDiv").load('myPHPfile.php', {selectedButtonValue : buttonValue});
alert(<?php $buttonPHP ?>);
;
Would it be possible to write the PHP value inside JavaScript?
You can just add a callback function in .load(), like this:
$("#myDiv").load('myPHPfile.php',
{selectedButtonValue : buttonValue},
function(data){
alert(data);
});
If you only want the value of the $buttonPHP to be displayed in the alert, change your echo to
echo $buttonPHP;
instead of
echo "Value button is ". $buttonPHP;
*Note: There is an issue with .load() function. It will not work if you access your html page locally/directly, you need to put it on a server. Or you can use xampp, wampserver, etc. *
Hope it helps.
Yes, almost had it:
alert('<?php echo $buttonPHP; ?>');
Your doing it right now, but you need to output the value:
alert(<?php echo $buttonPHP ?>);
On a sidenote, it seems like you don't have it really clear to you what happens.
HTML, css and javascript runs on the clients(the visitors) computer and the PHP code runs on the server, that means that the you can always combine php output with client-side code, and this is done regularly, just as you have done.
This is also one of the reasons why PHP is so flamed as a language, because of it low threshold to get started with, it is way to easy to create code that works, but that is a hell to maintain.
This is not a comment to your code, but a general reflection on php.
Either, you have to put the alert in the PHP generated code:
echo "<script type=\"text/javascript\">alert('Value button is ". $buttonPHP . "');</script>";
Or you have to use $.get function:
$.get('myPHPfile.php', {selectedButtonValue : buttonValue}, function(data) {
alert(data);
});
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
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