Send php variables to jquery function - php

Ok, I need to send data from PHP to jquery and use jquery function to update that data into HTML.
But the problem is jquery want update HTML elements with PHP data...
This is php code.Php is called from ajax.
$product_image = "";
$product_name = "";
$product_description = "";
$product_size = "";
if(mysqli_num_rows($r) > 0) {
while($row = mysqli_fetch_assoc($r)) {
$product_image = "wp-content/themes/meditalis-to-wp/assets/products/" . $row["image"];
$product_name = $row["name"];
$product_description = $row["description"];
$product_size = "wp-content/themes/meditalis-to-wp/assets/products/" . $row["img_size"];
echo '<script type="text/JavaScript">';
echo 'var product_image = ' . json_encode($product_image) . ';';
echo 'var product_name = ' . json_encode($product_name) . ';';
echo 'var product_description = ' . json_encode($product_description) . ';';
echo 'var product_size = ' . json_encode($product_size) . ';';
echo 'showProduct();';
echo '</script>';
}
}
//echo $product_num_id;
mysqli_close($dbc);
exit();
}
This is jquery function for updating html elemtns:
function showProduct()
{
alert("dbg");
$("#product_name_put").html(product_name);
$("#product_desc_put").html(product_description);
$("#product_image_put").attr("src", product_image);
$("#product_size_put").attr("src", product_size);
}
And this is html elements:
<div class="product_view_info">
<ul class="product">
<li><img id="product_image_put" src="" alt=" Product Photo"></li>
<li class="informations">
<div class="product_name"><h4 id="product_name_put"></h4></div>
<div class="desc_info"><p id="product_desc_put"></p></div>
<img id="product_size_put" src="" alt="Size Photo">
</li>
</ul>
</div>
This is a problem: https://ibb.co/HGyJkwB
UPDATE: AJAX CODE: When user click on product ajax sending id of clicked product to php.
$(document).on("click touchend", ".product_stake_stapovi, .product_invalidska_kolica, .product_antidekubitni_program, .product_ortoze, .product_mideri, .product_pojas, .product_toaletni_program, .product_bolnicki_kreveti_i_oprema", function (event) {
var product_num_id = $(this).children(".num_id").attr("id"); //Getting id from image element (that is location of real stored id in database)
var product_id = $(this).attr("class");
var product_real_id = product_id.replace("col-3 col ", "");
$.ajax({
method: "POST",
url: "index.php?proizvodi",
data: ({product_num_id:product_num_id}),
success: function() {
$(".big_categoryes").fadeOut("fast");
$(".all_products").fadeOut("fast");
$(".product_view_info").fadeIn("smooth");
}
});
});

U can get data from PHP as json like so:
if(mysqli_num_rows($r) > 0) {
while($row = mysqli_fetch_assoc($r)) {
$product = (object)[];
$product->image = "wp-content/themes/meditalis-to-wp/assets/products/" . $row["image"];
$product->name = $row["name"];
$product->description = $row["description"];
$product->size = "wp-content/themes/meditalis-to-wp/assets/products/" . $row["img_size"];
echo json_encode($product);
}
}
mysqli_close($dbc);
exit();
and get data from json with jquery:
$(document).on("click touchend", ".product_stake_stapovi, .product_invalidska_kolica, .product_antidekubitni_program, .product_ortoze, .product_mideri, .product_pojas, .product_toaletni_program, .product_bolnicki_kreveti_i_oprema", function (event) {
var product_num_id = $(this).children(".num_id").attr("id"); //Getting id from image element (that is location of real stored id in database)
var product_id = $(this).attr("class");
var product_real_id = product_id.replace("col-3 col ", "");
$.ajax({
method: "POST",
url: "index.php?proizvodi",
data: ({product_num_id:product_num_id}),
success: function(response) {
var product = JSON.parse(response);
console.log(product.image);// example
showProduct(product);
$(".big_categoryes").fadeOut("fast");
$(".all_products").fadeOut("fast");
$(".product_view_info").fadeIn("smooth");
}
});
});
function showProduct(product){
$("#product_name_put").html(product.name);
$("#product_desc_put").html(product.description);
$("#product_image_put").attr("src", product.image);
$("#product_size_put").attr("src", product.size);
}
I hope this could help you.

Related

unable $_GET data in PDO using AJAX for product filtering

Unable to filter product using PDOamd AJAX,
Below code loads data form sql using PDO and AJAX but when i try to filter based on Brand it doesn't work. tried debug var_dump method but nothing helps.
Can someone help me to solve, how do i filter product, is there anything missing in code?
HTML
<div class="md-radio my-1">
<input type="radio" class="filter_all cate" name="cate" id="<?php echo str_replace(' ', '', $row['sca']); ?>" value="<?php echo $row['sca'] ?>">
<label for="<?php echo str_replace(' ', '', $row['sca']); ?>">
<?php echo $row['sca']; ?>
</label>
</div>
SCRIPT
$(document).ready(function () {
var flag = 0;
var fetching = false;
var done = false;
function filter_data() {
// prevent concurrent requests
if (fetching === true) {
return;
}
fetching = true;
var data = {
action: 'fetch_data',
cate: get_filter('cate'),
brand: get_filter('brand'),
model: get_filter('model'),
sort: get_filter('sort'),
date: get_filter('date'),
offset: flag,
limit: 4
};
console.log($.param(data));
$.ajax({
url: "fetch.php?" + $.param(data),
type: 'POST'
})
.done(function (data) {
console.log('data received');
$('.filter_data').append(data); // append
// we reached the end, no more data
if (data === '<h3>No Data Found</h3>') {
done = true;
}
flag += 4;
fetching = false; // allow further requests again
})
.fail(function (error) {
console.log('An error occurred while fetching', error)
// TODO: some error handling
});
}
function get_filter(class_name) {
var filter = [];
$('.' + class_name + ':checked').each(function () {
filter.push($(this).val());
});
return filter;
}
$('.filter_all').click(function () {
filter_data();
});
filter_data(); // commented out for debugging purpose
var $window = $(window);
var $document = $(document);
$window.scroll(function () {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 300 && fetching === false && done === false) {
console.log('infinite scroll');
filter_data();
}
});
});
PHP
<?php
include("$_SERVER[DOCUMENT_ROOT]/include/config.php");
include("$_SERVER[DOCUMENT_ROOT]/include/function.php");
$query = "SELECT * FROM allpostdata WHERE sts = '1' AND mca='Vehicle'";
if (!empty($_GET['cate'])) {
$query .= " AND sca IN (" . str_repeat("?,", count($_GET['cate']) - 1) . "?)";
} else {
$_GET['cate'] = []; // in case it is not set
}
if (!empty($_GET['brand'])) {
$query .= " AND product_brand IN (" . str_repeat("?,", count($_GET['brand']) - 1) . "?)";
} else {
$_GET['brand'] = []; // in case it is not set
}
if (!empty($_GET['model'])) {
$query .= " AND mdl IN (" . str_repeat("?,", count($_GET['model']) - 1) . "?)";
} else {
$_GET['model'] = []; // in case it is not set
}
if (empty($_GET['sort']) || $_GET['sort'][0] == "date") {
$query .= " ORDER BY pdt DESC";
} elseif ($_GET["sort"][0] == "ASC" || $_GET["sort"][0] == "DESC") {
$query .= " ORDER BY prs " . $_GET['sort'][0];
}
if (isset($_GET['limit'])) {
if (!empty($_GET['offset'])) {
$query .= " LIMIT " . $_GET['limit'] . " OFFSET " . $_GET['offset'];
} else {
$query .= " LIMIT " . $_GET['limit'];
}
}
$stmt = $conn->prepare($query);
$params = array_merge($_GET['cate'], $_GET['brand'], $_GET['model']);
$stmt->execute($params);
$result = $stmt->fetchAll();
$total_row = $stmt->rowCount();
$output = '';
if ($total_row > 0) {
foreach ($result as $row) {
$parameter = $row['pid'];
$hashed = md5($salt . $parameter);
$output .= '<a href="/single_view.php?p=' . $row['id'] . '" class="w-xl-20 w-lg-20 col-md-3 col-6 p-1 p-lg-2">
<div class="card border-0 small">
<img class="card-img-top rounded-0" src="/upload/thumb/' . $row["im1"] . '" alt="Card image cap">
<div class="card-body pb-0 pt-2 px-0">
<h6 class="card-title text-dark text-truncate">' . ucfirst(strtolower($row['tit'])) . '</h6>
<h6 class="card-subtitle mb-1 text-muted text-truncate small">' . $row['product_brand'] . ' / ' . $row['mdl'] . '</h6>
<p class="card-text"><strong class="card-text text-dark text-truncate">₹ ' . $row['prs'] . '</strong></p>' . timeAgo($row['pdt']) . '
</div>
</div>
</a>';
}
} else {
$output = '<h3>No Data Found</h3>';
}
echo $output;
?>
You are sending data via GET query parameters despite defining the ajax call as a post. That's a security risk. Try changing your AJAX call to something like this, and replace youyr $_GET stuff to $_POST.
$.ajax({
url: '/your-form-processing-page-url-here',
type: 'POST',
data: data,
mimeType: 'multipart/form-data',
success: function(data, status, jqXHR){
alert('Hooray! All is well.');
console.log(data);
console.log(status);
console.log(jqXHR);
},
error: function(jqXHR,status,error){
// Hopefully we should never reach here
console.log(jqXHR);
console.log(status);
console.log(error);
}
});

Live Update Table entries to database SQL PDO AJAX

i try to make an editable-table on a homepage which automatically save the new entries after you leave the "field" or press enter but something doesnt work.
Everthing is fine until i want to save the new entrie to database.
I fired the PDO-SQL-Statment and it works.
For me it seems to be the table_edit_ajax.php wasnt work but i dont know why!
Hope some of you guys can help me?
Im using a normal mysql database
Homepagecode:
<Table>
$getIDBusinessRessources = $dbPDO->geteditableSingleBusinessRessoure();
foreach($getIDBusinessRessources as $getidBusiness){
$id = $getidBusiness['checkid'] ;
echo '<tr id="'
. $getidBusiness['checkid']
. '" '
. 'class="edit_tr"'
. '>';
// Spalte Ressourcenname
echo '<td class="edit_td">'
.'<span id="RessourceName_'
.$getidBusiness['checkid']
. '" '
. 'class="text">'
.$getidBusiness['Rn']
.'</span>'
.'<input type="text" value="'
.$getidBusiness['Rn']
. '" class="editbox" id="Ressourcname_Input_'
. $getidBusiness['checkid']
.'">'
.'</td>';
// Spalte Amount
echo '<td class="edit_td">'
.'<span id="Amount_'
.$getidBusiness['checkid']
. '" '
. 'class="text">'
.$getidBusiness['AM']
.'</span>'
.'<input type="text" value="'
.$getidBusiness['AM']
. '" class="editbox" id="Amount_Input_'
. $getidBusiness['checkid']
.'" '
.'</td>';
</tr>
</table>
JS:
$( document ).ready(function() {
$(".edit_tr").click(function()
{
var ID=$(this).attr('id');
$("#RessourceName_"+ID).hide();
$("#Amount_"+ID).hide();
$("#Ressourcname_Input_"+ID).show();
$("#Amount_Input_"+ID).show();
}).change(function()
{
var ID=$(this).attr('id');
var first=$("#Ressourcname_Input_"+ID).val();
var last=$("#Amount_Input_"+ID).val();
var dataString = 'id='+ ID +'&RessourceName='+first+'&Amount='+last;
$("#RessourceName_"+ID).html('<img src="img/bearbeiten.png" />'); // Loading image
if(first.length>0&& last.length>0)
{
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#RessourceName_"+ID).html(first);
$("#Amount_"+ID).html(last);
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
Ajax Code:
<?php
include "DBconnection.php";
if($_POST['id']){
$id = $_POST['checkid'];
$RessourceName = $_POST['Rn'];
$Amount = $_POST['AM'];
$dbPDO->UpdateLiveTableEntries($id,$RessourceName, $Amount );
}
?>
and at least the DB-Update code
function UpdateLiveTableEntries($id ,$Ressourcename, $Amount ){
// echo '<script type="text/javascript"> alert("inside");</script>';
$stmt = self::$_db->prepare("UPDATE BalancesheetInput SET RessourceName =:ressname , Amount =:menge WHERE ID =:id");
$stmt->bindParam(":id", $id);
$stmt->bindParam(":ressname", $Ressourcename);
$stmt->bindParam(":menge", $Amount);
$stmt->execute();
}
If you're sending this:
var dataString = 'id='+ ID +'&RessourceName='+first+'&Amount='+last;
^^ ^^^^^^^^^^^^^ ^^^^^^
why are you looking for these?
$id = $_POST['checkid'];
^^^^^---you aren't sending a 'checkid'
$RessourceName = $_POST['Rn'];
^-- you aren't sending an 'Rn'
$Amount = $_POST['AM'];
^^-- you aren't sending an 'AM'

Handling Infinite Scroll Effect Jquery and PHP

Why is the url I created getting 404 instead of loading the page data set to each group I want to show on scroll?
I implemented a infinite scroll effect to paginate my data from a table in my mysql database. Now that I am trying to load the page I am getting a 404 error for the url my query is creating.
example.com/inventory-search.php?limit=15&offset=0&_=1455489762864 404 (Not Found)
I am operating under the impression that the url being formed was specifying the amount of pages and my logic should be keeping track on which page set to be shown. Loading more on scroll.
I did use a tutorial online to get this part of the logic done so I am wondering if I am assuming something that is wrong.
My code looks like this,
DB Config
$db_host = "localhost";
$db_user = "username";
$db_pass = "password";
$db_name = "dbName";
try
{
$DB_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
$DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
?>
Inventory search script,
<?php
require_once get_stylesheet_directory() . '/wuno-search/Dbconfig.php';
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 15;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$sql = "SELECT * FROM wuno_inventory WHERE 1 ORDER BY id ASC LIMIT $limit OFFSET $offset";
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<tr class="invent">';
echo '<td>' . $res['wuno_product'] . '</td>';
echo '<td>' . $res['wuno_alternates'] . '</td>';
echo '<td>' . $res['wuno_description'] . '</td>';
echo '<td>' . $res['wuno_onhand'] . '</td>';
echo '<td>' . $res['wuno_condition'] . '</td>';
echo '</tr>';
}
}
?>
My Jquery
<script type="text/javascript">
jQuery(document).ready(function($) {
var busy = false;
var limit = 15;
var offset = 0;
var assetPath = "<?php echo $assetPath; ?>"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#productResults").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('<button class="btn btn-default" type="button">Loading please wait...</button>').show();
}
window.busy = false;
}
});
}
(function($) {
$(document).ready(function() {
if (busy == false) {
busy = true;
// start to load the first set of data
displayRecords(limit, offset);
}
});
})( jQuery );
(function($) {
$(document).ready(function() {
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#productResults").height() && !busy) {
busy = true;
offset = limit + offset;
displayRecords(limit, offset);
}
});
});
})( jQuery );
});
</script>
define $assetPath
$assetPath = get_stylesheet_directory() . '/wuno-search/inventory-search.php';
?>
There are a number of things that could be factors, but what may be the biggest issue is that you are trying to access result properties that you have not SELECTed. For example, you are trying to get $res['wuno_product'] when you have only selected id in your query. You can always do a print_r($results) or var_dump($results), etc. to see what the query is returning.

Passing data back from php to ajax

How can I pass data from a php of then rows back to ajax ?
PHP
$query = 'SELECT * FROM picture order by rand() LIMIT 10';
$result = mysql_query($query);
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url[]=$rec['pic_location'];
$name[]=$rec['name'];
$age[]=$rec['age'];
$gender[]=$rec['gender'];
}
echo json_encode($url);
echo json_encode($name);
echo json_encode($age);
echo json_encode($gender);
Ajax
$(".goButton").click(function() {
var dir = $(this).attr("id");
var imId = $(".theImage").attr("id");
$.ajax({
url: "viewnew.php",
dataType: "json",
data: {
current_image: imId,
direction : dir
},
success: function(ret){
console.log(ret);
var arr = ret;
alert("first image url: " + arr[0][0] + ", second image url: " + arr[0][1]); // This code isnt working
alert("first image Name: " + arr[1][0] + ", second image name: " + arr[1][1]);
$(".theImage").attr("src", arr[0]);
if ('prev' == dir) {
imId ++;
} else {
imId --;
}
$("#theImage").attr("id", imId);
}
});
});
});
</script>
My question is how can I display the values here ? The Alert message is giving me "Undefined" ?
You can do something along these lines.
PHP
$query = 'SELECT * FROM picture order by rand() LIMIT 10';
$res = mysql_query($query);
$pictures = array();
while ($row = mysql_fetch_array($res)) {
$picture = array(
"pic_location" => $row['pic_location'],
"name" => $row['name'],
"age" => $row['age'],
"gender" => $row['gender']
);
$pictures[] = $picture;
}
echo json_encode($pictures);
JS
...
$.ajax({
...
dataType: "json",
...
success: function(pictures){
$.each(pictures, function(idx, picture){
// picture.pic_location
// picture.name
// picture.age
// picture.gender
});
}
});
...
You can't put multiple echo statements for the AJAX response:
echo json_encode($url);
echo json_encode($name);
echo json_encode($age);
echo json_encode($gender);
Join your arrays and send a single response:
$arr = $url + $name + $age + $gender;
echo json_encode($arr);
You can easily do this using a single Array:
$pics = array();
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$pics[$rec['id']]['url'] = $rec['pic_location'];
$pics[$rec['id']]['name']=$rec['name'];
$pics[$rec['id']]['age']=$rec['age'];
$pics[$rec['id']]['gender']=$rec['gender'];
}
echo json_encode($pics);

mysql_fetch_array's div onmouseover only works for first result

I am new on this website and I hope you'll answer soon.
I want the Remove icon to show up when users hover on their selected friend, but it only appears on mysql_fetch_array's first result. doesn't work for others. can you help? I've heard that it's being done with foreach function but don't know how to use it, because I'm new at php.
Here are the codes.
PHP:
$q = mysql_query("SELECT * FROM `users`");
while ($row = mysql_fetch_array($q)) {
echo '<div id="friends" onmouseover="showRemove();" onmouseout="hideRemove();">';
echo '<div id="fillexit"></div>';
echo '<div id="showexit"></div>';
echo '</div>';
}
Javascript:
function showRemove() {
var l=document.getElementById("showexit");
var s=document.getElementById("fillexit");
l.style.display = 'block';
s.style.display = 'none';
}
function hideRemove() {
var p=document.getElementById("showexit");
var o=document.getElementById("fillexit");
p.style.display = 'none';
o.style.display = 'block';
}
CSS:
#fillexit {
width:12px;
height:12px;
float:right;
}
#showexit {
width:12px;
height:12px;
background-color:#000000;
float:right;
text-align:center;
display:none;
}
I'd really appriciate your help.
It is because the html echoed from php script will have same ids for all row elements.
You should create a unique id using counter or something and change your js accordingly. May be you can pass the id to the js method to help find the elements on the page.
PHP
$q = mysql_query("SELECT * FROM `users`");
$count = 0;
while ($row = mysql_fetch_array($q)) {
echo '<div id="friends'.$count.'" onmouseover="showRemove('.$count.');" onmouseout="hideRemove('.$count.');">';
echo '<div id="fillexit'.$count.'"></div>';
echo '<div id="showexit'.$count.'"></div>';
echo '</div>';
$count = $count + 1;
}
JS
function showRemove(id) {
var l=document.getElementById("showexit" + id);
var s=document.getElementById("fillexit" + id);
l.style.display = 'block';
s.style.display = 'none';
}
function hideRemove() {
var p=document.getElementById("showexit" + id);
var o=document.getElementById("fillexit" + id);
p.style.display = 'none';
o.style.display = 'block';
}
if($q ->num_rows()>0){
foreach ($q ->result()as $row){
echo '<div id="friends" onmouseover="showRemove();" onmouseout="hideRemove();">';
echo '<div id="fillexit"></div>';
echo '<div id="showexit"></div>';
echo '</div>';
}
}

Categories