accessing database values in javascript - javascript

Well
The situation is we are using mysql.We have written the queries and extracted the result from the assoc array.Now how do we access the result from javascript.
$query = "SELECT firstname FROM employees;
$result = mysql_query( $query , $resource );
$value= mysql_fetch_assoc( $result);
extract( $value );
Now does the javascript code be like
<script type="text/javascript">
function somefunction(){
var databasefield = document.getElementsByName("firstname").value;
}
</script>

You need to add the firstname value into your PHP-generated HTML somehow. You could output it as a Javascript variable, or you could output it as a hidden INPUT field.

You can write your PHP page to deliver a JSON string like:
callBack({employee:{firstName:'Jim', lastName:'Black'}});
Where callBack is a function that exist in your page before the script tag pointing to your PHP.
<script>
function callBack(json){
...
}
</script>
<script src="/request.php?some_param=234"></script>
This technique is called JSONP.

It depends on what you want to do with the data from the query. If you want programmatic access to lots of data from Javascript then one good way is to use JSON notation. Basically, your PHP script will generate a snippet of javascript source code that represents a collection of values or basic javascript objects. You could do this with typical PHP templating style, or you can use a JSON library for PHP that is used to respond to a request coming from javascript running in the browser.

Related

PHP json to a JavaScript variable inside an HTML file

I write the following script that creates a nice JSON of all the images under the current folder:
<?php
header('Content-type: application/json');
$output = new stdClass();
$pattern="/^.*\.(jpg|jpeg|png|gif)$/i"; //valid image extensions
$dirs = array_filter(glob('*'), 'is_dir');
foreach ($dirs as $dirname) {
$files = glob(''.$dirname.'/*');
$images = preg_grep($pattern, $files);
$output->{$dirname} = $images;
}
echo json_encode($output, JSON_PRETTY_PRINT);
?>
I have an HTML file with a basic page and I want to display the JSON's data in a formatted way after some javascript manipulation.
So the question is how can I get the PHP data into a javascript variable?
<html>
...
<body>
<script src="images.php"></script>
<script type="text/javascript">
// Desired: Get access to JSON $output
</script>
...
<div>
<img ... >
</div>
</body>
</html>
I tried to put both https://stackoverflow.com/a/61212271/1692261
and https://stackoverflow.com/a/50801851/1692261 inside that script tag but none of them work so I am guessing I am missing something fundamental here (my ever first experience with PHP :)
you should focus on what needs to be done, but currently you are trying to implement your own idea. maybe you should change your approach and do what you want in another way?
passing php variable to js is possible. but for what reason do you need this json? if you want to operate with it to generate html (f.e show images to user) you can do it on pure php without js. if you need exactly json you can generate json file with php and and get this file via additional js request. but the simplest way is
// below php code that generates json with images
$images = json_encode($output, JSON_PRETTY_PRINT);
...
// php code but in html template
<script type="text/javascript">
var images = "<?= $images ?>";
</script>
I won't guarantee that this js line is going to work but you get the idea)
P.S you dont need to use stdClass for such purposes. we do it via arrays (in you case it will be associative arrays), arrays are very powerful in php. json_encode() will generate same json from both array or object. but if this part of code works fine that let it stay as it is
I took #Zeusarm advice and just used ajax (and jquery) instead.
For others need a reference:
Nothing to change in PHP script in the original post.
Add jquery to the HTML file with <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Make a GET request like this:
<script type="text/javascript">
var images = ''
$.get('images.php',function (jsondata) {
images = jsondata
});
I am sure this is not the cleanest code but it works :)

How to place php variable in javascript object in different? [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Executing PHP code inside a .js file
(5 answers)
Closed 2 years ago.
I am trying to fetch data from php, store it as json and load it into my javascript code.
I stored my variable in php like this:
$data = array[];
$data = json_encode($raw_data);
Now I want to retrieve that data and use it in my javascript file.
I tried to use the following code in my js file:
var data ="<?php echo $data ?>";
[screenshot]: https://i.stack.imgur.com/pDfsf.png
If the data is only needed once on page load, you can use a script bloc inside the PHP code and then use a JS function to fetch it. But if data is being updated according to the user's interaction with the page, keep in mind that you can't send data from server side in PHP to the client side in JS without using AJAX.
I suggest you read about and use one of these 3 methods:
XHR
fetch
or axios
You are declaring the string to the variable data by using quotes.
Please remove the quotes and that would behave as per your expectations.
So your code should be replaced by the below lines.
var data =<?php echo $data ?>;
var data = <?php echo $data ?>;
or
var data = JSON.parse("<?php echo $data ?>");
The most obvious problem is your quote marks, which make the variable a string in JavaScript, rather than a complex object with a data structure. So any references to properties etc in the variable would not work. The quote marks should be removed so that the data is rendered as an object literal into the emitted JavaScript.
But there's another signficant issue: if this is being done in a .js file as you state, then the PHP interpreter is not running there, so the echo won't work (quotes or no quotes), because it isn't executed by PHP and turned into data. You'd just see the PHP code directly embedded in the JS code.
You'd have to echo the data into a script block in the .php file, then call the appropriate function in your .js file and pass the data as a parameter. This will work nicely if the data is only needed once.
e.g.
PHP file
<?php
$data = array[];
$data = json_encode($raw_data);
?>
<script src="someJsFile.js"></script>
<script>
var data = <?php echo $data ?>; //inject the data into the JS as an object literal
someFunc(data); //pass the data to a function in someJsFile.js
</script>
JS file:
function someFunc(data) {
//your code to process the data
}
If you need to keep it updated during the lifetime of the page, then you'll need AJAX to be able to request new data from the server, as suggested in one of the other answers.

How to pass javaScript values to PHP

How to pass javaScript values to PHP, my code is following
<script>
function a{
var b = a;
}
</script>
<button onclick="a(2)">Values</button>
<?php
$select = mysql_query("select * from tabl1 where id='values'"); // values comes here
echo $select;
?>
There's a lot of thing you could do.
Principal things you have to know is that javaScript run on the client side (browser), while PHP is running on the server.
Then If you want to pass a variable from your JS to your PHP you have to make a server call.
There's various way you can use in order to send variable from client to server.
As I understand from your example, it looks like your php code and your javascript on the same file. so maybe call your file another time will be enough for you.
Let's say your file's name is index.php.
<script>
function yourJavascriptFunction(id) {
window.location.href = "index.php?id=" + id;
}
</script>
Then in change your PHP code to this:
<?php
$select = mysql_query("select * from tabl1 where id='".$_GET['id']."'"); // values comes here
echo $select;
?>
$_GET will get the variable you've sent in your Js function.
Doing like this will refresh the page.
May be you don't want to refresh the page? Then look at the ajax way.
I hope it helps you

Inserting Javascript variable into PHP

I want to paste two variables from javascript to PHP so I tried
$.post("index.php", {myQuery: myFinalSQL, action: "show_all_stories_sorting"});
where myFinalSQL is a string in javascript
In index.php, I try to printout the myFinalSQL with
echo $_POST['myQuery'];
But it didn't work. Would you please tell me how to insert javascript variables to PHP?
You using wrong approach.
It is bad way to interract with server by such method (inserting php variable in <? ?> tags into script tag).
You should use this:
$.post("ajax.php/myGlobalAction", params, callback);
In callback you will do with your data all what you need.
Example:
var params = {
id: 5
};
$.post( "ajax.php?action=getSqlQueryForSomething", params , function( data ) {
$( ".sqlQuery" ).html( data.sqlQuery );
});
So you have complex architecture problem if you need to work with php and js like this. Change your architecture before it's too late.
If you want to add value from PHP to Javascript you can use :
<script>
var myQuery = "<?php echo $myQuery; ?>;
</script>
But, if you want to add value from Javascript to PHP, you'r not allowed because PHP is server based and javascript is text based.
If you used $.post() :
$.post("index.php", {myQuery: myFinalSQL}, *your_javascript_action* );
in your index.php, you can use this :
if(isset($_POST['myQuery'])){ // checking method
echo $_POST['myQuery'];
}

What is the most efficient and correct way of handling PHP array variables within JavaScript and being able it obtain those values using indexing

THE QUESTION
What is the most efficient and correct way of handling PHP array variables within JavaScript and being able it obtain those values using indexing.
I have a MYSQL database and have a PHP script that creates an indexed row array of the database information.
Now that this information is within the array i am comfortable about echoing this data on screen from within PHP.
i.e.
echo $lastplayed[1]['artist'];
My next step is to take the array into JavaScript so that i can use the variable information to display data on screen, make calculations and create an Ajax timer that looks for a value from a variable and refreshes the page..
Its basically a internet radio station that will display what is and has been played and when a counter reaches zero will refresh the page. (the counter being time left of a song)
I could echo each variable into a separate PHP script and then use JavaScript to call each of those PHP scripts that contain the different variables (This seems long-winded) AND puts unnecessary request strain on the MYSQL server
**I really feel that there must be a better way of transferring and handling the data, surely there must be some type of bridge between PHP and JavaScript, should i be looking into JSON ?
So my end result is to be able to take an indexed array from PHP, transfer this array into JavaScript and be able to call on different variables from within the array using indexing (i.e call the variable that resides in result 3 column 3)
And while this is happening i will be using separate PHP and JavaScript files...
Here is my code for the PHP part.
<?php
date_default_timezone_set('Europe/London');
require_once("DbConnect.php");
$sql = "SELECT `artist`, `title`, `label`, `albumyear`, `date_played`, `duration`,
`picture` FROM historylist ORDER BY `date_played` DESC LIMIT 5 ";
$result = $db->query($sql);
$lastplayed = array();
$i = 1;
while ($row=$result->fetch_object()) {
$lastplayed[$i]['artist'] = $row->artist;
$lastplayed[$i]['title'] = $row->title;
$lastplayed[$i]['label'] = $row->label;
$lastplayed[$i]['albumyear'] = $row->albumyear;
$lastplayed[$i]['date_played'] = $row->date_played;
$lastplayed[$i]['duration'] = $row->duration;
$lastplayed[$i]['picture'] = $row->picture;
$i++;
}
$starttime = strtotime($lastplayed[1]['date_played']);
$curtime = time();
$timeleft = $starttime+round($lastplayed[1]['duration']/1000)-$curtime;
$secsremain = (round($lastplayed[1]['duration'] / 1000)-($curtime-$starttime))
?>
Any thoughts on this would be greatly appreciated and thanks so much for your time.
Justin.
PROGRESS:
Thanks for the comments, i really need to take a JavaScript course at this point...
Now i have created a new output.PHP file that does the following
<?php
require_once("dblastplayedarray.php");
echo json_encode($lastplayed);
?>
So this file now echo's out the data i need in a JSON format from my array $lastplayed.
#VCNinc you say that i now can use the following code to take the data into JavaScript
<script>
var array = <?=json_encode($lastplayed)?>;
</script>
Please could you detail where i put the path information in this code so that the program knows where to look for the .PHP file output.php
Am i doing this right.. should i be printing the data into another .PHP file and then use your code to take the array into JavaScript..
Thanks
Justin.
JSON is the bridge!
You can "export" the variable to a json string and print on the output:
echo json_encode($lastplayed);
TIP: if the php file is used to show a html GUI AND you still want output a JSON too, you can create a GET variable like "&json=1" and, before output your HTML GUI, you do a IF. This way tou can use the same php file to output a GUI and the JSON. WHen you do the request via ajax, you call using the "&json=1".
if(isset($_GET['json']) && $_GET['json']==1){
echo json_encode($lastplayed);
exit;
}
Then, use AJAX to download this JSON string by calling your php script.
$.getJSON(url, function (json) {
//here the 'json' variable will be the array
//so you can interact on it if you want
$.each( json, function( key, value ) {
alert( key + ": " + value ); //here you can do anything you want
});
});
If you have a PHP array $array, you can easily export it into JavaScript like this:
<script>
var array = <?=json_encode($array)?>;
</script>
(and from that point you can manipulate it as JSON...)

Categories

Resources