array from php to javascript (need fresh decision) - javascript

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

Related

Keeping multiple values in an index of JavaScript Array

I would like to keep values like below
var skus = [];
<?php
foreach($col as $Product)
{
?>
<script type="text/javascript">
skus['<?php echo $Product->id; ?>'] = '<?php echo $Product->sku; ?>','<?php echo $Product->color; ?>';
</script>
<?php
}
?>
But this is not working.
UPDATE
Later I would like to search values of the array skus using that index.Is it possible in JavaScript like below??
var my_array = [];
my_arry['abc'] = 'pqr','xyz';
Is it possible to store multiple values in an index of an array in JavaScript??
Thanks
It looks like the problem with your code is a typo in the JS. I assume you want to make an array out of the PHP values in JS, so it looks like all you're missing is the square brackets around your value list.
Like so:
skus['<?php echo $Product->id; ?>'] = ['<?php echo $Product->sku; ?>','<?php echo $Product->color; ?>'];
You can use some objects:
So:
skus['<?php echo $Product->id; ?>'] = {'sku':'<?php echo $Product->sku; ?>','color':'<?php echo $Product->color; ?>'};
So every element of the skus array is an object with two keys
My PHP is a little rusty but is this what you mean?
<script type="text/javascript">
var skus = [];
<?php foreach($col as $Product) { ?>
skus['<?php echo $Product->id; ?>'] = ['<?php echo $Product->sku; ?>','<?php echo $Product->color; ?>'];
<?php } ?>
</script>
You need [] on that middle line because you're trying to save two values into each "cell" of the array, right?

Passing array values to js

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

Assigning PHP Variables To Javascript Variables Not Working

I am currently having trouble with this. I would like to make one of my variables in Javascript have a PHP value. Here is what I mean:
<script>
JSvariable = <?php echo $PHPvariable; ?>;
</script>
For some reason that is not working. Here is my full (snippet) of code:
<script>
currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
I am sure it is some stupid mistake, but I can not seem to find it! What is the problem? Thank you!
PS #parentcommentholder is an input field, and it just had the value 0 after the field is supposed to of been changed.
Here is some source:
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<script>
var currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
<input id="parentcommentholder"></div>
Don't forgot for give quotes ' or ". Use following:
<script>
var JSvariable = '<?php echo $PHPvariable; ?>';
//or
var JSvariable = "<?php echo $PHPvariable; ?>";
</script>
Reason: If php variable contains string and if while assigning it to javascript variable we shall not give quote like:
<?php $PHPvariable = 'String';?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = String;//which will give error in javascript
But this will work fine if PHP variable contains a numeric value like:
<?php $PHPvariable = 2;?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = 2;//which will work perfect
Complete code should be:
<script>
var currentreplyid = "<?php echo $allpostcomments[$key]['replyid']; ?>";
//or if you are sure your variable contains int value
var currentreplyid = parseInt("<?php echo $allpostcomments[$key]['replyid']; ?>");
$('#parentcommentholder').val(currentreplyid);
</script>
Try the below instead of using javascript (as I don't think you need it):
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<input id="parentcommentholder" value="<?php echo ((int)$allpostcomments[$key]['replyid']>0) ? $allpostcomments[$key]['replyid'] : 0; ?>" />
<?php
}
?>
If your defiantly sure $allpostcomments[$key]['replyid'] is bringing back a value, this should work without any issues.

Two identical .load() don't work together

I have these two scripts.
First:
$(document).ready(function(){
refreshStatus();
});
function refreshStatus(){
setTimeout(function(){
$('#div_top_info').load('load_status.php');
}, 2000);
}
Second:
var skill = <?php echo json_encode($skill_, JSON_UNESCAPED_UNICODE); ?>;
var skill_final = <?php echo json_encode($skill_final, JSON_UNESCAPED_UNICODE); ?>;
var camp_final = <?php echo json_encode($camp_final, JSON_UNESCAPED_UNICODE); ?>;
var jmeno = <?php echo json_encode($jmeno_, JSON_UNESCAPED_UNICODE); ?>;
var pozice = <?php echo json_encode($pozice_, JSON_UNESCAPED_UNICODE); ?>;
var delka = <?php echo json_encode($delka_, JSON_UNESCAPED_UNICODE); ?>;
var opravneni = <?php echo json_encode($opravneni, JSON_UNESCAPED_UNICODE); ?>;
$(document).ready(function(){
refreshPrehled();
});
function refreshPrehled(){
$('#checkboxes').load('load_prehled.php', {
skill: skill,
skill_final: skill_final,
camp_final: camp_final,
jmeno: jmeno,
pozice: pozice,
delka: delka,
opravneni: opravneni
}, function(){
setTimeout(refreshPrehled, 12000);
});;
}
Second is below first on my page.
Does this mean only one setTimeout can run on one page?
And if thats the case, how do I put these two together into one script when I wanna load two different .php into two different html objects?
Thanks for help!
EDIT
Also html objects:
<div class="div_top_info" id="div_top_info"></div>
<form action="index.html" method="POST" id="checkboxes"></form>
I have tried different variations of timeouts, setInterval, different positioning, delay one of the timeouts. Really don't know. I fight this second day now.
EDIT2
Important info:
Sorry bad info.
They load, but into each php (load_status and load_prehled) I put this code:
$z_cas_editace = date('Y-m-d H:i', filemtime('datazelva_UL.txt'));
And second one updates the time and first one doesn't.
The first function also works fine when I put it in place of second.
Just my head spinning...
var skill = <?php echo json_encode($skill_, JSON_UNESCAPED_UNICODE); ?>;
var skill_final = <?php echo json_encode($skill_final, JSON_UNESCAPED_UNICODE); ?>;
var camp_final = <?php echo json_encode($camp_final, JSON_UNESCAPED_UNICODE); ?>;
var jmeno = <?php echo json_encode($jmeno_, JSON_UNESCAPED_UNICODE); ?>;
var pozice = <?php echo json_encode($pozice_, JSON_UNESCAPED_UNICODE); ?>;
var delka = <?php echo json_encode($delka_, JSON_UNESCAPED_UNICODE); ?>;
var opravneni = <?php echo json_encode($opravneni, JSON_UNESCAPED_UNICODE); ?>;
$(document).ready(function(){
refreshStatus();
refreshPrehled();
});
function refreshStatus(){
setTimeout(function(){
$('#div_top_info').load('load_status.php');
}, 2000);
}
function refreshPrehled(){
$('#checkboxes').load('load_prehled.php', {
skill: skill,
skill_final: skill_final,
camp_final: camp_final,
jmeno: jmeno,
pozice: pozice,
delka: delka,
opravneni: opravneni
}, function(){
setTimeout(refreshPrehled, 12000);
});;
}

Saving variables within while loop

not pretty sure how you do this. But I want to save my javascript variables as data(1,2,3,4,...) in my while loop. Happy for any help! Thanks
$id = 0;
while($rows = mysql_fetch_array($data)){
$id = $id + 1;
$data = $rows['data'];
?>
<script>
var id = '<?php echo $id; ?>'; //1,2,3,4,5,6,...
var data = '<?php echo $id; ?>'; // Example - Data 1 = Frog, Data 2 = Bird
// So here I want to sava variables so the name will be
// var "data+'id'";
// And the output is data for that row
</script>
<?php
}
?>
//And here outside I want to use the variables like this:
document.write(data1); writes out "Frog"
document.write(data2); writes out "Pig"
<script>
var jsData = [];
<?php
$id = 0;
while($rows = mysql_fetch_array($data)){
$data = $rows['data'];
?>
jsData[<?php echo $id; ?>] = '<?php echo $data; ?>';
<?php
$id++;
}
?>
</script>
This would yield a JS Array called jsData where your ID is the index and which is filled with the PHP $data values.
Declare $data = new Array(); just before the WHILE LOOP then in the WHILE LOOP you could do $data['id'][$id]= $id which will collect all the IDS.
Add $data['data'][$id]= $row['data'] below it so as also to collect each data that you want.
in the script tag do this:
var id = <?php echo '['.join(',', $data['id']).']' ?> //will create --> [1,2,3,4,5,6,7]
var data = <?php echo '['.join(',', $data['data']).']' ?> //--> ['cat', 'dog', 'cow', 'sheep']
now you can access the variable in the Javascript array created eg. $data[0] // 'cat'

Categories

Resources