user3370412
user3370412

Reputation:

Catching php mysql variable in 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.

Upvotes: 0

Views: 87

Answers (5)

Vishwanath Tadahal
Vishwanath Tadahal

Reputation: 116

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>

Upvotes: 0

Pebbl
Pebbl

Reputation: 36065

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)

Upvotes: 0

GoalDone
GoalDone

Reputation: 343

<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. }

Upvotes: 0

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] ."'";

Upvotes: 2

Helpful
Helpful

Reputation: 706

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); ?>);

Upvotes: 0

Related Questions