Why can't I access textarea id's after parsing array - php

I'm loading multiple clients on a page, each record with its own <textarea>. I set each <textarea> with the client's clientid.
if(isset($_POST['loaddata'])){
try{
$stmt = $db->prepare('SELECT clientid, fname, lname
FROM clients
WHERE memberid = :memberid
AND groupid = :groupid
ORDER BY lname');
$stmt->bindValue(':memberid', $_SESSION["memberid"], PDO::PARAM_INT);
$stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row ) { $i++;
echo '<tr style="'.getbgc($i).'">
<td style="display:none">'.$row[0].'</td>
<td style="width:auto;">'.$row[1].'</td>
<td style="width:auto;">'.$row[2].'</td>
<td><textarea id='.$row[0].' class="form-control" rows="1"></textarea></td>
</tr>';
}
} ...
After the data loads, I test the <textarea> id's:
$.ajax({
url : 'wsparticipation.php',
type : 'POST',
async : false,
data : {
'loaddata' : 1,
'groupid' : temp
},
success:function(re){
$('#showdata').html(re);
$('#13').html("I am 13");
$('#15').html("I am 15");
$('#10').html("I am 10");
} ...
and the textareas show the html.
When I get ready to save the the entered data, I set the clientid's into an array.
if(isset($_POST['getarray'])){
$stmt = $db->prepare('SELECT clientid
FROM clients
WHERE memberid = :memberid
AND groupid = :groupid
ORDER BY lname');
$stmt->bindValue(':memberid', $_SESSION["memberid"], PDO::PARAM_INT);
$stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
$ret = array();
foreach($result as $row ) {
$ret[] = $row['clientid'];
}
echo json_encode($ret);
exit();
}
$.ajax({
url : 'wsparticipation.php',
type : 'POST',
datatype : 'JSON',
data : {
'getarray' : 1,
'groupid' : temp
},
success:function(re){
data = $.parseJSON(re);
$.each(data, function(i, clientid) {
alert(clientid);
$('#clientid').html("hahaha");
});
$('#2').html("Made it here with this");
}
});
The alert() indeed shows me each of the clientid's, but the next statement $('#clientid').html("hahaha"); does nothing. The last statement $('#2').html("Made it here with this"); puts that text in the appropriate textarea.
So, since the alerts are showing me the clientid's, why am I not able to access the textarea using the clientid from $.each(data, function(i, clientid)?

$('#clientid') selects an element with the ID of "clientid".
I think you want to dynamically build the selector by concatenating the "#" symbol with your variable's value:
$('#'+clientid).html("hahaha");
Example below:
var clientid = 2;
$('#' + clientid).html('test');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="2"></textarea>

Change your selector from:
$('#clientid').html("hahaha");
to
$('#'+clientid).html("hahaha");
Also a side note: Don't use integers as ids, it's very bad idea and it's not really descriptive of what it is, a better choice might be: clientInfo1, clientInfo2.. etc or clientTextarea1, clientTextarea2 .. etc

Related

Fetch hidden product_id from database to jquery autocomplete plugin list

I am using jquery autocomplete plugin for selecting data from database using PHP, MySql and Ajax.
The plugin operates good except fetching the product_id. When the plugin fetches the autocomplete list I want also to attach a hidden product_id to the products to differentiate the products for example in case of multiple products with the same product_name.
Below is the code that functions only with product_name.
function select_name(){
$("[id^='product_name']").focus(function() {
var id = $(this).attr('id');
id = id.replace("product_name",'');
$("[id^='product_name']").autocomplete({
source: 'store_supply/fetch_autocomplete_name.php',
select: function (event, ui) {
var pro_nm = ui.item.value;
$.ajax({
url:"store_supply_manage/fetch_product_code.php",
method:"POST",
data:{pro_nm:pro_nm},
//here I want to post a product_id when selecting the product_name
dataType:"json",
success:function(data){
$('#mu_emri_'+id).val(data.mu_name);
$('#product_code_'+id).val(data.barCode);
$('#vat_vlera_'+id).val(data.vat_value_4);
$('#product_id'+id).val(data.product_id);
calculateTotal();
}
});
}
});
});
}
//fetch_autocomplete.php
if (isset($_GET['term'])) {
$term = $_GET['term'];
$query = $db->prepare("SELECT product_name FROM products
WHERE product_name LIKE '%$term%' LIMIT 10");
$query->execute();
$nr = $query->rowCount();
if ($nr > 0) {
while ($row = $query->fetch()) {
$result[] = $row['product_name'];
}
}
else {
$result = array();
}
//return json result
echo json_encode($result);
}
In your code you are preparing your SQL statement but interpolating the $term variable instead of parameterizing your query. In the example below I have parameterized your query.
As shown in the documentation, the data can be either:
An array of strings: [ "Choice1", "Choice2" ]
An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]
So you can just change your fetch_autocomplete.php to something like:
if (isset($_GET['term'])) {
$term = '%' . $_GET['term'] . '%';
// parameterized query in nowdoc*
$sql = <<<'SQL'
SELECT id AS `value`, product_name AS `label`
FROM products
WHERE product_name LIKE :term
LIMIT 10
SQL;
// prepare the query
$query = $db->prepare($sql);
// bind variables and execute
$query->execute(['term'] => $term);
// As fetchAll() returns an empty array if there are no matching
// rows we do not need to check rows returned
$result = $query->fetchAll(PDO::FETCH_OBJ);
// return json result
echo json_encode($result);
}
* nowdoc
Change id to whatever the name of your product id column is. Now, inside your select handler, ui.item.value will be the product id instead of its name.

MySQL update query is executed but no change in data for some rows

Unfortunately there is no error message. This is my update query, and it works granted that it always reaches the echo statement after execute(). The strange thing is it does not reflect the update on some rows (some rows do get updated), even if correct data is being sent on the network payload. Another strange thing is that this totally works in localhost, but not in live server.
include_once("../connections/db.inc.php");
if(isset($_POST['id'])) {
try {
$value = $_POST['value'];
$column = $_POST['column'];
$id = $_POST['id'];
$sql = "UPDATE `users` SET $column = :value WHERE md5(userId) = :id OR userId =:id LIMIT 1";
$stmt = $db->prepare($sql);
$stmt->bindParam(":id", $id, PDO::PARAM_INT);
$stmt->bindParam(":value", $value);
if (!$stmt->execute()) {
print_r($stmt->errorInfo());
}
echo "y";
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
Currently the id is being retrieved using a simple loop
while ($row = $stmt->fetch()) {
$id = md5($row['userId']);
...
and the fields are inline editable
<td>
<div contenteditable="true" onBlur="updateValue(this, 'userLevel', '<?php echo $id;?>')">
<?php echo $userLevel; ?>
</div>
</td>
with a jquery ajax to send data into the php file above
function archiveRow(id) {
$.ajax({
url: 'archiveusers.php',
type: 'post',
data: {
id: id
},
success: function(php_result) {
console.log(php_result);
}
});
}
Assuming that your code is working, your comparison is flawed:
WHERE md5(userId) = :id OR userId = :id
The md5function returns a string and :id is PDO::PARAM_INT. In MySQL, the comparison of string with number is guaranteed to produce unexpected results:
select '912ec803b2ce49e4a541068d495ab570' = 912 -- 1
select '912ec803b2ce49e4a541068d495ab570' = 913 -- 0
Your php code should be like this:
$sql = "... WHERE md5(userId) = :id_str OR userId = :id_int";
$stmt->bindParam(":id", $id_str, PDO::PARAM_STR);
$stmt->bindParam(":id", $id_int, PDO::PARAM_INT);
That still looks incorrect to me though. The roper solution is to check if $_POST['id'] contains a md5 hash or an integer (using filter_input with FILTER_VALIDATE_INT and FILTER_VALIDATE_REGEXP) then build the query + parameters based on that.

How to retrieve multiple data from ajax post function?

I have a select dropdown list and some input fields. My goal is when I select any option from the dropdown list it takes it's value and insert it into the input fields, and that is the ajax post function
<script>
$(document).ready(function(){
$('#productSelect').on('change',function(){
var selectedValue = $('#productSelect').val();
$.post('php/loadProducts.php', {
productId : selectedValue
}, function(data, status) {
$('#id').val(data);
$('#name').val(data);
$('#price').val(data);
});
});
});
</script>
and that is what happens in the "loadProdcut.php" file
<?php
if (isset($_POST['productId'])) {
$productId = $_POST['productId'];
$sql = "SELECT * FROM products WHERE product_id = '$productId';";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$Id = $row['product_id'];
echo $Id;
$Name = $row['product_name'];
echo $Name;
$Price = $row['product_price'];
echo $Price;
}
};
}
?>
Now when I select any option of the dropdown list it inserts all the values (id, name and price) in every single input field, so what I want to achieve is to place every single value into it's input feild.
It's simpler and more reliable to return JSON from an AJAX call to the server if for no other reason than you then return it all in one lump rather than in multiple echo's
Also a prepared statement protects you from bad actors attempting to mess up your database.
I am assuming as you are using a product_id to access a product table there will be only one row returned, so the loop is unnecessary
<?php
if (isset($_POST['productId'])) {
// query with prameter ?
$sql = "SELECT product_id, product_name, product_price
FROM products WHERE product_id = ?";
// prepare it
$stmt = $conn->prepare($sql):
// bind the parameter to its data
$stmt->bind_values('i', $_POST['productId']);
$stmt->execute();
// get resultset from the execution of the query
$result = $stmt->get_result();
$row = $result->fetch_assoc();
//return the row (an array) converted to a JSON String
echo json_encode($row);
}
Now you need to amend the javascript to process the nice object you have just returned.
<script>
$(document).ready(function(){
$('#productSelect').on('change',function(){
var selectedValue = $('#productSelect').val();
$.post('php/loadProducts.php', {productId : selectedValue}, function(data, status) {
$('#id').val(data.product_id);
$('#name').val(data.product_name);
$('#price').val(data.product_price);
});
});
});
</script>

PHP not inserting into SQL columns

I'm using Ajax to collect the data such as the winningReddit, the LosingReddit, and the win and lose photos. The PHP script (below) is then supposed to send that to the MySQL tables. The "win" and "lose" columns should increase by 1 each time.
For some reason this script is not saving to the database though. What am I doing wrong? Am I missing something?
<?php
if(isset ($_POST['action'])) {
include( 'connection.php');
$winnerLink = $_POST['winnerReddit'];
$loserLink = $_POST['losingReddit'];
$win = $_POST['win'];
$lose = $_POST['lose'];
mysql_query("UPDATE $winnerLink SET win = win + 1 WHERE imagelink = '$win'");
mysql_query("UPDATE $loserLink SET lose = lose + 1 WHERE imagelink = '$lose'");
}
?>
Here's the Ajax code I'm using:
$.ajax({
url: 'http://website.com/vote.php',
method: 'POST',
data: {
action: 'save',
win: chosenURL,
lose: chosenURL,
winnerReddit: $(this).attr('id'),
losingReddit: $(this).siblings('div').attr('id')
},
success: function(data) {
alert('sent');
},
error: function() {
alert('nope')
}
});
})
})
Replace this
mysql_query("UPDATE $winnerLink SET win = win + 1 WHERE imagelink = $win");
mysql_query("UPDATE $loserLink SET lose = lose + 1 WHERE imagelink = $lose");
With this prepared statement:
$stmt = mysqli_prepare("UPDATE ? SET win = win + 1 WHERE imagelink = ?");
$stmt->bind_param("ss", $_POST['winnerReddit'], $_POST['win']);
$stmt->execute();
$stmt->close();
$stmt = mysqli_prepare("UPDATE ? SET lose = lose + 1 WHERE imagelink = ?");
$stmt->bind_param("ss", $_POST['losingReddit'], $_POST['lose']);
$stmt->execute();
$stmt->close();
You will also need make sure you have connected to a database.

PHP/jQuery AJAX algorithm only working every other time

I am trying to build a page that uses jQuery to call a database every second and return the highest numbered row.
The jQuery code is below (this is in $('document').ready)
var id = 0;
$.post('check.php', 'id=0', function(data){
id = parseInt(data);
$('h1').text(data);
});
var timer = setInterval(function() {
$.post('check.php', 'id=' + id, function(data){
if (data != '')
$('h1').text(data)
else
$('h1').text("NOTHING!");
id = parseInt(data);
});
}, 1000);
And the PHP file, check.php, has the following code (after connecting to the database):
$id = $_POST['id'] - 1;
$query = "SELECT * FROM testtable WHERE 'id' > $id ORDER BY id DESC";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
echo "$row[0]";
When 'id' is the first column.
The highest row number right now is 13. I would expect it to send 13 to the PHP file. $id would then be 12, so it would select all rows with id values higher than 12, returning the row with id value 13. Then it would echo "13", which is sent back to jQuery, which is parsed to an integer, making id equal to 13. Then 13 is sent to the PHP file again a minute later, and the process cycles.
What's actually happening is that it's alternating between displaying "13" and "NOTHING!", and I can't figure out why.
Because select * from tesstable where id > 13 will always be an empty result if 13 is the highest id. What you want is this:
select max(id) as id from testtable
You don't have to send back $id, and if it's got an index on it, this query will return very quickly.
Also, your original query has the column id in quotes, not backticks. You're comparing the string "id" with your variable $id. To top that off, you're susceptible to SQL injection here, so use mysql_escape_string, PDO, or remove the variable reference altogether using the max query provided.
I'll suggest you to do it like this.Try it.And tell if it's working.
var id = 0,count = 0;
$.post('check.php', {id:0}, function(data){
id = +data["rows"]; // Try parse or just a +
$('h1').text(data);
count++;
},"json");
var timer = setInterval(function() {
$.post('check.php', {id:id-count}, function(data){
if (data["rows"] != null || data["rows"] != "")
$('h1').text(data)
else
$('h1').text("NOTHING!");
id = +data["rows"];
count++;
},"json");
}, 1000);
$id = $_POST['id'];
$queryString = ($id == 0) ? "'id' > $id" : "'id' = $id";
$query = "SELECT * FROM testtable WHERE $queryString ORDER BY id DESC";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
echo json_encode(array("rows" => "$row[0]");

Categories