How to retrieve multiple data from ajax post function? - php

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>

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.

on append data with ajax call returns only first row from database in jquery and php?

I am working with jquery and php to get data from database onchange particular selection.
My ajax call works fine.but it shows only first row from table.
my ajax call:
$.ajax({
method: "GET",
dataType: 'json',
url:"getdata.php?id="+emp_id,
success:function (response){
$.each(response, function( index, value ) {
$(".bodytable").empty();
$("table.table").append("<tr><td>" + response.emp_name + "</td><td>" + "</td><td><input type='file'></td></tr>");
});
},
});
and below is my query for the same :
if(isset($_GET['id'])){
$explodeVal = $_GET['id'];
$sql = "SELECT * FROM emp_master_new as emn
INNER JOIN emp_info as cti ON emn.id=cti.id
WHERE cti.com_id = '".$explodeVal."' ";
$execute = mysqli_query($con, $sql);
$row=mysqli_fetch_array($execute,MYSQLI_ASSOC);
echo json_encode($row);
}
on success response i only get [object object].
You should get all records from php file by using mysqli_fetch_all as below:
if(isset($_GET['id'])){
$explodeVal = $_GET['id'];
$sql = "SELECT * FROM emp_master_new as emn
INNER JOIN emp_info as cti ON emn.id=cti.id
WHERE cti.com_id = '".$explodeVal."' ";
$execute = mysqli_query($con, $sql);
$row=mysqli_fetch_all($execute,MYSQLI_ASSOC);
echo json_encode($row);
}
Hope it helps you.

Running two select queries in php and encoding it in json format

How would I go about returning two JSON objects with one AJAX call and PHP function?
Here's the HTML :
// bootstrap modal
<div id="paymentViewModal" class="modal fade">
<form method="POST" id="update_payment">
<input type="text" class="totalAmount" id="totalAmount">
<br>
<input type="text" class="pdAmount" id="pdAmount">
</form>
</div>
And the Jquery :
$(document).on('click', '.payment_data', function() {
var pymnt_id = $(this).val();
$.ajax({
url:"sum_total.php",
method:"POST",
data:{pymnt_id:pymnt_id},
dataType:"json",
success:function(data){
// textboxt totalAmount
$('#totalAmount').val(data.total_order_value);
//textbox pdAmount
$('#pdAmount').val(data.paid_total);
$('#paymentViewModal').modal('show');
}
});
});
the result comes perfect from 1st query but I want to execute both query
// sum_total.php
if(isset($_POST["pymnt_id"]))
{
$query = mysqli_query($conn, "SELECT SUM(sub_total) AS total_order_value FROM tbl_order2
WHERE order_customer_id = '".$_POST["pymnt_id"]."'
");
$row = mysqli_fetch_array($query);
// if i run only one query its work fine
// want to get result from both tables
$query = "SELECT SUM(payment_amount) AS paid_total FROM payments
WHERE customer_id = '".$_POST["pymnt_id"]."'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_array($result);
}
echo json_encode($row);
?>
You are rewriting to the $row hence the old data is getting overwritten. consider doing something like this:
Also, consider using PDO prepared statments
note: untested code
// sum_total.php
if(isset($_POST["pymnt_id"]))
{
$output = [];
// use prepared statements to prevent SQL injection
$query = $conn->prepare($conn, "SELECT SUM(sub_total) AS total_order_value FROM tbl_order2
WHERE order_customer_id = ?
");
$query->exec($_POST["pymnt_id"]);
$output["row1"] = $query->fetch();
// if i run only one query its work fine
// want to get result from both tables
$query = "SELECT SUM(payment_amount) AS paid_total FROM payments
WHERE customer_id = ?";
$query->exec($_POST["pymnt_id"]);
$output["row2"] = $query->fetch();
// echo inside the if statement
echo json_encode($output);
}
Hope it helps
Add your rows to and array and then echo the entire array.
// sum_total.php
if(isset($_POST["pymnt_id"]))
{
$output = array();
$query = mysqli_query($conn, "SELECT SUM(sub_total) AS total_order_value FROM tbl_order2
WHERE order_customer_id = '".$_POST["pymnt_id"]."'
");
$row = mysqli_fetch_array($query);
$output['row1'] = $row;
// if i run only one query its work fine
// want to get result from both tables
$query = "SELECT SUM(payment_amount) AS paid_total FROM payments
WHERE customer_id = '".$_POST["pymnt_id"]."'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_array($result);
$output['row2'] = $row;
}
echo json_encode($output);
?>

How to add item/post to favourites

I'm trying to create a button which will allow users to favourite certain posts using php and jquery (ajax). I've been trying to use This answer on here to get it all working, but I'm having trouble with getting the post id specific to the post that is meant to be favourited and instead it always gives the post id of the last post to be loaded on the page. Here's my code as it is, but I suspect I've probably just made a mistake in adapting it.
I have 3 tables; Users, Posts and Favourites. In Users I have username password and id, Posts I have id (and content) and in Favourites I have id, userid and postid.
Jquery:
<script>
$(document).ready(function() {
$('.favourite').on('click', null, function() {
var _this = $(this);
var postid = _this.data('$postid');
$.ajax({
type : 'POST',
url : '/add.php',
dataType : 'json',
data : '$postid='+ postid,
complete : function(data) {
if(_this.siblings('.favourite'))
{
_this.html('<img src="add2.png" />');
}
else
{
_this.html('<img src="add1.png />');
}
}
});
});
});
</script>
Main PHP (index.php):
<?php
$getposts = mysql_query("SELECT * FROM Posts ORDER BY id DESC") or die(mysql_query());
while ($row = mysql_fetch_assoc($getposts))
{
$id = $row['id'];
$user = $_SESSION['user'];
$findid = mysql_query("select * from Users where username='$user'");
if ($rows = mysql_fetch_assoc($findid));
{
$userid= $rows['id'];
$postid= $id;
}
echo '<img src="add1.png" />';
}
?>
(There is other code, but it's not related to this section.)
add.php:
<?php
session_start();
require_once('connect.php');
$userid = $_SESSION['$id'];
$postid = $_SESSION['$postid'];
$query_favorite = "SELECT userid, postid FROM Favourites";
$favorite = mysql_query($query_favorite) or die(mysql_error());
$row_favorite = mysql_fetch_assoc($favorite);
$totalRows_favorite = mysql_num_rows($favorite);
if(in_array($_POST['id'], $row_favorite))
{
$Del="DELETE FROM Favourites WHERE userid='$userid' AND postid='$postid'";
$result = mysql_query($Del);
}
else
{
$Add = "INSERT INTO Favourites (userid, postid) VALUES ('$userid', '$postid')";
$result = mysql_query($Add);
}
?>
Thanks in advance for any assistance!
In main.php you are using data-id="' . $postid . '".
Which inserts the postId into the HTML, right?
But in your Javascript you are trying to fetch this data element with
var postid = _this.data('$postid');
data : '$postid='+ postid,
instead of
var post_id = _this.data('id');
data : 'id='+ post_id,
Because your data attribute isn't data-$postid, but data-id.
Same error in add.php:
$userid = $_SESSION['$id'];
$postid = $_SESSION['$postid'];
without single-qoutes:
$userid = $_SESSION[$id];
$postid = $_SESSION[$postid];
Because, when you single-quote the variable, then its the string "$id",
which isn't in $_SESSION.
and you have to fetch $id(postid) from the $_POST data send with your AJAX request. The code missing is: json_decode incoming POST and grab the id, then use it...
Debugging hints:
test that the data is inserted into HTML
add var_dump($_POST); to add.php in order to see the data the AJAX requests posts. The "id" should be part of it.
json_decode() the incoming $_POST to get the ID
and then use it on other variables

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