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==""){
Related
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;
}
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'>₱ " . $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.
Im using this is an ID
$id = $row['id'];
echo "<input type='text' id='$id' value='$row["s_code"]'>";
How can I get that ID in javascript function? I want it in here...
var scode = $('#').val();
While loop..
while ($row = mysqli_fetch_array($sqlSimplex , MYSQLI_ASSOC)) {
echo "<tr><td>";
$id = $row['id'];
echo "<input type='text' id='$id' value='".$row['s_code']."' readonly>";
echo "</td><td>";
echo $row['description'];
echo "</td>";
echo "<input type='hidden' id='comval' value='$newProductID'>";
echo "<td>";
echo "<input type='text' size='7' id='userqtyval'>";
echo "</td><td>";
echo "<input type='button' onclick='addthis()' value='Add!'>";
echo "</td></tr>";
}
Javascript
function addthis() {
var myID = '$id';
var scode = $("#"+myID).val();
alert(scode);
$.ajax({
type: 'POST',
url: 'insertsimplextoc_comp.php',
data: { simplexcode: scode },
});
}
Been stuck on this for over a week!
PHP:
while ($row = mysqli_fetch_array($sqlSimplex , MYSQLI_ASSOC)) {
echo "<tr><td>";
$id = $row['id'];
echo "<input type='text' id='$id' value='".$row['s_code']."' readonly>";
echo "</td><td>";
echo $row['description'];
echo "</td>";
echo "<input type='hidden' id='comval' value='$newProductID'>";
echo "<td>";
echo "<input type='text' size='7' id='userqtyval'>";
echo "</td><td>";
echo "<input type='button' class='submit-scode' data-field-id='$id' value='Add!'>";
echo "</td></tr>";
}
Javascript (using jQuery click event):
$('.submit-scode').click(function(){
var field_id = $(this).attr('data-field-id');
var scode = $("#"+field_id).val();
$.ajax({
type: 'POST',
url: 'insertsimplextoc_comp.php',
data: { simplexcode: scode },
});
});
Untested, but it should work.
Add the id of the current loop as a parameter to the addthis function:
echo "<input type='button' onclick='addthis(\"$id\")' value='Add!'>";
Then grab the id when the function is called like so:
function addthis(myID)
{
var scode = $("#"+myID).val();
//etc
}
have to keep track of that dynamic id's
It you have that id then you can do something like this
var id="assign php varable";
var scode =$('#'+id).val();
I'm guessing you want it to be used in the addthis() function ?
In this case, you'll hve to give a similar class to all your readonly inputs.
Then, while clicking on the add button, you'll have to check for its parent <tr>
I made some example here : http://jsfiddle.net/captain_torche/frzadnbb/
Or, you could alteratively put the ID as a parameter of the addthis() function, like so :
echo "<input type='button' onclick='addthis(".$id.")' value='Add!'>";
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\"> $quantity </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.
Im looking to pass one variable from my PHP code to my Javascript code to validate a figure. I'm creating a shopping cart scenario whereby i have a variable 'in_stock' which specifies the amount of stock available for a product. If I enter an amount that is greater than the 'in_stock' available i need an error to be thrown. This is currently what I have:
Java Script
<script language="javascript">
function numCheck()
{
var enteredChar = document.getElementById('add_value').value;
var stockavailable ="<?php echo $stock?>";
//To check if a non-numerical value is entered
if (isNaN(enteredChar))
{
alert("Not a Number!");
return false;
}
//To check if the input is empty
if (enteredChar=="")
{
alert("Empty!");
return false;
}
//To check if the amount entered is not greater than the amount in stock
if (enteredChar > stockavailable)
{
alert("Not enough in stock");
return false;
}
}
</script>
This is all occurring whilst my PHP has called the database and returned the value on the screen. As follows:
PHP
$product_id =(int)$_GET['product_id'];
$username = "potiro";
$password = "pcXZb(kL";
$hostname = "rerun";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("poti",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM products where product_id=$product_id");
echo '<form name="form1">';
echo '<table class="Grocery-table">';
while($row = mysql_fetch_array($result))
{
$stock =$row['in_stock'];
$product_id = $row['product_id'];
echo "<tr><td><b>Product ID</b></td>";
echo "<td>";
echo $product_id;
echo "</td></tr>";
echo "<tr><td><b>Product Name</b></td>";
echo "<td>";
echo $row['product_name'];
echo "</td></tr>";
echo "<tr><td><b>Unit Price</b></td>";
echo "<td>";
echo $stock;
echo "</td></tr>";
echo "<tr><td><b>Unit Quantity</b></td>";
echo "<td>";
echo $row['unit_quantity'];
echo "</td></tr>";
echo "<tr><td><b>In Stock</b></td>";
echo "<td>";
echo $row['in_stock'];
echo "</td></tr>";
echo '<tr><td><b>Add</b></td><td><Input type="text" id="add_value" name="cart"></input></td></tr>';
echo '<tr><td></td><td><input type="submit" value="Submit" onclick="return numCheck()"></td></tr>';
}
echo "</table>";
echo "</form>";
mysql_close($dbhandle);
?>
add your stock value to a hidden input value stock_value
echo '<tr><td><b>Add</b></td><td><Input type="text" id="add_value" name="cart" ></input><Input type="hidden" id="stock_value" name="stock_value" value="'.trim($stock).'"></input></td></tr>';
echo '<tr><td></td><td><input type="submit" value="Submit" onclick="return numCheck()"></td></tr>';
in javascript
<script language="javascript">
function numCheck()
{
var enteredChar = document.getElementById('add_value').value;
var stockavailable =document.getElementById('stock_value').value;