I have a simple button calling a js function. There I want use the php var with dynamic names. Any Idea please?
<?php
$counter = 1;
${"fotos" . $counter++} = array();
foreach ($row as $item) {
${"fotos" . $counter}[] = $item->img;
}
?>;
//will generate two vars:
$fotos = [img1];
$fotos1 = [img1,img2];
<button type="button" onClick="verAdjuntos(<?php echo $counter; ?>)" class="btn btn-xs btn-default"> View</button>
//parameter passed verAdjuntos(1) forxample
When id parameter is null, the if condition works fine. But adding id to php var name is the problem...
<script type="text/javascript">
function verAdjuntos(id){
if (id == null){
var fotos = <?php echo $fotos ?>; //output ok
alert(JSON.stringify(fotos));
}else{
var fotos = <?php echo $fotos?> + id; /// how do name $fotos1 here?
alert(JSON.stringify(fotos));
};
}
</script>
Doing alert work fine too:
alert(JSON.stringify(fotos1));
Solved doing with array of arrays from php variable.
<?php
$counter = 1;
$fotos = array();
foreach ($row as $item) {
$allfotos[$counter] = array($item->img);
$counter++;
}
?>;
//will generate two vars:
$fotos[1] = [img1];
$fotos[2] = [img1,img2];
<button type="button" onClick="verAdjuntos(<?php echo $counter; ?>)" class="btn btn-xs btn-default"> View</button>
<script type="text/javascript">
function verAdjuntos(id){
if (id == null){
var fotos = <?php echo $allfotos ?>;
alert(JSON.stringify(fotos));
}else{
<?php
$js_array = json_encode($allfotos);
echo "var javascript_array = ". $js_array . ";\n";
?>
var fotos = JSON.parse(javascript_array[id]);
alert(JSON.stringify(fotos));
};
}
</script>
Related
I have a column in my db, tip_sting:
1 row example(each one has the same format):
G1-11, G2-21, P2-50, P4-20, P100-2,
I'm using this when editing a item(I want to create(as many selects in the string) and put the values automaticaly in the select) :
https://jsfiddle.net/avrzwt6k/
So I was thinking of doing something like:
$pieces = explode(",", $tip_stingu);
$a=count($pieces); // piece1
echo $a;
echo '<br>';
echo $pieces[1]; // piece2
echo '<br>';
$tip_stinga=explode("-",$pieces);
I just dont know how could I continue?
Do you need something like this?
<?php
$items = "G1-11, G2-21, P2-50, P4-20, P100-2";
$pieces = explode(",", $items);
echo ("<select>");
foreach ($pieces as $piece) {
$tip_stinga = explode("-", $piece);
echo ('<option value="'.$tip_stinga[1].'">'.$tip_stinga[0].'</option>');
}
echo ("</select>");
?>
Using PHP & Javascript you can do:
<html>
<body>
<form id="example" name="example">
<select name="myName" id="myID" onchange="updateText()">
<?php
$tip_stingu = "G1-11, G2-21, P2-50, P4-20, P100-2,";
$pieces = explode(', ', $tip_sting);
$piece1 = explode('-', $pieces[0])[1];
foreach($pieces as $piece) {
$tip_stinga = explode("-", $piece);
echo ('<option value="'.$tip_stinga[1].'">'.$tip_stinga[0].'</option>');
}
echo '</select><input type="text" value="'.$piece1.'" id="quantity" /><br />'
?>
</form>
<script>
function updateText() {
document.getElementById("quantity").value = document.getElementById("myID").value;
}
</script>
</body>
</html>
You also have a trailing comma at the end of your example, if that's a problem you can use:
echo ('<option value="'.rtrim($tip_stinga[1], ',').'">'.$tip_stinga[0].'</option>');
instead of:
echo ('<option value="'.$tip_stinga[1].'">'.$tip_stinga[0].'</option>');
I already get the id from a php loop for my checkboxes, and pass them as a string(maybe not because I could not split them with comma) in parameter, then I need to check if the checkbox is checked in javascript using the ids I passed through.
It doesnt seem like I can split it in javascript as well, and after I ran the for loop, the data is undefined in the new string.
Do you have any ideas? Please help
here is my php
echo "<div id='addstock'>";
$ids = '';
while($row_add = mysqli_fetch_array($result_add)){
$id=$row_add['id'];
$company = $row_add['companyname'];
//create checkbox for company
echo "<p class='checkbox'><input type='checkbox' name='stocks' id='".$id."' value='".$id."'>".$company."</p><br>";
$ids .= $id;
}
echo "</div>";
echo "<p class='input'><input type='submit' class='submitbutton' value='Submit' onclick='updatetable(".$ids.",".$user.")'></p>";
here is my javascript
//update table after add to stock
function updatetable(ids,user){
var url = "update.php";
//var res= ids.split(" ");
alert(ids);
var stocks = "";
//check if the checkbox is checked
for(var id in ids){
if(document.getElementById(ids[id]).checked)
{
stocks += ids[id];
alert(ids[id]);
}
}
//alert(stocks);
var data = "ids="+stocks+"&user="+user;
alert(data);
ajaxRequest(url, "POST", data, true, proceedUpdate);
}
function proceedUpdate(response){
target_div = document.getElementById("tablediv");
target_div.innerHTML = response;
}
Try this:
<div id="addstock">
<?php
$ids = array();
while($row = mysqli_fetch_array($result_add)) {
$ids[] = $row_add['id'];
echo '<p class="checkbox"><input type="checkbox" name="stocks" id="' . htmlspecialchars($id) . '" value="' . htmlspecialchars($id) . '">' . htmlspecialchars($company). '</p><br>' . "\n";
}
?>
</div>
<p class="input">
<input type="submit" class="submitbutton" value="Submit" onclick="updatetable('<?php echo htmlspecialchars(implode(',', $ids)); ?>', '<?php echo htmlspecialchars($user); ?>')">
</p>
I tried to add checked property to a specific checkbox using jquery, but it seems doesn't work properly.
Checkbox Function Display
function product_category_loop_array ($product_category_array = array (), $parent_id = 0, $margin = -20) {
if (!empty ($product_category_array[$parent_id])) {
$margin = $margin + 20;
foreach ($product_category_array[$parent_id] as $items) {
echo "<input style='margin: 0 0 0 ".$margin."px; overflow: hidden;' id='".$items['id']."' class='category_checkbox left' name='product_category[]' type='checkbox' value='".$items['id']."'><label class='category_checkbox_label left'>".$items['name']."</label>
<div class='clear'></div>";
product_category_loop_array ($product_category_array, $items["id"], $margin);
}
}
}
function product_category () {
$db_connect = mysqli_connect (db_host, db_username, db_password, db_name);
$product_category_query = $db_connect->query ("SELECT id, name, parent_id FROM `product_category` ORDER BY name ASC");
$product_category_array = array ();
if (mysqli_num_rows ($product_category_query)) {
while ($row = mysqli_fetch_array ($product_category_query, MYSQLI_ASSOC)) {
$product_category_array[$row['parent_id']][] = $row;
}
product_category_loop_array ($product_category_array);
}
}
HTML
<div id="tabs-2" class="product_detail hide">
<div class="left">
<form class="product_detail_form" method="post" action="">
<?php product_category () ?>
<p class="detail_submit"><input name="save_product_category" type="submit" value="Save"></p>
</form>
</div>
</div>
Jquery
<script>
$ (document) .ready (function () {
<?php echo $hide_div ?>;
var selected_array = <?php echo json_encode ($product_category_selected) ?>;
$.each (selected_array (key, value) {
$ ("#"+value).prop("checked", true);
});
});
</script>
Any help will be appreciated.
Use
$ ("#"+value).attr("checked", "checked");
<script>
$(document).ready(function() {
<?php echo $hide_div ?>;
// DECODE JSON IN JS
var selected_array = $.parseJSON(<?php echo json_encode ($product_category_selected) ?>);
$.each(selected_array(key, value) {
$("#" + value).prop("checked", true);
});
});
</script>
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.
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'