I have a PHP file that is going to write a two-dimensional array in JavaScript:
<?php
print "<script language='javascript'>";
print " extra[0][0] = new Array(1,'Bob',12);";
print " extra[0][1] = new Array(2,'Alice',18);";
..
// Need to assign the extra[1][0], extra[1][1] and so on.
print "</script>";
?>
Mu.js:
var extra = new Array();
...
How do I assign the two-dimensional array from PHP to a JavaScript variable?
json_encode is your friend: json_encode in the PHP manual
<script type="text/javascript">
var jsArray = <?= json_encode($my_array) ?>;
</script>
Yes, wvanbergen is right, json_encode is your friend. You can create the array as JSON:
<?php
$extra = array(
array(1,'Bob',12),
array(2,'Alice',18)
);
echo "var extra = " . json_encode($extra) . ";";
?>
And in your javascript it will output:
var extra = [[1,"Bob",12],[2,"Alice",18]];
<script type="text/javascript">
var jsArray = <?php json_encode($my_array); ?>;
</script>
Related
i have an xml file in my server that i want to extract a list of IDs with php then convert the array to a JSON using json_encode() and put it in a $_SESSION variable, to make this clear my ideal JS function is:
function getIDs() {
var x = <?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>;
if(x == '') {
$.post('getPL.php','PL_name=cool&q=IDs',function(responseText){
x = responseText;
});
}
//some other code
//return array; // this is an array i use later in js
}
in my getPL.php i have:
$videos_list = $theOne->parentNode->parentNode->getElementsByTagName('video');
for ($i = 0; $i < $videos_list->length; $i++) {
$a = $videos_list->item($i);
$id_out = $a->getElementsByTagName('id')->item(0)->nodeValue;
$array[$i] = $id_out;
}
$IDs = json_encode($array);
$_SESSION['IDs'] = $IDs;
echo $IDs;
break;
if i alert var x = <?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>; i get g8M8kxuaCWk,VWrBFt46J18
but when i alert the responseText i get ["g8M8kxuaCWk","VWrBFt46J18"]
all i want is to extract the IDs from the xml file and put them in a js array object
if there is anything need more tell me
i think you need the put quotes arround the php code in your JS like:
var x = '<?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>';
ok i fixed it
so var x = '<?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>'; would give me an array, which is what i actually want
but the alert(resposeText); was actually giving me a string so i did this JSON.parse(responseText);
thanks to who helped me get to this answer
after this in both cases if i alert(obj[0]); i get the first element so it is working
my ideal JS function becomes:
function getIDs() {
var x = <?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>;
if(x == '') {
$.post('getPL.php','PL_name=cool&q=IDs',function(responseText){
x = JSON.parse(responseText); // this is the difference
});
}
return x;
}
<?php require_once('Connections/root.php'); ?>
<?php $q = mysql_query("SELECT * FROM performer"); ?>
<script> $(document).ready(function () {
$(function() {
var availableTags = ["<?php while($r = mysql_fetch_assoc($q)) { echo $r['username']; } ?>"];
$("#search_box").autocomplete({
source: availableTags
});
});
});
</script>
the script works but it displayes : User1User2User3
and i want it to display:
User1
User2
User3
How do i add a new line after every user and where do i add the line feed
if i make it like this
var availableTags = ["<?php while($r = mysql_fetch_assoc($q)) { echo $r['username'] . " <br />"; } ?>"];
i get User1User2User3 and the br as a string
Separate your PHP logic from your Javascript code. Up top, build a PHP array first:
$tags = array();
while($r = mysql_fetch_assoc($q)) {
$tags[] = $r['username'];
}
Then in your javascript, echo the array JSON encoded:
var availableTags = <?php echo json_encode($tags); ?>;
Note: You are using deprecated mysql_* functions and should switch to mysqli_* or PDO.
As mentioned, your availableTags array has only 1 string variable.
You need to push the string to the Array.
You can try this:
var availableTags = [];
<?php while($r = mysql_fetch_assoc($q)) { ?>
availableTags.push('<?php echo $r['username']; ?>');
<?php } ?>
The generated js array is not what you expect it to be. With your code, you obtain
var availableTags = ["User1User2User3"];
whereas what you need is
var availableTags = ["User1", "User2", "User3"];
Yous should adapt your PHP code to generate the right JS.
I am trying to assign a php echo value to an input generated from a jquery function. But so far no luck. It breaks the function and no results are displayed along with the input field. What is the proper way for this scenario to display php value inside the query function.
PHP
$tablename = "table";
$next_increment = 0;
//$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = $db_con->prepare("SHOW TABLE STATUS LIKE '$tablename'");
$qShowStatusResult->execute();
$results = $qShowStatusResult->fetchAll(\PDO::FETCH_ASSOC);
foreach($results as $value){
$next_increment = $value['Auto_increment'];
}
var nextAutoIncrement = '"'<?php echo $next_increment; ?>'"';
Jquery
newSection.children(':nth-child(1)').children(':first').attr('id', 'auto_id_' + newNum).attr('name', 'auto_id_' + newNum).val(nextAutoIncrement).hide();
Try this
<script language="javascript" type="text/javascript">
var nextAutoIncrement = '<?php echo $next_increment;?>';
</script>
Try like this:
<script language="javascript" type="text/javascript"
var nextAutoIncrement = <?php echo $next_increment; ?>;
</script>
<script>
//if it is anumber
var nextAutoIncrement = <?php echo $next_increment; ?>;
// if ity is a string
var nextAutoIncrement = '<?php echo $next_increment;?>';
</script>
In JS code there is require to define the <script> tag:
$tablename = "table";
$next_increment = 0;
$qShowStatusResult = $db_con->prepare("SHOW TABLE STATUS LIKE '$tablename'");
$qShowStatusResult->execute();
$results = $qShowStatusResult->fetchAll(\PDO::FETCH_ASSOC);
foreach($results as $value){
$next_increment = $value['Auto_increment'];
}
<script type="text/javascript" >
var nextAutoIncrement = '<?php echo $next_increment; ?>';
</script>
I want to get php booelan value with javascript.
That is my code.
<script type="text/javascript">
var $j = jQuery.noConflict();
var isValue = $j(<?php isset($getResult[]); ?>);
alert(isValue);
</script>
php is a server side programming, and javascript is client side. so you need to "echo" the php value to get result on javascript
var isValue = $j(<?php echo isset($getResult[]) ? "true" : "false"; ?>);
You'll have to convert the boolean result of isset() into a string representation of 'true' or 'false' so that it can be understood by the javascript parser. Like this:
var isValue = $j(<?php isset($getResult[]) ? echo 'true' : echo 'false'; ?>);
It should be like this
<script type="text/javascript">
var $j = jQuery.noConflict();
var isValue = $j(<?php if (isset($getResult)){ echo true;} else {echo false;} ?>);
alert(isValue);
</script>
You cannot use $getResult[] for reading using issest. It will return fatal error or you have to specify some index in the array.
If you want to check if it is an array then you can use :
<script type="text/javascript">
var $j = jQuery.noConflict();
var isValue = $j(<?php if (isset($getResult) && is_array($getResult)){ echo true;} else {echo false;} ?>);
alert(isValue);
</script>
<?php
$abc=array();
$abc = (abc, cde,fre);
?>
<script language="javascript" type="text/javascript">
for (var i = 0; i < 3; i++) {
var gdf = "<?php echo $lat['i'];?>";
alert("value ="+gdf);
}
</script>
Following your comment, I think this is what you are trying to do:
<?php
$abc = array('abc', 'cde', 'fre');
?>
<script type="text/javascript">
var gdf = '<?php
for ($i = 0; $i < count($abc); $i++) {
echo "{$abc[$i]}";
if ($i != (count($abc)-1)) echo ", ";
}
?>';
</script>
Will output:
http://codepad.org/KjEH5CmN
<script type="text/javascript">
var gdf = 'abc, cde, fre';
</script>
NOTE
Using implode if you want a single variable would also work well:
http://codepad.org/UwukCY4m
<?php
$abc = array('abc', 'cde', 'fre');
?>
<script type="text/javascript">
var gdf = '<?php echo implode(', ',$abc); ?>';
</script>
You're not looking to assign a single value of the array; you're looking for the whole array. Your JavaScript loop is trying to iterate over the entire $abc array from PHP.
Something like this would work:
var abc = <?php echo json_encode($abc); ?>;
for(var i = 0; i < 3; i++)
var gdf = abc[i];
alert("value = " + gdf);
}
Firstly, to build a PHP array you should be using this notation:
<?php
$abc = array('abc', 'cde', 'fre');
?>
Next, it's not possible use JavaScript to directly loop through your variable that is stored in PHP. You can do something like this instead, performing the loop in PHP:
<?php
$abc=array('abc', 'cde', 'fre');
?>
<script language="javascript" type="text/javascript">
<?php foreach ( $abc as $el ): ?>
alert('value=<?php echo $el ?>');
<?php endforeach ?>
</script>
Or, if you'd really like the loop to happen in JavaScript and not PHP, you can "export" the PHP array to JavaScript by converting the array to a JSON string and outputting it.
<?php
$abc=array('abc', 'cde', 'fre');
?>
<script language="javascript" type="text/javascript">
var abc = <?php echo json_encode($abc) ?>;
for ( var i = 0; i < abc.length; i++ ) {
alert('value=' + abc[i]);
}
</script>