Catching php mysql variable in javascript - javascript

Im wondering how to catch mysql row in javascript, i tried to do that this way:
var x = <?php
mysql_connect(Not important);
mysql_select_db(not important);
$zapytanie = "SELECT (times) FROM dane WHERE email='$email'";
$idzapytania = mysql_query($zapytanie);
$wiersz = mysql_fetch_row($idzapytania);
echo $wiersz[0];
mysql_close (notimportant);
?>;
alert(x);
But this is not working. Any solutions? Sorry if this questions seems to be lame but i not the best in php/js, but have few things to do.

You should enclose the output of PHP in single quotes if you want it to be treated as a string in javascript. Like this:
var x = '<?php
mysql_connect(Not important);
mysql_select_db(not important);
$zapytanie = "SELECT (times) FROM dane WHERE email=\'$email\'";
$idzapytania = mysql_query($zapytanie);
$wiersz = mysql_fetch_row($idzapytania);
echo $wiersz[0];
mysql_close (notimportant);
?>';
Or alternatively, replace echo $wiersz[0]; for echo "'". $wiersz[0] ."'";

Try this
<?php
mysql_connect(Not important);
mysql_select_db(not important);
$zapytanie = "SELECT (times) FROM dane WHERE email='$email'";
$idzapytania = mysql_query($zapytanie);
$wiersz = mysql_fetch_row($idzapytania);
$w=$wiersz[0];
mysql_close (notimportant);
?>;
<script>
var x =<?php echo $w ?>
alert(x);
</script>

If you want to pass an array from PHP to jquery/javascript, the best way would be using JSON. Pseudocode:
var x=JSON.parse(<?php echo json_encode($array); ?>);

<script type="text/javascript">
setVariables('<?php echo $tag_name ?>', '<?php echo $client_id ?>');
</script>
and then creating that function in your .js file to utilize those values and do what you need.
function setVariables(name, id){
var tag_name = name
var client_id = id
//Operations that need these values.
}

write bundles to javascript!
Personally whenever transferring initilisation data from PHP to the client I find it best to combine the data into an array, and use casting and json_encode (as per Helpful's answer) to make a final structure that is nice and easy to use on the JavaScript side. This saves echoing different variables all over the place, and will automatically handle any type and escape syntax that is required i.e. wrapping strings with quotes, or back-slashing internal quotes in strings.
<?php
$export = array();
mysql_connect(Not important);
mysql_select_db(not important);
$zapytanie = "SELECT (times) FROM dane WHERE email='$email'";
$idzapytania = mysql_query($zapytanie);
$wiersz = mysql_fetch_row($idzapytania);
mysql_close (notimportant);
$export['x'] = !empty($wiersz[0]) ? $wiersz[0] : 'default';
?>
var data = <?php echo json_encode((object) $export); ?>;
Obviously the above is a little overkill for just one small value, however, if there ever became more than one value — something that could quite easily happen after further coding — it would be very easy to extend:
$export['x'] = !empty($wiersz[0]) ? $wiersz[0] : 'default';
$export['something_else'] = 54321;
Then all you need do to access these values in JavaScript is:
data.x
data.something_else
why use an array and why cast to an object?
The reason why I use an associative Array on the PHP side is because I find writing to arrays cleaner in PHP than Objects — not a huge fan of the -> notation. Also instantiating an Array is easier and seemingly more native than an Object in many versions of PHP. I then cast to an object before writing to JavaScript because I find the opposite is true in JavaScript, it's easier and nicer to read when accessing objects rather than arrays. This is all personal taste however.
NOTE: When defining your keys in the $export array you should be wary to keep to standard variable naming conventions i.e. either use camelCase/interCaps or convert spaces to underscores. Whilst you can get away with using any characters, even spaces, it will mean accessing the data from the JavaScript side becomes more cumbersome.
another thing to bear in mind
When setting variables in JavaScript it's often seen as a bad thing to pollute the global namespace. This basically means writing variables at the top level of run-time, that attach to themselves to global Object (usually Window), so that they are accessible by every bit of JavaScript code that runs in that execution. It is seen as bad because unless you use a likely unique variable name, collisions with other code can occur i.e. if both bits of code rely on the same global variable.
If you just output your data var at the top of your script it will become part of the global namespace, and using something as bland as data would be a prime example of something to avoid. It may not matter at all for small projects that aren't going to be extended or worked on by multiple coders, but it is always a good idea to get into the habit of avoiding this.
You can of course just use a variable name that is more unique to your project e.g. myProjectData, or if you have an over-arching namespace that defines your project i.e. examples of which would be jQuery, JSON, console; you could attach it to that e.g. Project.data.
However, if you wanted a more general approach you can also do this by wrapping your JavaScript code in an anonymous function.
<?php
$export = array();
$export['random_value'] = 'Where\'s my monkey?';
?>
(function( data ){
/// data will only be available inside this function
/// or to other sub functions defined inside this function.
console.log(data.random_value);
})(<?php echo json_encode((object) $export); ?>);
With the above code you should end up with your JavaScript always having a nice bundle of values to access, properly escaped and formatted, that have come straight from PHP in an easy way, and that doesn't pollute the global namespace.
WARNING: Obviously it should be noted that if you use the above anonymous wrapper method and you call in any other script files within your page, they wont be able to access data unless you pass the object to that code in some way. This is why people often prefer to have an over-arching namespace object for their project i.e. MyProject.data. However you do not necessarily have to do this — due to the benefit of having all your values bundled up in a singular JavaScript object — because passing it to other code is as simple as sending one variable as a parameter to a function i.e. other.code(data)

Related

How to minify "a priori" php files that output javascript?

We have some PHP files that output JavaScript code. I know things could have been different, but that was a decision taken during the start of the project.
We have several PHP files which generate Javascript files, something like:
<?php Header("content-type: application/x-javascript");
if(strlen($_GET['country']) != 2){ exit;} //avoids code injection
include_once($_SERVER['DOCUMENT_ROOT'].'/countries/'.$_GET['country'].'.php');?>
/*Define GLOBAL Javascript variables*/
var COUNTRY = "<?php echo $GLOBALS["country"]; ?>";
/*Language code according to ISO_639-1 codes*/
var LANGUAGE = "<?php echo $lang_CT[$GLOBALS["country"]]; ?>";
...
What is the best way to minify that code a priori, i.e., not when the file is called or echoed, but on the server, using the Javascript minifying rules?
edit: I've been thinking and things might be complex to achieve, I imagine this case of invalid JS code:
var str = <?php echo "'a string';"; ?>
which outputs a valid JS code
var str = 'a string';
but basically I was wondering if there is any basic minifying option, to remove double spaces, comments and breaklines, which would then not affect the generated JS code.
AFAIK there is no support for achieving this as an integrated feature of PHP as you obviously want to minify code which is actually ignored by PHP due to not residing in process instructions <?php and ?>. So you will need to process your PHP code with another tool. If that is to be written in PHP, too, I might give the following code fragment a try:
$sequence = preg_split( '/(<\?php|<\?=|\?>)/', $phpFileCode, null, PREG_SPLIT_DELIM_CAPTURE );
$isPHP = false;
foreach ( $sequence as &$segment ) {
switch ( $segment ) {
case '<?php' :
case '<?=' :
$isPHP = true;
break;
case '?>' :
$isPHP = false;
break;
default :
if ( !$isPHP ) {
$segment = preg_replace( array(
'#\s*/\*.*?\*/\s*#', // matching multi-line comments
'#\s*//.*$#m', // matching single-line comments
'#\s+#', // matching arbitrary sequences of whitespace incl. multiple blank lines
), array(
' ',
' ',
' ',
) );
}
}
}
$phpCodeMinified = implode( '', $sequence );
Note: This code is just a scribble ... I haven't tested it, but I think it's pointing towards some quite simple approach.
A more elaborate approach might
use this code to replace all PHP process instruction sequences with some special global variable name in Javascript rather than detecting segments not belonging to PHP. E.g. use names like window.__PHPreplacedXXXX where XXXX is the numeric index of an array the whole replaced PHP segment has been pushed to for recovery in step 3 below. By using global names they won't be mangled in next step.
mangle the resulting code using some JS minifier such as uglify or minify referenced before.
process the resulting minified JS file and revert previous replacement of PHP sequences with global names.
This might enable use of more aggressive minification, but might result in broken JS code either when minifier is optimizing and reorganizing code. The risk isn't that high though when sticking with "simple" minifiers.
Here's what I would do; put all the Javascript in a variable using Heredoc, for example:
$js = <<<EOD
console.log('Valar Morgulis');
console.log('Valar Dohaeris');
EOD;
Then use the minify_js() function that can be found here on Github, or something similar. Here's the function:
function minify_js($input) {
if(trim($input) === "") return $input;
return preg_replace(
array(
// Remove comment(s)
'#\s*("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')\s*|\s*\/\*(?!\!|#cc_on)(?>[\s\S]*?\*\/)\s*|\s*(?<![\:\=])\/\/.*(?=[\n\r]|$)|^\s*|\s*$#',
// Remove white-space(s) outside the string and regex
'#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/)|\/(?!\/)[^\n\r]*?\/(?=[\s.,;]|[gimuy]|$))|\s*([!%&*\(\)\-=+\[\]\{\}|;:,.<>?\/])\s*#s',
// Remove the last semicolon
'#;+\}#',
// Minify object attribute(s) except JSON attribute(s). From `{'foo':'bar'}` to `{foo:'bar'}`
'#([\{,])([\'])(\d+|[a-z_][a-z0-9_]*)\2(?=\:)#i',
// --ibid. From `foo['bar']` to `foo.bar`
'#([a-z0-9_\)\]])\[([\'"])([a-z_][a-z0-9_]*)\2\]#i'
),
array(
'$1',
'$1$2',
'}',
'$1$3',
'$1.$3'
),
$input);
}
minify_js($js); would get you the minified JS. You can use variables inside Heredoc, more information here.

How can I bring two variables from php to jQuery (on separate values).

This is confusing and i've read documentation and some other questions here in StackOverFlow. And I just don't understand (Or the answers doesn't fit my need)
Here's the thing: I have a php with two values from a SQL query. So far, everything is great. I have them in two separate values.
Here's a piece of the two values:
$puntoslocal = json_encode($reglocal["puntaje"]);
$puntosvisitante = json_encode($regvisitante["puntaje"]);
But I need in Javascript (using or not jQuery) to get these two values ($puntoslocal and $puntosvisitante). Here's where i get lost.
How can I bring these two separate values in two separate vars?
Thank you so much, I know this may sound silly, but I really don't know how to do this.
It's as easy as an array
$arr = array(
"puntoslocal" => $reglocal["puntaje"],
"puntosvisitante" => $regvisitante["puntaje"]
)
echo json_encode( $arr );
You can get the 2 variables using an ajax request or putting them along with HTML.
Try this in your php file:
<script>
puntoslocal = '<?php echo $puntoslocal; ?>';
puntosvisitante = '<?php echo $puntosvisitante; ?>';
</script>
If needed, can be done without json too, by concatenating the two strings and split them in jquery:
In your php-file:
echo $arr[0].":".$arr[1];
and jquery:
success: function(data){
if(data){
var myarr = data.split(":");
$('#div1').html(myarr[0]);
$('#div2').html(myarr[1]);
}
}
Note: use another divider when your vars contain the :

Storing php value in javascript variable

I am trying to store php value in my javascript variable. But this code is giving me syntax error. Is the code correct ?
var b = <?php echo $tagValue;?>;
alert("B is " +b);
You have to make sure that your webserver interprets that file as a php file. then you have to adapt your code, because it looks like you could have an error in your js code in the end:
var b = "<?php echo $tagValue;?>";
alert("B is " +b);
(I have added quotes). Does not apply, if you are sure that $tagValue is only numeric.
In case you don't really know what kind of value your $tagValue is or you simply want to make sure you won't fail you should use json_encode($tagValue):
var b = <?php echo json_encode($tagValue);?>;
alert("B is " +b);
Please note that in case $tagValue is an array/object your js-alert won't be very usefull :)
Easiest way i've found to do it without worrying about character escaping or XSS is to convert the contents of the variable to JSON. All it takes is to echo json_encode($tagValue); instead of echo $tagValue;
make a function maybe can help u.
this is an example
// your php code
$tagValue = 'value';
getValue($tagValue);

How do you access a PHP variable with JavaScript? [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 4 months ago.
I have a PHP file that creates a randomized string stored in a variable. I want to access this variable with JavaScript but the methods I've found online doesn't seem to be working. This is the code I have so far:
var test = "<?php echo json_encode($myVariable); ?>";
alert(test);
$myVariable is just a string: "testing".
I thought "testing" would be alerted but instead the code itself is (<?php echo json_encode($myVariable); ?>). When I take away the quotations, nothing happens. I'm very new to JavaScript so I'm not sure what's wrong. Is there another way I can access a PHP variable with JavaScript?
you can transfer variable contents by this
var test = "<?php echo $myVariable; ?>";
alert(test);
There are few way of accessing variables from php with javascript AJAX/Cookies/_SESSION or echo directly to javascript.
AJAX
Is more readable with better separations between layers it also allows for async transfer. BUT it can be very slow adding HTTPrequest can lead the website to slow down alot if there is alot of variable to request from php.
Cookies
I dont recommend it as there will be alot of necessary data store on the client side.
_SESSION
I recommend you using _SESSION as new developer will find it easier to use. it works similar to cookies but the only difference is once the page is closed the data is erase.
Echo directly to javascript
Easy to implement but horrible code practise.
All the above answers I explain quite vague do your research on topics, look for _SESSION to start with then move on to AJAX if appropriate.
Code example
PHP
if you are getting data from mysql
$_SESSION["AnyVariable"] = my_sql_query ("SELECT someData FROM someTable")
Or if its just a variable in PHP
$SESSION["aVariable"] = whateverValue;
JavaScript
<script type="text/javascript">
function someFunction()
{
var someVariable = '<%= Session["phpVariableSessionName"] %>';
alert(someVariable);
}
</script>
json_encode produces output ready for javascript, you must not put it into quotes:
var test = <?php echo json_encode($myVariable); ?>;
Try it the other way around ...
<?php echo "var test = '" . json_encode($myVariable) . "';"; ?>

assigning php return value to a javascript variable

I have a database form on a MySql table on which I have a javascript function to populate the options of a select tag. Those options are fetched from a table of clients who have a status of either "Active" or "Inactive", and the return values are of those clients where their status is active. In the event an order is loaded where the client status is inactive, I'm trying to add a handler for inactive clients. The form loads from a php script that left joins the client table to the main table, where clientId in the main table is equal to Id in the client table. So, I have the name and id of the client fetched outside of the function to populate the options list, regardless of their status.
There is one line that is causing me fits. I have searched this site and others and have found many solutions, but none have worked for me so far. This is the line:
var txt = <?php echo $row[`clients`.'name']; ?> ;
What is returned in Chrome and Firefox debuggers is, "Uncaught syntax error: Unexpected token <". The debugger shows: var txt = <br />
I've tried enclosing the php script in single quotes, double quotes, and without quotes, and still no luck. Any thoughts, anyone?
About an hour later--> I found a workaround. I tried all of your suggestions, but none worked in this instance. var_dump and json_encode confirmed what I knew already, that the returned data was valid. Regardless of any of the variations in syntax, they all returned the same error. What I did was to apply the same syntax as above, but in a hidden input:
<input type="text" id="cName" hidden value="<?php echo $row[`clients`.'name']?>" />
Then changed the javascript code to this:
var txt = document.getElementById('cName').value;
Everything else works perfectly. Of course, I still have lingering thoughts about the use of backticks, and would prefer that I had a better, and safer code. As I mentioned somewhere, I simply copied the sql syntax directly from phpMyAdmin. In this instance, if I substitute single quotes for the backticks, the input returns nothing. Well, thanks all. If anyone wants to contribute more, I'll be glad to hear about it.
That's illegal PHP syntax, and very dangerous syntax in general. Try doing a var_dump($row) to see exactly what's in that array. Probably you want something more like
var txt = <?php echo json_encode($row['clients.name']); ?>;
instead.
Note the use of json_encode(). This will ENSURE that whatever you're spitting out in the JS code block is actually syntactically valid javascript.
e.g. consider what'd happen if you ended up with
var txt = Miles O'Brien;
^^^^^--undefined variable;
^--- another undefined var
^--- start of a string
^^^^^^^---unterminated string.
with json_encode(), you end up with
var txt = "Miles O'Brien";
and everything's a-ok.
var txt = "<?php echo $row['clients']['name']; ?>";
var txt = <?php echo $row[`clients`.'name']; ?> ;
Consider how PHP parses this:
var txt = is to be output directly to the client.
Enter PHP mode.
echo the following expression.
Evaluate $row[`clients`.'name'].
First we need to determine the array index, which is the concatenation of `clients` and 'name'.
Backtick in PHP is the execution operator, identical to shell_exec(). So PHP attempts to execute the shell command clients, which probably fails because that isn't what you intended and it doesn't exist. Consequently, at this stage, PHP outputs an HTML error message, starting with a line break <br />.
Your client now has var txt = <br /> (you can verify this by inspecting the HTML source of the page returned to your browser), which it attempts to evaluate in its JavaScript context. This gives rise to the "unexpected token" error that you have witnessed.
As others have mentioned, you probably meant to do something like $row['clients']['name'] or $row['clients.name'] instead—but without seeing the rest of your PHP, it's impossible to be sure. Also, as #MarcB has observed, you need to be certain that the resulting output is valid JavaScript and may wish to use a function like json_encode() to suitably escape the value.
The error comes from the fact that your return value (a string in javascript) must be in quotes.
Single quotes will take whatever is between them literally, escapes (like \n ) will not be interpreted, with double quotes they will.
var txt = "<?php echo $row['clients']['name']; ?>";
is what you want
Change this
var txt = <?php echo $row['clients'.'name']; ?> ;
to this:
var txt = <?php echo $row['clients']['name']; ?> ;

Categories