Pass PHP var to js function - javascript

I would like to pass a var from PHP to Javascript. I did this but it does not work. Can someone help me? If you tell me where I'm wrong I learn.
<script>
var passo = <?php echo 'hello'; ?>;
</script>
<button type="button" onclick="funzionepassaggio(passo)" class="btn btn-info btn-lg" data-toggle="modal" data-target="#ModalSubmit"><?php echo "empty"; ?></button>
<script>
function funzionepassaggio(pass) {
alert("hello" + pass);
}
</script>
The answer is hello undefined.
I have one other question! The variable that I have to pass is located within a loop, and of course he always passes the last value! How can I do so that has passed the value that the variable at that time? This is the code:
for ($a = 0; $a < 2; $a = $a + 1) {
?>
<td>
<script>
var passo = "<?php echo $rigauno->nome; ?>";
</script>
<button type="button" onclick="funzionepassaggio(passo)" class="btn btn-info btn-lg" data-toggle="modal" data-target="#ModalSubmit"><?php echo "vuoto"; ?></button>
</td>
<?php } ?>

you need to incude the quotes, so it will be valid string:
<script>
var passo = "<?php echo 'hello'; ?>";
</script>
or better call json_encode that will convert whatever you pass as JSON:
<script>
var passo = <?php echo json_encode($data); ?>;
</script>

json_enocde variable which you want to pass
<script>
var passo = <?php echo json_encode('hello'); ?>;
</script>

$pass='your string or your value ';
<button type="button" onclick="funzionepassaggio('<?php echo $hello; ?>')" class="btn btn-info btn-lg" data-toggle="modal" data-target="#ModalSubmit"><?php echo "empty"; ?></button>
<script>
function funzionepassaggio(pass) {
alert("hello" + pass);
}
</script>

Related

JS apply only for first element

I need some help to apply js code for all elements, but for now works only for first on each page.
On page are items with buy buttons, that is created by script, so all buttons have same id but is more than one of them - and I can't apply script that disable button if some condition, only work for first button.
<?php $elem = getElement('button_basket'); ?>
<button disabled = "true" onclick = "checkInput(event)" id="b1" class="btn btn-warning btn-lg btn-block tobasket <?php echo $elem['content_tr'] ?>" product_id="<?php echo $v['id']; ?>" name="<?php echo $prdata['full_name'] ?>" nametr="<?php echo $prdata['name1_tr'] ?>" url="<?php echo $cur_url; ?>catalog/<?php echo $v['img_url']; ?>" price="<?php echo $v['price']; ?>" <?php if($v['sold']==1) echo 'sold="true"'; ?>><?php echo $elem['content'] ?></button>
<?php $elem = getElement('button_oneclick'); ?>
<p class="prod-oneclick <?php echo $elem['content_tr'] ?>" <?php if($v['sold']==1) echo 'sold="true"'; ?>><?php echo $elem['content'] ?></p>
<script type="text/javascript">
function checkInput(event){
<?php
$cookie_basket = $_COOKIE['basket'];
$tempo = urlencode($cookie_basket);
$countChars = mb_strlen($tempo);
//echo $countChars;
?>
let test = '<?php echo $countChars;?>';
let btncheck = document.querySelectorAll('[disabled]');
// var step;
// for (step = 0; step < 5; step++) {
if (test > 80){
document.getElementById("b1").disabled = true;
}else{
document.getElementById("b1").disabled = false;
}
}
// window.onload = checkInput(event);
// }
</script>
if will need can provide full page script.
You should use data attributes and delegation
Also your script can be vastly simplified
let test = '<?php echo $countChars;?>';
window.addEventListener("load", function() {
[...document.querySelectorAll('[disabled]')].forEach(btn => btn.disabled = test > 80)
});
<?php
$cookie_basket = $_COOKIE['basket'];
$tempo = urlencode($cookie_basket);
$countChars = mb_strlen($tempo);
?>
<button disabled class="btn btn-warning btn-lg btn-block tobasket <?php echo $elem['content_tr'] ?>" data-product_id="<?php echo $v['id']; ?>" name="<?php echo $prdata['full_name'] ?>" data-nametr="<?php echo $prdata['name1_tr'] ?>" data-url="<?php echo $cur_url; ?>catalog/<?php echo $v['img_url']; ?>"
data-price="<?php echo $v['price']; ?>" <?php if($v[ 'sold']==1) echo 'data-sold="true"'; ?>><?php echo $elem['content'] ?></button>
<p class="prod-oneclick <?php echo $elem['content_tr'] ?>" <?php if($v[ 'sold']==1) echo 'data-sold="true"'; ?>>
<?php echo $elem['content'] ?>
</p>
Final code, fully working for me was:
<script>
function beCheerful() {
<?php
$cookie_basket = $_COOKIE['basket'];
$tempo = urlencode($cookie_basket);
$countChars = mb_strlen($tempo);
?>
let test = '<?php echo $countChars;?>';
window.addEventListener("DOMContentLoaded", function() {
[...document.querySelectorAll('[disabled]')].forEach(btn => btn.disabled = test > 80)
});
}
for (var i = 0; i < 1; i++) {
beCheerful();
}
window.onload = beCheerful;
</script>

post jquery array to php page when checking checkboxes

i have dynamic number of checkboxes and a button to post the checked elements to another page .. here is the code:
<div class="overSelect"></div>
<div id="checkboxes<?php echo $aa['id']; ?>">
<?php
$pid = select::property($aa['name']);
$arr2 = select::properties($pid);
$cc = 1;
foreach ($arr2 as $aa2) { ?>
<div style="padding-right: 20px" class="row"><label>
<input type="checkbox" value="<?php echo $aa2['name'] ?>" name="checks<?php echo $aa['id'] ?>[]"id="check<?php echo $aa['id']; ?>"><?php echo $aa2['name'] ?>
</label></div>
<?php } ?>
</div>
<a class="btn btn-primary btn-sm" name="update-all"onclick="update_all('prop_id<?php echo $aa['id']; ?><?php $counter; ?>','checks<?php echo $aa['id'] ?>')"id="btn-all<?php echo $aa['id']; ?><?php $counter; ?><?php echo $p['id']; ?>">save</a>
i tried this code but it is not working
<script type="text/javascript">
function update_all(a, b) {
var aa = document.getElementById(a).value;
var values = new Array();
$("input:checkbox[name=b]").each(function () {
if ($(this).is(":checked")){
values.push($(this).val());
}
});
alert(aa);
alert(values.length);
alert(values);
}
</script>
if the checkboxes checked .. it's value will be added to the array and posted to php page
any help please .. thanks in advance

Multiple ID's on single button click

HTML + PHP
<?php
for($i=0;$i<5;$i++){
?>
<input readonly class="copyTarget" id="copyTarget<?php echo $i; ?>" value="val<?php echo $i; ?>">
<span>
val<?php echo $i; ?>
</span>
<button class="btn btn-primary" id="copyButton<?php echo $i; ?>" onClick="reply_click(this.id, $('.copyTarget').attr('id'));">Copy</button>
<?php
}
?>
JS
<script>
function reply_click(clicked_id, target_id) {
alert(clicked_id);
alert(target_id);
}
</script>
What i want
I want to get the both values for copyTarget and copyButton as per loop cycle. It means
If current value of $i = 3
then I want alert values like,
clicked_id = copyTarget3
target_id = copyButton3
What i am currently getting is,
If current value of
$i = 3
then I want alert values like,
clicked_id = copyTarget0
target_id = copyButton3
Its taking first value of ID(copyTarget) stored initially. I want current loop cycle value.
Any help would do
Thanks
Why use JS in handler?
Try:
onClick="reply_click('copyButton<?php echo $i; ?>', 'copyTarget<?php echo $i; ?>')"
Also you should store id names (copyButton and copyTarget) in php variable, so you can change them in one place.
You could try something like below. However, I would go by Maxx's answer .. It really depends on what you plan to do with the rest of code etc.
<?php
for($i=0;$i<5;$i++){
?>
<div>
<input readonly class="copyTarget" id="copyTarget<?php echo $i; ?>" value="val<?php echo $i; ?>">
<span>
val<?php echo $i; ?>
</span>
<button class="btn btn-primary" id="copyButton<?php echo $i; ?>" onClick="reply_click(this)">Copy</button>
</div>
<?php
}
?>
<script>
function reply_click(btn) {
var clicked_id = $(btn).attr('id');
var target_id=$(btn).parent().find('span').html();
alert(clicked_id);
alert(target_id);
}
</script>
Try This
<?php
for($i=0;$i<5;$i++){
?>
<input readonly class="copyTarget" id="copyTarget<?php echo $i; ?>" value="val<?php echo $i; ?>">
<span>
val<?php echo $i; ?>
</span>
<button class="btn btn-primary" id="copyButton<?php echo $i; ?>" onClick="reply_click(this.id);">Copy</button>
<?php
}
?>
JS
<script>
function reply_click(clicked_id) {
alert(clicked_id); //clicked id
alert(clicked_id.split('copyButton').join('copyTarget')); // target id
}
</script>

JavaScript value passing

Using SQLite I can list the values in
<div class="text-middle">
<?php foreach($result as $row) ?>
<button class="button button1" id="myBtn" value="<?php echo $row['Id']; ?>" onclick="myFunction()"><?php echo $row['Id']; ?></button>
<?php } ?>
</div>
However when I click on the button it's showing the only the first value in popup alert.
function myFunction() {
var x = document.getElementById("myBtn").value;
alert(x);
}
How can I get the corresponding values in each button?
All of your buttons have the same id attribute. they must be unique within the page. To fix this you can remove the id attribute and pass the reference of the button to the function:
<div class="text-middle">
<?php foreach($result as $row) { ?>
<button class="button button1" value="<?php echo $row['Id']; ?>" onclick="myFunction(this)"><?php echo $row['Id']; ?></button>
<?php } ?>
</div>
function myFunction(el) {
var x = el.value;
console.log(x);
}
Better still would be to place the same class on all the buttons and use unobtrusive JS code to attach your event handler, like this:
<div class="text-middle">
<?php foreach($result as $row) { ?>
<button class="button" value="<?php echo $row['Id']; ?>"><?php echo $row['Id']; ?></button>
<?php } ?>
</div>
// native JS:
var buttons = document.getElementsByClassName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function() {
var x = this.value;
console.log(x);
});
}
// jQuery:
$('.button').click(function() {
var x = this.value;
console.log(x);
});
Do not use the same id for more then one element: id="myBtn"
Change your function:
onclick="myFunction()"
to:
onclick="myFunction(this)"
And so:
function myFunction(element) {
var x = element.value;
alert(x);
}
You need to get the elements by their class, not by the id that they all share (which is a bad thing to do).
<script>
function myFunction() {
var x = document.getElementsByClassName("button1");
for (var i = 0; i < x.length; ++i) {
alert(x[i].value);
}
}
</script>

Send parameter to the PHP-function from JavaScript

I've a such PHP-script:
<?php
$menuItemList = getSubPkgCategForDDList(echo "<script>showSubCatForMenuItem();</script>");
if(isset($menuItemList)){
foreach($menuItemList as $u){
?>
<p><span contenteditable="true"><?php echo $u->name ?></span><button type="button" class="btn btn-danger btn-xs" onclick="deleteCategory(<?php echo $u->pkg_cat_ddlist_id ?>)">Delete</button>
<button type="button" class="btn btn-success btn-xs" onclick="editCategory(<?php echo $u->pkg_cat_ddlist_id ?>,<?php echo "'".$u->name."'" ?>)">Save</button></p>
<?php
}
}
?>
Function getSubPkgCategForDDList must generate html-code,so it depends from parameter, which is send to this function.
I get this parameter from such js-function showSubCatForMenuItem():
function showSubCatForMenuItem(){
console.log($('#menuItem').val());
return $('#menuItem').val();
}
This function takes data from such dropdown list:
<select id="menuItem" onchange="showSubCatForMenuItem()">
<?php
$itemList = getPackCategoriesForAsideMenu();
if(isset($itemList)){
foreach($itemList as $u){
?>
<option value="<?php echo $u->pkg_cat_ddlist_id ?>"><?php echo $u->name ?></option>
<?php
}
}
?>
</select>
How to do that parameter transfer is correctly, when I load page and select item from dropdown list? Sorry for my English.
You should take advantage of $_SESSION in this case. Now print out the drop down :
<select id="menuItem">
<?php
$itemList = getPackCategoriesForAsideMenu();
if(isset($itemList)){
foreach($itemList as $u){
echo'<option value="'.$u->pkg_cat_ddlist_id.'">'.$u->name.'</option>';
}
}
?>
</select>
Write the JS script :
$("#menuItem").live('change',function(){
var val = $(this).val();
$.post('change.php',{data:val},function(){
// Do some
});
});
And create a php file named change.php :
<?php
session_start();
if(!empty($_POST['data'])){
$_SESSION['menu_sltd'] = (int) $_POST['data']; // It makes sure that the data sent is integer / number
}
?>
Now, change your main script to :
<?php
session_start();
$menu_sltd = (!empty($_SESSION['menu_sltd']) ? $_SESSION['menu_sltd'] : 'default id'); // Default id is the default menu id if it's blank
$menuItemList = getSubPkgCategForDDList($_SESSION['menu_sltd']);
if(isset($menuItemList)){
foreach($menuItemList as $u){
echo'
<p>
<span contenteditable="true">'.$u->name.'</span>
<button type="button" class="btn btn-danger btn-xs" onclick="deleteCategory('.$u->pkg_cat_ddlist_id.')">Delete</button>
<button type="button" class="btn btn-success btn-xs" onclick="editCategory('.$u->pkg_cat_ddlist_id.',\''.$u->name.'\')">Save</button>
</p>';
}
}
?>
GOOD LUCK,, glad to help you. Don't give up
In javascript function showSubCatForMenuItem() you can set the value of selected item in some hidden field on every change event the value selected by user will get updated, then while saving the use this value that is saved in the hidden field.

Categories