Pass PHP output to jQuery - php

I have got this code
/* Popup for hot news */
$(document).ready(function() {
var $dialog = $('<div></div>')
.html('text to be shown')
.dialog({
autoOpen: false,
title: 'Table'
});
This code is in my JavaScript files which are included by header.php.
How to pass PHP output to this function?
Inputing <?php echo($mydata)?> in .html('') above does not solve anything.
Any reason why this gives an error?
Thanks for helping!

First of all your code is having some problem, $ in php is a prefix of variable and $ in jQuery is a selection sign. You can view the html source(the output) on browser for debug.
I can think of three ways to do so:
(1)The way you have mentioned should work, see the code below
<?php $foo='hi'?>
<script>
alert("<?php echo $foo?>");
</script>
(2)Another way is to separate server side and client slide code clearly for better maintenance
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<?php echo"<div id='foo' style='visibility:hidden;'>HI</div>"?>
<script>
alert($('#foo').text());
</script>
(3)The last way is by passing variable from the URL http://example.com/example.php#hi
<script>
var foo= location.href.split('#')[1];
alert(foo);
</script>

Adding <?php //code?> to your JS files do nothing because JS files are not executed by Apache. You can either use Ajax to request for data once your page loads (if the data doesn't need to be there at start) or you can add those PHP code blocks to your HTML code.
Using Ajax (goes in your JS file)
$(document).ready(function(){
var u = 'data.php';
var d = {};//data
$.get(u, d, function(data){
//got by data. lets invoke some methods here
});
});
Putting it in your HTML (goes in your HTML file)
var __DATA = '<?php //output some data I prepared earlier ?>';
//I'm using __ and capitol case to denote a global variable. Just personal preference
<script src='myjsfile.js' type='text/javascript'></script>
//the variable __DATA is available to your JS file and you can use it

Related

echo in jquery doens't output as expected

I found on stackoverflow how to use a php variable in jquery, but on my test page, it simply isn't working:
$('#q').keyup(function(e) {
var test = "<?php echo 'test123'; ?>";
alert(test);
});
The code above outputs "" literally in the box where I want it to say "test123". I tried using single quotes instead of double, other small changes ... Didn't get it to work. Am I missing something?
The code above sits in a .js file which is linked in a .php page, which is (again) linked in my index.php file via require_once.
You should not use PHP in javascript files (.js). Javascript and PHP are different languages. PHP works on the server-side and Javascript on the client-side.
You have to put this code in your <head> under the jquery.js file, like this:
<script type="text/javascript" src="link-to-jquery-file.js"></script>
<script type="text/javascript">
$('#q').keyup(function(e) {
var test = "<?php echo 'test123'; ?>";
alert(test);
});
</script>
Also make sure your file extension ends with .php
There is also an advanced solution for this, and that would be using the header() function. Save as javascript.php or someting Example:
<?php
header("Content-Type: text/javascript");
?>
$('#q').keyup(function(e) {
var test = "<?php echo 'test123'; ?>";
alert(test);
});
Then attach the file in your <head> like this:
<script type="text/javascript" src="javascript.php"></script>
Goodluck!

How to call function from jquery to php?

PHP:
$product_code = $_GET['product_code'];
$countryCode = getCountryCode();
<script src="js/register_script.js" type="text/javascript"></script>
Jquery:
function getCountryCode() {
countryCode = qrcode_getinfo(qrCode1,"mfg_c_a_code",0)
return countryCode;
}
I want to get my country code from the jquery to perform some validation task, however, i wasn't able to retrieve the country code. Any idea what should i do for it to work? please note that the library is already been called. (I had read up on examples but dont really understand how it works..)
It is not possible to directly call PHP function from JavaScript and vice versa. Part of the reason for this is that as #Pekka indicated JS runs clientside (in your browser) while PHP runs server-side (on your server).
It is however possible to use AJAX for your purposes:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function getCountryCode()
{
countryCode = qrcode_getinfo(qrCode1,"mfg_c_a_code",0)
return countryCode;
}
function doAjax(){
var countryCode = getCountryCode();
$.ajax({
'url' : '<THE_URL_TO_YOUR_PHP>?countryCode=' + countryCode,
'method' : 'GET',
'success' : function(data){
console.log(data);
// do your handling here
},
'error' : function(data){
console.log(error);
// this function is executed on an HTTP error
}
});
}
</script>
PHP
This is your php file that would do your validation. In principle it is a different file than the file that outputs the html as shown above.
$countrycode = $_GET['countryCode'];
# handle countrycode
echo "<What you want to return to JS>";
Edit
On the additional question of how to get session variables to js.
Would I navigate to your page in my browser, the following would happen: If I requested a file with an .php extension, the PHP processer gets run on it. This processer identifies all code between the tags <?php and ?> as PHP, and thus runs all this code. If it encounters an echo statement, it echo's out the specific value at the location of the php-block.
After PHP is done processing, the page is served (given) to your browser, where it will be interpreted as a combination of HTML/javascript/... Javascript interprets everything between the tags <script> and </script> as javascript.
So, what if we where to make a request to index.php?par=val on your server, and index.php looks like
<script type="text/javascript">
function doStuff(){
var param = <?php echo json_encode($_GET['par']);?>;
}
</script>
(the json_encode function ensures that the variable is in proper json format. Of course you can change the `$_GET['par']; to be whatever you would like.)
Remember, PHP only cares about whats between the <?php and ?> tags, so this would output:
<script type="text/javascript">
function doStuff(){
var param = "val";
}
</script>
You will need to edit this to match your requirements of course, but this is the basics of passing parameters from PHP to client-side (JS)

change php variable with ajax

I have an php variable like this:
PHP Code:
$php_value = 'Am from PHP';
And I want to be able to change this variable with jQuery and the jQuery is on the same page?
You can't.
By the time the page has been delivered to the browser and the JavaScript has run, the PHP program that generated the page will have finished running and the variable will no longer exist.
JavaScript will allow you to send new data to the server (Ajax), where the server could store the data somewhere (a database is usual), and read the response.
JavaScript will also allow you to modify the page in in the browser (DOM) (including with the data included in the response for an Ajax request).
PHP code is run server-side, and jQuery runs on the client. The way to update a PHP variable from jQuery is to have a jQuery call which submits to the PHP page, and have the PHP look for it:
$php_value = 'Am from PHP';
if exists($_POST['php_value_from_jquery']) {
$php_value = $_POST['php_value_from_jquery'];
}
If I understand your question correctly, AJAX cannot post data to PHP code on the same page. I've been told that it can, but it is not trivial - still, I cannot imagine how that is possible. At any rate, AJAX is easy if a secondary PHP file is used.
Here is an example of what I mean. If you try this:
<?php
echo 'Hello';
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body>
</body>
</html>
The popup will contain the HTML for the page.
However, if you use two files:
file1.php
<?php
echo 'Hello';
?>
file2.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'file1.php',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body></body>
</html>
The popup will contain only the word "Hello".
To use ajax, you must call an external PHP file.
After considering the above, note that Quentin's answer is important -- even if you use AJAX to set a PHP variable on the server, that variable disappears after the AJAX completes -- just like the PHP variables all disappear after your index.php has finished rendering the DOM and presenting it to the visitor's browser.
So, what's to be done? Two options.
(1) As Quentin points out, you can store values permanently in a database, or
(2) You can use a PHP superglobal, such as a $_SESSION variable. For example:
Client side: file2.php
var storeme = "Hello there";
$.ajax({
type: 'POST',
url: 'file1.php',
data: 'stored_on_server=' +storeme,
success: function(data) {
alert(data);
}
});
file1.php
<?php
session_start();
$SESSION['a_variable_name'] = $_POST['stored_on_server'];
You can later retrieve that variable value thus:
$.ajax({
type: 'POST',
url: 'file3.php',
success: function(data) {
alert(data); //a popup will display Hello There
}
});
file3.php
<?php
session_start();
echo $SESSION['a_variable_name'];
You can't able to change the php value using javascript. i.e Server scripts runs first after that client side script will take effect in that case you cant able to modify the same, since they already rendered in browsers
If jQuery is going to be processing the data, then you can assign the PHP variable to a jQuery variable like this:
<script>
var jquery_value = <?php echo $php_value; ?>
</script>
As far as I know, because jQuery is client-side and php is server side, it's not possible to assign a jQuery variable back to PHP.

How to pass PHP session variable into Javascript/jQuery function?

I have a PHP page that loads a session variable:
$user_id = $_SESSION['USER_ID'];
Previously, I included my Javascript/jQuery within that page, and added <? echo $user_id; ?> to set the Javascript variable:
$(document).ready(function() {
$(".button").click(function() {
var user_id = <? echo $user_id; ?>
var dataString = 'user_id=' + user_id;
$.ajax({
type: "POST",
url: "../add_user.php",
data: dataString,
});
return false
});
});
However, I'd like to move my Javascript to a separate page and call the script from my PHP page:
<script src="add_user.js" type="text/javascript"></script>
If I do this, I can no longer user <? echo $user_id; ?>, so what is the best way to pass my PHP variable into the Javascript/jQuery function?
You can configure your webserver to treat .js files as PHP scripts, which would let you execute your PHP code from within the .js file.
However, if that's not acceptable, you can always do something like:
<script type="text/javascript">var user_id = <?php echo json_encode($user_id) ?>;</script>
<script type="text/javascript" src="add_user.js"></script>
to define the variable at your PHP script level, and then include the external .js as usual.
If $user_id is always numeric, then the json_encode() bit is overkill, but I've gotten into the habit of using that everywhere I'm generating JS code dynamically. Using json_encode guarantees you're inserting a syntactically correct JS snippet.
<script>
var user_id = <?php echo $user_id; ?>
</script>
<script src="add_user.js" type="text/javascript"></script>
Now you can use user_id in your add_user.js file. Also, I would advise against using PHP short tags.
You will still be able to reference your varible in your external js file
<script type="text/javascript">
var yourvar = <? echo $user_id; ?>;
</script>
<script src="add_user.js" type="text/javascript"></script>
Just start the session on the other side. Its is also more secured, considering that JS data may be corrupted, even deliberately and may be exploited (security).
After starting the session - read the value there.
Of course, this is valid for scripts on the same vhost.

Using smarty variable within a jQuery Function

My php generates some type from the DB and it is passed to a Smarty Variable $X.
With the help of Jquery, I want to be able to click a button, and the content of one of my div will be be replace with $X.
$(document).ready(function(){
$("button").click(function(){
$("#div1").html($X);
});
});
This piece of Jquery script is included in an external js file.
If you have a template file that is parsed where you can output PHP->Smarty assigned variables, something you could do is create a global JS variable in the template, and then use that global variable within your JS as normal.
Such as:
Template file
<script type="text/javascript">
var MyGlobalVar = "{$MyGlobalVar}";
</script>
Global.js file
$(document).ready(function(){
$("button").click(function(){
if (MyGlobalVar != '') {
$("#div1").html(MyGlobalVar);
} else {
alert('Error! Error! Abort!');
}
});
});
Note, you could output the Global.js file with it being parsed by Smarty (although... this is probably not a great idea) and inject your PHP->Smarty variables this way. This would treat the Global.js included file as a Smarty template.
To do so, you would need to use {literal}, probably name the file with a .php file ending (so it was PHP-parseable), and add a PHP header() call so PHP outputs the file contents to the browser as a Javascript content-type.
Global.js
<?php
header("content-type: text/javascript");
?>
var MyGlobalVar = "{$MyGlobalVar}";
{literal}
$(document).ready(function(){
$("button").click(function(){
if (MyGlobalVar != '') {
$("#div1").html(MyGlobalVar);
} else {
alert('Error! Error! Abort!');
}
});
});
{/literal}
Additionally, on the PHP side, you might want to consider adding slashes to your variable, especially if the JS variable will contain html or other bits of text that will use single/double quotes.

Categories