Passing array values to js - javascript

So current setup is as following:
PHP:data.php
<?php
$method = $_SERVER['REQUEST_METHOD'];
$data = array(
"16508",
"16498",
"16506"
);
if ($method === "GET") {
echo json_encode($data);
}
?>
JS:
$.get("./page_asset/data.php").then(function(returned) {
data = JSON.parse(returned);
};
Now, how do I parse the data without getting the specific php page (as I don't want to rely on the specific php address such as "/page-asset/data.php").
For example:
PHP:
<?php
$data = array(
"16508",
"16498",
"16506"
);
?>
I simply want to pass these values to js without relying on the page url.

You can use PHP to create the Javascript in the original page. json_encode() can be used to convert a PHP value to the analogous JS literal.
<?php
$data = array(
"16508",
"16498",
"16506"
);
?>
<script>
var data = <?php echo json_encode($data); ?>;
</script>

You can use a hidden field:
<input id="my-data" type="hidden" value='<?php echo json_encode($data)?>' />
And then you can parse the input value from javascript:
var data = $.parseJSON($('#my-data').val());

Related

Can I make a php function that turns all the data in a database into variables that can transfer to javascript

I'm making a virtual worlds. I need to add players. Is it possable to make a php function that finds all the data in a database/player data and turns each line into a variable so I can tranfer it into javascript. The function would look something like,
function data() {
Finddata_from("players");
Create var p.$number;
}
You may create the Javascript Code and just echo it.
function data() {
$data = ['john' => 200, 'marc' => 200];
echo '<script>', PHP_EOL;
foreach($data as $playername=> $score) {
printf('var %s = "%s";' . PHP_EOL, $playername, $score);
}
echo '</script>', PHP_EOL;
}
Example output:
<script>
var john = 100;
var marc = 200;
</script>
Writing values to JavaScript on the page is no different than writing values to HTML. Consider the following example of writing a value to HTML:
<div>
<p><?php echo "some value"; ?></p>
</div>
This would result in:
<div>
<p>some value</p>
</div>
From PHP's perspective, there was only that one single PHP statement. Everything else outside of the <?php ?> tags is just text sent directly to the browser without PHP's involvement. What's in that text doesn't matter. It can just as easily be JavaScript. For example:
<script>
var someValue = "<?php echo "some value"; ?>";
alert(someValue);
</script>
Would emit:
<script>
var someValue = "some value";
alert(someValue);
</script>
Try to use a JSON (JavaScript Object Notation):
<?php
$con = mysqli_connect($host, ...);
$sth = mysqli_query($con, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
?>
<script>
var _obj = <?php echo json_encode($rows) ?>;
console.log(_obj);
</script>

Get javascript variable value in php

I need to get javascript variable value in php file.
html example:
UPDATE:
$html = '
<script>
window.runParams.adminSeq="3423423423423";
window.runParams.companyId="2349093284234";
</script>';
Shout I use regex ? regex is very complex to me... any help ?
<?php
$html = '<script>
window.runParams.adminSeq="3423423423423";
window.runParams.companyId="2349093284234";
</script>';
$variables = ["adminSeq", "companyId"];
$counter = 0;
foreach($variables as $variable) {
preg_match_all('/"(.*?)"/', $html, $matches);
${"$variable"} = ($matches[1])[$counter];
$counter++;
}
echo $adminSeq; // Prints out: 3423423423423
echo $companyId; // Prints out: 2349093284234
?>
You can also use GET requests to do this. The link would look like http://localhost/?adminSeq=3423423423423&companyId=2349093284234 then get out these values in PHP with:
<?php
$adminSeq = $_GET["adminSeq"];
$companyId = $_GET["companyId"];
?>

jQuery take array from php file and display in html

This is my php script to display json data:
$get_chat = "SELECT * FROM chat WHERE u_id1='$u_id' && u_id2=2 ORDER BY data DESC";
$run_chat = $conn->query($get_chat);
if ($run_chat->num_rows > 0) {
while($chat_row = $run_chat->fetch_assoc()) {
echo json_encode( $chat_row );
}
}
This is my result from php file:
{"u_id1":"1","content":"ae","u_id2":"2","data":"17\/03\/27 02:02"}
{"u_id1":"1","content":"ax","u_id2":"2","data":"17\/03\/27 02:01"}
{"u_id1":"1","content":"fd","u_id2":"2","data":"17\/03\/26 11:49"}
{"u_id1":"1","content":"hh","u_id2":"2","data":"17\/03\/26 11:47"}
And now I whant to display all of this in html.
Try something like:
<?php while($chat_row = $run_chat->fetch_assoc()): ?>
<p><?= $chat_row['content']; ?></p>
<?php endwhile; ?>
No need to use json_encode unless you want a Javascript object from my understanding, and it doesn't seem like that's what you're trying to do.

array from php to javascript (need fresh decision)

I have found these two ways:
1st way (width incorrect)
<?php
$arr = new Array (...);
?>
<input id="arr" value="<?php echo json_encode($arr); ?>" hidden>
<script>
$(function (){
var arr = $("#arr").val(); // array with trash
});
</script>
2nd (we need control sequence)
<?php
$arrJS = json_encode($arr);
?>
<script>
var arrJS = <?php echo $arrJS; ?>; // good array
</script>
Question: Is there a better attempt?
Have you considered using AJAX? Here's an example:
Javascript:
$.ajax( "example.php" )
.done(function(json) {
var jsObject = json;
})
and in your 'example.php' file:
<?php
$arr = new Array ('element1'=>'value1', 'element2'=>'value2');
header("Content-type: text/json");
echo json_encode($arr);
exit;
?>

how to pass json object into javascript function in php

i have a json object.
$json = json_decode($data,true);
it looks like-
array(5) {
["screenShareCode"]=>
string(9) "021113322"
["appletHtml"]=>
string(668) ""
["presenterParams"]=>
string(396) "aUsEN5gBYi4vlIEGpk0="
["viewerUrl"]=>
string(65) "http://api.leap.com/v2/viewer/021113322?accountid=mynet"
["origin"]=>
string(3) "API"
}
alert('?php echo $json; ?>');
when i am trying to assign this into javascript variable it gives me an error saying "unterminated string constant".
You don't decode it, in PHP or JavaScript. The contents of a JSON string is a valid JavaScript literal.
<?php
...
?>
<script ...>
var data=<?php echo $data; ?>;
alert(data["screenShareCode"]);
<?php
...
Try:
alert(<?php echo json_encode($json); ?>);
or:
alert(<?php echo $data; ?>);
You're a bit confused about terminology. $data is a JSON string, $json is a PHP array that you got by decoding the JSON string.
Try the following code. I have created a php file named sample.php. We have a php array named $data. Encode that data in to json using json_endode(). That results json formatted data. Then we can assign it into a java script variable like var jsonData = <?php echo $jsonData ?>; Note that this is done inside <script> tag.
<?php
// We have some data
$data = array(
"screenShareCode"=>"021113322",
"appletHtml"=>"",
"presenterParams"=>"aUsEN5gBYi4vlIEGpk0",
"viewerUrl"=>"http://api.screenleap.com/v2/viewer/021113322?accountid=mynet",
"origin"=>"API"
);
// Convert it into json format.
$jsonData = json_encode($data,true);
?>
<script>
// Assign that json data to a java-script variable
var jsonData = <?php echo $jsonData ?>;
// To view the full data
console.log(jsonData);
// You can take a specific data like this.
alert(jsonData.presenterParams);
</script>

Categories

Resources