Show specific text from a php loop of database results using jquery - javascript

I have selected data from my database and I have looped through the results to display them on my page. I have 3 results which are shown. Each result has a button with an id called decrease. When I click this button, an alert with the name of the item containing the alert button should be displayed. I am using jQuery to achieve this.
My problem is that whenever I click the button, the name of only the first item in the results array is displayed. The buttons in the other two results don't seem to work. What am I doing wrong?
The code that loops through the result and displays the items in the database table:
if(mysqli_num_rows($run) >= 1){
while($row = mysqli_fetch_assoc($run)) {
$name = $row['name'];
$quantity = $row['quantity'];
$price = $row['price'];
$image = $row['image'];
$category = $row['category'];
$total = $price * $quantity;
echo "<div class=\"post-container\">\n";
echo "<div class=\"post-thumb\">\n";
echo "<img src='$image'>\n";
echo "</div>\n";
echo "<div class=\"post-title\">\n";
echo "<h4 style=\"font-weight:bold;\">\n";
echo "$name\n";
echo "<span id=\"deletion\">Delete</span>\n";
echo "</h4>\n";
echo "</div>\n";
echo "<div class=\"post-content\">\n";
echo "<ul style=\"list-style-type:none;\">\n";
echo "<li>Cost Per Item: <span id=\"cost\">$price</span>/=</li>\n";
echo "<li>\n";
echo "Quantity: \n";
echo "<button type=\"submit\" id=\"decrease\" class=\"glyphicon glyphicon-minus\" title=\"Decrease Quantity\"></button>\n";
echo "\n";
echo "<span id=\"cost\" class=\"quantity\">&nbsp$quantity&nbsp</span>\n";
echo "\n";
echo "<button type=\"submit\" id=\"increase\" class=\"glyphicon glyphicon-plus\" title=\"Increase Quantity\"></button>\n";
echo "</li>\n";
echo "<li>Total Cost: <span id=\"cost\">$total</span>/=</li>\n";
echo "</ul>\n";
echo "</div>\n";
echo "</div>";
}
}
And here's the jquery:
$("#decrease").click(function(){
var name = $(this).parent("li").parent("ul").parent("div.post-content").siblings("div.post-title").find("a").text();
alert(name);
});

Your HTML markup is invalid as there can be only one element with given id - id must be unique. You can use classes instead, for example class decrease will have selector .decrease, that will pertain to all your buttons.

Related

PHP: javascript alert, with value from sql query, into IF condition

With the following code, a popup table should appear with sql query data, only when retrieved records are greater than 1.
$sql = "SELECT * FROM pt_locations WHERE country = ('$countryCode') AND location = ('$cityCode')";
$result = $conn->query($sql);
$rowcount=mysqli_num_rows($result);
$message = "Records found: " . $rowcount . "<br /><br />";
if ($rowcount > 1) {
echo '<script language="javascript">';
echo 'alert' .$message;
foreach($result as $val){
$id_country = $val["country"] ;
$id_code = $val["code"] ;
$id_location = $val["location"] ;
$id_latitude = $val["latitude"] ;
$id_longitude = $val["longitude"] ;
echo "<table border='1' cellpadding='5'>";
echo "<tr>";
echo "<td><i><strong>ID Code</strong></i></td><td>";
echo $id_code."</td>";
echo "<td><i><strong>Country</strong></i></td><td>";
echo $id_country."</td>";
echo "<td><i><strong>Code</strong></i></td><td>";
echo $code."</td>";
echo "<td><i><strong>Location</strong></i></td><td>";
echo $id_location."</td>";
echo "<td><i><strong>Latitude</strong></i></td><td>";
echo $id_latitude."</td>";
echo "<td><i><strong>Longitude</strong></i></td><td>";
echo $id_longitude."</td>";
echo "</tr>";
echo "</table><br /><br />";
}
echo '</script>';
}
Recording counts are done correctly, but I can not make the popup appear in any way.
try this. Hope this help you.
$sql = "SELECT * FROM pt_locations WHERE country = ('country') AND
location = ('location')";
$result = $conn->query($sql);
$rowcount=mysqli_num_rows($result);
$message = "Records found: " . $rowcount;
if ($rowcount > 1) {
echo '<script language="javascript">';
echo 'alert("'.$message.'")';
echo '</script>';
while($val=mysqli_fetch_assoc($result)){
$id_country = $val["country"] ;
$id_code = $val["code"] ;
$id_location = $val["location"] ;
$id_latitude = $val["latitude"] ;
$id_longitude = $val["longitude"] ;
echo "<table border='1' cellpadding='5'>";
echo "<tr>";
echo "<td><i><strong>ID Code</strong></i></td><td>";
echo $id_code."</td>";
echo "<td><i><strong>Country</strong></i></td><td>";
echo $id_country."</td>";
echo "<td><i><strong>Code</strong></i></td><td>";
echo $code."</td>";
echo "<td><i><strong>Location</strong></i></td><td>";
echo $id_location."</td>";
echo "<td><i><strong>Latitude</strong></i></td><td>";
echo $id_latitude."</td>";
echo "<td><i><strong>Longitude</strong></i></td><td>";
echo $id_longitude."</td>";
echo "</tr>";
echo "</table><br /><br />";
}
}
There are some errors, because for logic you must put the alert at the end of the table complete, just for logic and after you put alert something without brakets and you open a script before the foreach loop and after the foreach loop you close the script, this is absolutley wrong, another error is in the $message, you are using br inside an alert javascript that isn't recognize as html but just like characters at the least you can use unicode \n\t not br, i used also a setTimeout,but works also without setTimeout.
Sometimes can result essential use javascript injection inside the php for example to autofill of some forms and input select or to call a change event from external compilation of other application that pass variables in get and need to autofill a form, but i think in this case is not necessary do a javascript injection you can print the total Records just in the page, btw...
The code under works
Bye
$message = "Records found: " . $rowcount." \\n\t\\n\t";
if ($rowcount > 1) {
foreach($result as $val){
//var_dump($val);
$id_country = $val["country"] ;
$id_code = $val["code"] ;
$id_location = $val["location"] ;
$id_latitude = $val["latitude"] ;
$id_longitude = $val["longitude"] ;
echo "<table border='1' cellpadding='5'>";
echo "<tr>";
echo "<td><i><strong>ID Code</strong></i></td><td>";
echo $id_code."</td>";
echo "<td><i><strong>Country</strong></i></td><td>";
echo $id_country."</td>";
echo "<td><i><strong>Code</strong></i></td><td>";
echo $code."</td>";
echo "<td><i><strong>Location</strong></i></td><td>";
echo $id_location."</td>";
echo "<td><i><strong>Latitude</strong></i></td><td>";
echo $id_latitude."</td>";
echo "<td><i><strong>Longitude</strong></i></td><td>";
echo $id_longitude."</td>";
echo "</tr>";
echo "</table><br /><br />";
}
$jvsVar = "<script type='text/javascript'>;setTimeout(function(){alert('$message');},100)</script>";
echo $jvsVar;
}

Undefined index after json_decode

I have a problem when I'm trying to get the contents of a JavaScript Array and pass its value to a PHP Array Variable.
What I'm doing is that, when a user clicks a button, the value of the item clicked will be added to the javascript array and every time the javascript array updates, the PHP variable will also update and so the contents of the div displaying the contents of the PHP array. I'm not using forms for this matter but buttons
However, when I try to use the json_decode function to get the values of a JavaScript array, it's giving me a Message: undefined index: data error
I'm a beginner in JavaScript, jQuery and AJAX so please bear with me
This is my code:
<script>
// ARRAY VARIABLE WHERE ITEM VALUES WILL BE STORED
var food_item = new Array();
// FUNCTION TO BE TRIGGERED WHEN USER CLICKED THE BUTTON, GET THE ITEM'S VALUE AND ADD IT TO ARRAY
function addToTray(data){
food_item.push(document.getElementById(data).value);
dataString = food_item; // array?
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "main",
data: {data: jsonString},
cache: false,
success: function(){
alert("OK");
}
});
}
</script>
<body>
...
// LINE OF CODE RESPONSIBLE FOR FETCHING JAVASCRIPT ARRAY VALUES
$this->session->userdata['food_tray'] = json_decode($_POST['data']);
// DIV TO BE UPDATED
<div class="col-md-3 food-tray" id="food-items" style="margin-top: 7%">
<!--FOOD TRAY-->
<div class="panel-heading">
<h3 class="ft-header">Food Tray</h3>
</div>
<div class="panel-body">
<?php
$count_fi = count($this->session->userdata('food_tray'));
echo "<p>Your Items (" . $count_fi . ")</p>";
if($count_fi == 0){
echo "<p class='no-avail-list'>NO ITEMS ADDED IN FOOD TRAY</p>";
}else{
echo "<table class='table borderless'>";
for($i = 0; $i < $count_fi; $i++){
echo "<tr>";
echo "<td>" . $this->session->userdata['food_tray'][$i] . "</td>";
echo "<td>P 200.00</td>";
echo "<td><form method='post'><input type='number' name='qty' min='1' max='100' value='1'/></form></td>";
echo "</tr>";
}
echo "</table>";
echo "<a href='' class='btn btn-success' data-toggle='modal' data-target='#myModal'>
Add Friend</a>";
echo "<a href='".base_url()."index.php/CheckOut' class='btn btn-warning'>Proceed to Checkout</a>";
}
?>
</div>
</div>
...
<?php
foreach($query->result() as $row){
echo "<div class='col-lg-7'>";
echo "<div class='thumbnail'>";
$file_name = strtolower(preg_replace('/[^A-Za-z0-9\-.]/', '', $row->name));
/*if(file_exists(FCPATH . '/assets/images/main/food/' . $file_name . '.jpg')){
echo "<img src='".base_url()."/assets/images/main/food/".$file_name.".jpg' alt='' width='320px' height='100px'>";
}else{
echo "<img src='http://placehold.it/320x150' alt=''>";
}*/
echo "<img src='http://placehold.it/320x150' alt=''>";
echo "<div class='caption'>";
echo "<h5 class='pull-right'>&#x20B1 " . $row->price . "</h5>";
echo "<h5><a href='#'>" . $row->name . "</a></h5>";
echo "<h5>Calorie Count : " . ($row->calorie_count == NULL ? "Not Available" : $row->calorie_count) . "</h5>";
// BUTTON FOR `addToTray()` FUNCTION
echo "<button class='btn btn-primary' id='".$row->id."' value='".$row->name."' style='width:100%' onclick='addToTray(".$row->id.")'>Add to Tray</button>";
// var_dump($row->name);
echo "</div>";
echo "</div>";
echo "</div>";
}
?>
</body>
Anyone who knows how to solve this problem? Any help would be appreciated.
create your session as
$array = array ('food_tray' => json_decode($javascriptarray));
$this->session->set_userdata($array);
check if your javascript libraries are loaded in sources tab.

How to render UI using php and angular for display and in place update

<?php
$ach_json = json_decode ( $ach, true );
for($i = 0; $i < count ( $ach_json ); $i ++) {
echo "<ng:switch on='edit'>";
echo "<div ng:switch-when='true'>";
$title = $ach_json [$i] ['title'];
echo "<h3>title $title</h3><br>";
echo "<input type='image' src='http:'..' name='edit' value='$i' ng-click='editClick()'>";
echo "</div>";
echo "<div ng:switch-when='false'>";
echo "Title: <input type='text' ng-model='title' value=$title> <br>";
echo "<button ng-click='updateRequest()'>update</button>";
echo "</ng:switch>";
}
?>
</form>
here I display title, when someone clicks on edit button, I change it to textbox and give the user to update . once someone clicks on update , now I will make a rest call and need to show updated title.

Stuck in endless loop while creating buttons

I'm trying to create a website, where I can insert products with a button.
So for now I got one button which creates one div as a product box. When the button is clicked it becomes invisible, under this I can see the div now; and under the div, there's the next button which should be able to create one more divs (always the same way).
The problem is that I can't find any solution to do that. I always land in an endless loop.
If you're wondering about the mailer, the idea for the first step is, to send a mail as newsletter for every created product.
Here's my code:
<?php
echo "<form action='index.php' method='GET'>";
echo "<input type='submit' name='insert' id='insert' value='INSERT'>";
echo "</form>";
if ($_GET["insert"]) {
echo " <script language='JavaScript'> ";
echo "";
echo " ";
echo " document.getElementById('insert').style.visibility='hidden' ";
echo "";
echo "</script>";
echo " <div class='article'>";
echo "<h2>product</h2>";
echo "<p>";
echo "EXAMPLE";
echo "</p>";
echo "</div> ";
echo "<form action='index.php' method='GET'>";
echo "<input type='submit' name='ins ert' id='insert' value='INSERT'>";
echo "</form>";
//send mail
$message = "hello TEST!";
for ($i = 0; $i < $z; $i++) {
mail('' . $res[$i] . '', 'Newsletter', $message);
}
}
?>
You are hiding an "id=insert" item, and then creating a second "id=insert" item. So you get 2 identical id, which is not good.
You should "remove" the "id=insert" rather than "hide" it. jquery may help you on that.
(And so you may not need to remove the "id=insert" item, but rather "add" a new div "after" your last product).

Ajax function can't get int valor onclick javascript

I have a function on ajax that retrieves the int on the input button onclick, this is the javascript ajax code:
function checkBoxes(str){
var xmlhttp=browsers();
if(str=""){
document.getElementById("txt").innerHTML="";
return;
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("txt").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.php?h"+str,true);
xmlhttp.send();
}
I use php to print the results on the screen, with an onclick button:
if(isset($_GET['k'])){
$con=oci_connect('jvillegas','1234','XE');
if(!$con){
die("No s'ha pogut connectar: ".mysqli_error($con));
}
$k=intval($_GET['k']);
$sql3=oci_parse($con, "SELECT TARIFAS.ID, TARIFAS.ID_TIPO_ACTIVIDAD, TARIFAS.TIPO, TIPO_ACTIVIDAD.TEMPS_KM, TARIFAS.PRECIO
FROM TARIFAS, TIPO_ACTIVIDAD
WHERE TARIFAS.ID_TIPO_ACTIVIDAD=TIPO_ACTIVIDAD.ID
AND TARIFAS.ID_TIPO_ACTIVIDAD=$k");
oci_execute($sql3);
echo "<div class='divPrecios'>";
echo "<table border='1'>";
echo "<tr class='tabPreciosTitles'>";
echo "<td>Tipus Tarifa</td>
<td>Temps/Km</td>
<td>Preu</td>
<td><input type='button' class='carrito' value=''></td>";
echo "</tr>";
while (($row=oci_fetch_array($sql3,OCI_BOTH))!=false){
echo "<tr>";
echo "<td>".$row['TIPO']."</td>";
echo "<td>".$row['TEMPS_KM']."</td>";
echo "<td>".$row['PRECIO']."</td>";
echo "<td>".$row['ID']."</td>";
echo "<td><input type='button' name='checkbox[]' onclick=checkBoxes('".$row['ID']."') value='".$row['ID']."'/></td>";
echo "</tr>";
}
echo "</table>";
echo "</div>";
}
I thougt there is the error:
input type='button' name='checkbox[]' onclick=checkBoxes('".$row['ID']."') value='".$row['ID']."';
I do tests and if I pass a single int valor, it returns 0... why??
So the table with the result if all it's correct:
if(isset($_GET['h'])){
$con=oci_connect('jvillegas','1234','XE');
if(!$con){
die("No s'ha pogut connectar: ".mysqli_error($con));
}
echo "<table border=1>";
echo "<tr class='tabPreciosTitles'>";
echo "<td>Nom Activitat</td>
<td>Nom Tipus Activitat</td>
<td>Tipus Tarifa</td>
<td>Temps/km</td>
<td>Preu</td>";
echo "</tr>";
$h=intval($_GET['h']);
$sql4=oci_parse($con, "SELECT ACTIVIDAD.NOM AS NOM_ACTIVIDAD, TIPO_ACTIVIDAD.NOM AS NOM_TACTIVIDAD, TARIFAS.TIPO, TIPO_ACTIVIDAD.TEMPS_KM, TARIFAS.PRECIO
FROM TARIFAS, ACTIVIDAD, TIPO_ACTIVIDAD
WHERE TARIFAS.ID=$h
AND TARIFAS.ID_TIPO_ACTIVIDAD = TIPO_ACTIVIDAD.ID
AND TIPO_ACTIVIDAD.ID_ACTIVIDAD = ACTIVIDAD.ID");
oci_execute($sql4);
$array=array(
0=>array(),
1=>array(),
2=>array(),
3=>array(),
4=>array()
);
while (($row=oci_fetch_array($sql4,OCI_BOTH))!=false){
array_push($array[0],$row['NOM_ACTIVIDAD']);
array_push($array[1],$row['NOM_TACTIVIDAD']);
array_push($array[2],$row['TIPO']);
array_push($array[3],$row['TEMPS_KM']);
array_push($array[4],$row['PRECIO']);
}
for ($x=0;$x<count($array[4]);$x++){
echo "<tr>";
echo " <td>".$array[0][$x]."</td>";
echo " <td>".$array[1][$x]."</td>";
echo " <td>".$array[2][$x]."</td>";
echo " <td>".$array[3][$x]."</td>";
echo " <td>".$array[4][$x]."</td>";
echo " <td><input type='submit' class='carritoElim' value=''></td>";
echo "</tr>";
}
echo "</table>";
}
And to show these results I use divs:
<div id='txtHint'></div>
<div id='txtIhnt'></div>
<div id='txt'></div>
If I put an int on the query of the last table, change the $h for a 13, it works, or if I change the ajax function on > xmlhttp.open("GET","ajax.php?h=13",true); it works too.
I think your problem is coming from this line here
if(str=""){
Rather that doing a comparison you are assigned an empty string to the str variable. So from that point on in the function the value of str will be "". You want to change it to
if(str==""){

Categories