JavaScript does not work inside PHP loop - javascript

It seems like when i echo out the result in php, it will loop through the database and display it in the "echo" below but if I try to display it using javascript, it does not even loop. what's the problem in the javascript?
<?php
while($row = $result->fetch()){
$id = $row['id'];
echo $id; //loops through and displays the all the id's in order in the database
?>
//this only displays the first id and doesn't loop even though it is in the php while loop
<script>
document.getElementById("test").innerHTML = "<?= $id ?>";
</script>
<span id="test"></span>
<?php
}
?>

please try with this
<?php
while($row = $result->fetch()){
$id = $row['id'];
echo $id; //loops through and displays the all the id's in order in the database
?>
//this only displays the first id and doesn't loop even though it is in the php while loop
<!-- change in id name -->
<span id="test_<?=$id?>"></span>
<script type="text/javascript">
//change here
document.getElementById("test_<?=$id?>").innerHTML = "<?= $id ?>";
</script>
<?php
}
?>

Related

Retrieve The PHP variable Value of a HTMl Element Using Jquery inside a Loop

I have a strange problem. I am getting the table values using PHP MySQL using a while loop and stored them in a array. Then I am displaying it one after another in a single page.
$sql = "select * from newsfeed order by id DESC";
$result = $db->query($sql);
$posts_array = array(); // Storing the result to an Custom Array
$index = 0;
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
$posts_array[$index] = $row;
$index++;
}
}
I have successfully set the $post_id of the posts on to the HTML elements using the following code.
<?php
$array_size = sizeof($posts_array);
for($i = 0; $i < $array_size; $i++){
?>
<div class='wrapper' id='wrapper'>
<div class='user'>
<!-- Some Code -->
<?php
$post_id = $posts_array[$i][id];
?>
<input type='image' name='like' id='like' width='40' height='40' src='like_btn.png' value='<?php echo ($post_id);'?> />
<?php } ?>
Now I want to take that value using Jquery and do some Database Work. I have accessed the value using the following code:
<script type="text/javascript">
function justsomething() {
alert($(this).val());
}
</script>
The problem is I am only getting the last post's id as alert() for every post rather than getting different id's .
Please help me. I am confused whether the PHP script is loading every time I click and call the justsomething() function.
Note: I can display the $post_id of every post alone without any problem.
Beacuse the id should be unique to one html element try changing your code to this :
<?php $array_size = sizeof($posts_array); for($i = 0; $i < $array_size; $i++){ ?>
<input type='image' name='like_<?php echo $i ?>' id='like_<?php echo $i ?>' width='40' height='40' src='like_btn.png' value='<?php echo $post_id;?>' onclick='justsomething(this);' />
<?php } ?>
<script>
function justsomething(el) {
var img = el;
alert(img.value);
}
</script>
here is an example
function justsomething(el) {
var img = el;
alert(img.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='image' name='like_1' id='like_1' width='40' height='40' src='like_btn.png' value='15454' onclick='justsomething(this);' />
It works for loop, I hope You can make use of it
$("input[id=like]").each(function(i){
alert($(this).val());
});
It will alert values from every <input id="like"...
Try this code:
onclick='justsomething(this)'
function justsomething(obj) {
alert($(obj).val());
}

How to add JavaScript response to more than one forearch result

I currently have a PHP script that works well, but when it comes to adding JavaScript I'm having a small issue.
What I'm trying to achieve is display the results in a php foreach loop which works well, but I have a onclick JavaScript function that is suppose to display results in the same row as the results of the foreach loop, but instead it changes the current value of only one results.
So I currently have four car types with a price. When one is selected I would like the name and price to display on top of the [echo "Select:" . $name] line.
My current code is this:
<?php
$cars = array(
array("Volvo",40.000),
array("BMW",45.000),
array("Saab",50.000),
array("Land Rover",60.000)
);
foreach($cars as $key){
$name = $key[0];
$price = $key[1];
echo "<span id='$name'></span> <span id='$price'></span><br />";
echo "Select: " . $name;
?>
<script type="text/javascript">
function grabData(d){
document.getElementById("<?php echo $price; ?>").innerHTML = d.getAttribute("data-price");
document.getElementById("<?php echo $name; ?>").innerHTML = d.getAttribute("data-title");
}
</script>
<input onclick="grabData(this);" type="radio" name="rate" data-price="<?php echo $key[1]; ?>" data-title="<?php echo $key[0]; ?>"><br />
<?php
}
?>
So if all options are selected the end results should look like this:
Volvo 40
Volvo:
BMW 45
BMW:
Saab 50
Saab:
Land Rover 60
Land Rover:
Any help or direction is highly appreciated. Thanks!
The loop is simply defining the same function over and over. When it gets called, it will call the last definition, not the one for that element in the loop.
You should just define the function once, and add additional parameters. Then you can call it with different parameters for each element.
<script type="text/javascript">
function grabData(d, priceid, nameid){
document.getElementById(priceid).innerHTML = d.getAttribute("data-price");
document.getElementById(nameid).innerHTML = d.getAttribute("data-title");
}
</script>
<?php
$cars = array(
array("Volvo",40.000),
array("BMW",45.000),
array("Saab",50.000),
array("Land Rover",60.000)
);
foreach($cars as $key){
$name = $key[0];
$price = $key[1];
echo "<span id='$name'></span> <span id='$price'></span><br />";
echo "Select: " . $name;
?>
<input onclick="grabData(this, '<?php echo $price; ?>', '<?php echo $name; ?>');" type="radio" name="rate" data-price="<?php echo $key[1]; ?>" data-title="<?php echo $key[0]; ?>"><br />
<?php
}
?>
set the script part as a string in a variable and echo it using php, php sees every <?php ?> as a different coding block.

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?

Only getting the last row in materialize select

How do I change the value of a SELECT tag in MATERIALIZE CSS. I'm trying show the selected item that was stored from the database. I tried adding .material_select() at the end of the select but it only retrieves the LAST one in the row. How do I show every try ? Here's what I've tried so far.
$(function() {
<?php
$q = $db->query("SELECT buildingID, buildingName,building_projectID, floorNumber FROM tblBuilding");
while($r = $q->fetch(PDO::FETCH_ASSOC)){
$buildingID = $r['buildingID'];
$buildingName = $r['buildingName'];
$building_projectID = $r['building_projectID'];
$floorNumber = $r['floorNumber'];
$t = $db->query("select projectName from tblProject where projectID = $building_projectID ");
while($u = $t->fetch(PDO::FETCH_ASSOC)){
$projectName = $u['projectName'];
?>
$("#editModal<?php echo $buildingID ?>").click(function(){
alert('<?php echo $projectName ?>');
$("#editBuildingName").val("<?php echo $r['buildingName'] ?>");
$("#editBuildingProject").val("<?php echo $projectName");
$("#editBuildingFloors").val("<?php echo $floorNumber ?>");
});
<?php }}?>
});
instead of:
$("#editBuildingProject").val("<?php echo $projectName");
use this:
$("#editBuildingProject").val("<?php echo $building_projectID ?>").material_select('update');

Ajax: Data passing through button value not working

Problem: All the other portions of the program works. When I add data:$("#friendadd").val() it won't update the table. I believe the problem might be with the value form? I've seen others use it to get the value of textboxes but shouldn't it still work when using a submit button?
Purpose: each user on the website has an add-as-friend button next to it. When you click on that button, I want to put the userid of that user into a database "friends".
Javascript
<script>
$(document).ready(function(){
$("#friendadd").submit(function(){//Used to be .each
$.ajax({
type:"POST",
url:"getuser.php",
data:$("#friendadd").val()
});//Add data: and success:function
//$.post('getuser.php');//JSON AJAX, {UserId:"13", FriendId:"16"}
})
});
</script>
PHP and HTML; $ctk_values are each of the users
<form id="friendadd">
<?php
for($i=0; $i<$ctk->rowCount(); $i++){
echo "<img src='".$ctk_values[$i][6]."' alt='Blank' style='width:64px;height:64px'>";//PP, Later add clickable profile
echo "<th rowspan='3'>Attributes</th>";
echo "<tr> ".$ctk_values[$i][0]."</tr>";//UN
echo "<tr> ".$ctk_values[$i][1]."</tr>";//UL
echo "<tr> ".$ctk_values[$i][5]."</tr>";//UA
?>
<input type="submit" value="<?php echo $ctk_values[$i][4];?>"><br>
<?php
}//Ends for loop
?>
</form>
<?php
}
}
?>
getuser.php
<?php
if(!isset($_SESSION)){
session_start();
}
require "conn.php";
$gtu = $dbh->prepare("INSERT INTO friends (AskerId, AcceptorId, mutual, type) VALUES(:AskerId, :AcceptorId, :mutual, :type)");
$gtu->execute(array(
'AskerId'=>$_SESSION['UserId'],
'AcceptorId'=>$_POST['friendadd'],
'mutual'=>false,
'type'=>'friend'
));
?>

Categories

Resources