Using PHP Variable as ID and calling from Javascript - javascript

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!'>";

Related

Ajax request not working on button click using PHP and MySQL

I'm sending an ajax request through JavaScript on clicking a button. When button gets clicked a function is called from where ajax request is performed.
Here is the html code where function is called:
echo "
<form > ";
if ($status == 'regular') {
echo "<input type='hidden' value='".$id."' name='id'>";
echo "<input type='hidden' value='official' name='status'>";
echo "<td><button class='btn btn-info' onclick='UpdateStatus(".$id.",'official')'>UPDATE TO OFFICIAL</button><br><br>";
}
if ($status == 'official') {
echo "<input type='hidden' value='".$id."' name='id'>";
echo "<input type='hidden' value='regular' name='status'>";
echo "<td><button class='btn btn-success' onclick='UpdateStatus(".$id.",'regular')'>UPDATE TO REGULAR</button><br><br>";
}
echo "</form>";
UpdateStatus() is the function in which there is ajax request. From here I'm sending $id which is user ID and the status which is to be updated.
Here is the UpdateStatus() function:
<script>
function UpdateStatus(str,str1) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
//ready
};
xmlhttp.open("GET", "update_status.php?id=" + str + "&status=" + str1, true);
xmlhttp.send();
}
}
</script>
The str and str1 are the Id and status respectively. Here is the update_status.php:
<?php
$id = $_REQUEST["id"];
$status = $_REQUEST["status"];
$server_name = "localhost";
$user_name = "root";
$password = "";
$db = "diwan";
$conect = new mysqli($server_name, $user_name, $password, $db);
if($conect->connect_error)
{ die("Connection failed ".$conect->connect_error); }
$sql = "UPDATE user SET status = '$status' WHERE UserID = $id";
if(!$conect->query($sql))
{echo "error in adding record ".$conect->error;}
$result = $conect->query($sql);
?>
And when I click on button I get url of this format:
http://localhost/diwan_web/manageusers.php?id=2&status=official
But it's not updating the data in database. Please guide me where I'm wrong or if anything is missing. Any suggestion will be highly appreciated.
Looks like your syntax is wrong. Try
$sql = "UPDATE user SET status = ".$status." WHERE UserID = ".$id";
Code looks good. There is probably an error you are not seeing.
Add this to top:
ini_set('error_reporting', E_ALL);
ini_set('display_errors', true);
There were some issues:
You need to ensure the button does not reload the page (with type='button' as mentioned in another post).
We should always use double-quote for HTML attributes to prevent such mistakes (use onclick=\"UpdateStatus('param-here')\" instead of onclick='...')
If you use PHP's double-quote features you do not need to concatenate manually (If PHP finds $ in double-quotes like echo "Variable is: $x" it tries to find and concatenate the $x variable automatically).
If you apply above mentioned changes your code should look like:
echo "<form >";
if ($status == 'regular') {
echo "<input type='hidden' value='$id' name='id'>";
echo "<input type='hidden' value='official' name='status'>";
echo "<td><button type='button' class='btn btn-info' onclick=\"UpdateStatus('$id','official')\">UPDATE TO OFFICIAL</button><br><br>";
}
if ($status == 'official') {
echo "<input type='hidden' value='$id' name='id'>";
echo "<input type='hidden' value='regular' name='status'>";
echo "<td><button type='button' class='btn btn-success' onclick=\"UpdateStatus('$id','regular')\">UPDATE TO REGULAR</button><br><br>";
}
echo "</form>";

Alerting only 1st Product Code from table?

So, I have a table emitting data from database table.
//Display the simplex table
echo "<div id='simptable'>";
$sqlGet = "SELECT * FROM simplex_list";
//Grab data from database
$sqlSimplex = mysqli_query($connect , $sqlGet)or die("Error retrieving data!");
//Loop to display all records on webpage in a table
echo "<table>";
echo "<tr><th>Product Code</th><th>Description</th><th>Quantity</th></tr>";
while ($row = mysqli_fetch_array($sqlSimplex , MYSQLI_ASSOC)) {
echo "<tr><td>";
echo "<input type='text' id='sim' value='".$row['s_code']."' readonly>";
echo "</td><td>";
echo $row['description'];
echo "</td>";
echo "<input type='hidden' id='com' name='complexcode' value='$newProductID'>";
echo "<td>";
echo "<input type='text' size='7' id='userqty'>";
echo "</td><td>";
echo "<input type='button' onclick='addthis()' value='Add!'>";
echo "</td></tr>";
}
echo "</table>";
echo "</div>";
And I try to alert the 'Product Code' here when the user clicks 'Add' button....
function addthis() {
var scode = $('#sim').val();
alert(scode);
}
The problem is it only alerts the first Product Code in the table. That from row 1.
Example:
Product code Name More
123 Toy 'Add'
321 Food 'Add'
555 Pen 'Add'
So if I click on 'Add' for food or pen it will still alert 123..
Any ideas?
ID must be unique.
You can do something like following. Add parameter in onclick function. Which will be ID of row.
echo "<input type='button' onclick='addthis(".$row['s_code'].")' value='Add!'>";
^^^
Parameter added in above code. Now javascript function can be:
function addthis(scope) {
alert(scode);
}
As I stated in comments, the ID of your input must be unique. You're currently assigning 'sim' as the ID to every input in your loop over the data results.
One approach to fix this:
$i = 0;
echo "<input type='text' id='sim" . $i ."' value='".$row['s_code']."' readonly>";
And then add a unqiue id to your button using the same incrementor:
echo "<input type='button' id='btn" . $i . "' value='Add!'>";
$i++; //then increment
Notice that the button and the input have the same number at the end of their id. You can use this to parse the id of the button and use it to find the input.
Tie the click event with:
$(document).on('click', '[id^="btn"]', function() {
var id = $(this).attr('id').split('btn')[1];
var val = $('#sim' + id).val();
console.log(val);
//do other stuff
});
UPDATE: JSFiddle

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==""){

Updating value of textbox getting value from first text box only

I have cart page in which text box is present for updating quantity, I'm using jquery to listen to the click event & get the values of productid & the textbox. Productid I'm getting fine but value of textbox always is the value in first textbox.
Here is the code of cart file
echo "<tr>";
echo "<th><img src=".$row["image_location"]."></th>";
echo "<th>".$row["product_name"]."</th>";
echo "<th><input type='text' id='quantity' name='quantity' required='required' autocomplete='off' value=".$row["quantity"].">";
echo "&nbsp";
echo $row["type"]."</th>";
echo "<th>".$row["price"]."</th>";
echo "<th>"."₹ ".$subtotal."</th>";
echo "<th><div class='buttoncircle' id='".$row["productid"]."'>Update</div></th>";
echo "<th><a href='removefromcart.php?productid={$row["productid"]}' class='buttoncircle' style='margin-left:-65px'>Remove</a></th>";
echo "</tr>";
Here is the code for javascript.
<script>
$('.buttoncircle').live('click',function() {
var productid = $(this).attr('id');
var quantity = $('#quantity').val();
window.open('db_changequantity.php?quantity='+quantity+'&productid='+productid,'_self');
});
Can anyone help calling the value of particular textbox & not from the first one only?
Added dynamic id for the quantity filed - id='quantity_".$row["productid"]."' and mapped the same in javascript var quantity = $('#quantity_'+productid).val();.
In PHP
echo "<tr>";
echo "<th><img src=".$row["image_location"]."></th>";
echo "<th>".$row["product_name"]."</th>";
echo "<th><input type='text' id='quantity_".$row["productid"]."' name='quantity' required='required' autocomplete='off' value=".$row["quantity"].">";
echo "&nbsp";
echo $row["type"]."</th>";
echo "<th>".$row["price"]."</th>";
echo "<th>"."₹ ".$subtotal."</th>";
echo "<th><div class='buttoncircle' id='".$row["productid"]."'>Update</div></th>";
echo "<th><a href='removefromcart.php?productid={$row["productid"]}' class='buttoncircle' style='margin-left:-65px'>Remove</a></th>";
echo "</tr>";
Javascript:
$('.buttoncircle').live('click',function() {
var productid = $(this).attr('id');
var quantity = $('#quantity_'+productid).val();
window.open('db_changequantity.php?quantity='+quantity+'&productid='+productid,'_self');
});

ajax POST on form sumbit event not working properly

i have problem with ajax post with form submit event. i have table generated by opentable.php
here code for opentable.php
<?php
session_start();
require("dbc.php");
$memberid = $_SESSION['memberid'];
$sql = "SELECT * FROM `open` WHERE `memberid`='$memberid'";
$mydata = mysql_query($sql);
echo "<table><tr><th>Time</th><th>Type</th><th>Size</th><th>Price</th><th>Profit</th><th></th><th></th></tr>";
while($record = mysql_fetch_array($mydata)){
echo "<form action = assets/close.php id=closeform>";
echo "<tr>";
echo "<td>" . $record['opendate'] . "</td>";
echo "<td>" . $record['type'] . "</td>";
echo "<td>" . $record['size'] . "</td>";
echo "<td>" . $record['openprice'] . "</td>";
echo "<td>" . $record['profit'] . "</td>";
echo "<td>"."<input type=hidden name=openid value=".$record['openid']." </td>";
echo "<td>" . "<input type=submit name=close value=close". " </td>";
//echo "</tr>";
echo "</form>";
}
echo "</table>";
?>
and ajax javasript for submit event trade.js
$(document).ready(function() {
$('#closeform').submit(function( event ) {
event.preventDefault();
var $form = $( this ),
price = $('#price').val(),
id = $form.find( "input[name='openid']" ).val(),
url = $form.attr( "action" );
var posting = $.post( url, { openid: id, closeprice: price } );
var r=confirm("Are you sure?");
if(r =true){
posting.done(function( data ) {
alert(data);
});
}
else
{
alert("Transaction canceled")
}
});
}
i tested it, and it runs like normal php form. and error there is no $_POST data passed.
please give me recomendation for this kind of event thanks.
closeform is a dynamically added form, try using .on():
$(document).on('submit', '#closeform', function ( event ) {

Categories