I have a table with dynamically created rows ('s) - in each is a set of inputs, one of which is an autocomplete input field where the user can search for an item and is given a list of choices, when they select one, the details of their ITEM are populated in all the remaining fields and an image that corresponds to their choice is called from the Database.
Here's my DB call Query:
$return_arr = array();
$param = $_GET["term"];
$fetch = mysql_query("SELECT * FROM crd_jshopping_products WHERE `name_en-GB` REGEXP '^$param' LIMIT 5");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['product_name'] = $row['name_en-GB'];
$row_array['category'] = $row ['meta_keyword_en-GB'];
$row_array['jshop_code_prod'] = $row['product_ean'];
$row_array['_ext_price_html'] = number_format($row['product_price'],2);
if (!empty($row['product_thumb_image']) AND isset($row['product_thumb_image'])){
$row_array['image'] = $row['product_thumb_image'];
}else {
$row_array['image'] = 'noimage.gif';
}
array_push( $return_arr, $row_array );
}
mysql_close($conn);
echo json_encode($return_arr);
In my JQuery all I have to do is place this:
$('#prodImage').append('<img class="imgLoads" src="/components/com_jshopping/files/img_products/' + ui.item.image + '" >');
So it will put the Image into the div ID : prodImage.
I have tried IF Statements:
if ($('#prodImage').length)
{
$('#prodImage').append('<img class="imgLoads" src="/components/com_jshopping/files/img_products/' + ui.item.image + '" >');
}
else {
$('#prodImage').remove();
}
And ...
if (!$('#imgLoads').length)
{
$('#prodImage').append('<img class="imgLoads" src="/components/com_jshopping/files/img_products/' + ui.item.image + '" >');
}
else if($('#imgLoads').length){
$('#prodImage').remove();
}
And a whole bunch of variations and replaceWith() statements, but to no avail.
You can check out the live interface here :
http://cardoso.co.za/index.php/login-shop
Username: stackUser
Password: demo
What happens, at best, is the images bunch up one under the other ...
Any help is appreciated. I have also tried the following post, but it didn't work :(
Change image src with jQuery autocomplete
In Response to RST's piece of code, here is how I have tried to implement it so that it only changes the image in the exact TR where the autocomlete ifield is changed:
$(this).closest('#product_name').blur(function(){
$('.imgLoads').attr('src','/components/com_jshopping/files/img_products/' + ui.item.image);
});
This is how I solved the issue:
$(this).closest('tr').find('#product_name').blur(function(){
$(this).closest('tr').find('.imgLoads').attr('src','/components/com_jshopping/files/img_products/' + ui.item.image);
$(this).closest('tr').find ('.imgLoads').attr('style','border-radius:8px;-webkit-border-radius:8px;-moz-border-radius:8px;border:solid 1px #CF3;');
});
In your HTML set the image tag already
<div id="prodImage">
<img class="imgLoads" src="">
</div>
jQuery
$('.imgLoads').attr('src','/components/com_jshopping/files/img_products/' + ui.item.image);
This code should go in a function, something like:
$('#some-element-id').change(function(){
$('#prodImage img.imgLoads').attr('src','/components/com_jshopping/files/img_products/' + ui.item.image);
)};
So it will adjust when selections are made.
Solved by using this code, after tweaking a lot of things, thanks again RST!
$(this).closest('tr').find('#product_name').blur(function(){
$(this).closest('tr').find('.imgLoads').attr('src','/components/com_jshopping/files/img_products/' + ui.item.image);
$(this).closest('tr').find ('.imgLoads').attr('style','border-radius:8px;-webkit-border-radius:8px;-moz-border-radius:8px;border:solid 1px #CF3;');
});
Related
I am new here and newbie learner. I've checked some similar questions like this but could not get them to work.
What I am trying to achieve is, querying my database, retrieve list of accounts, then jquery function sends a query to ajaxtest2.php file for each of the account to retrieve account information and shows it in a html table.
Main problem is, table is populating with information of the last account in the database instead of all accounts.
I am getting this output at the moment:
`3459 1459 3459 1459`
Your help will be much appreciated.
Thank yoU :)
include_once('database.php');
$sql1 = "select * from account ";
$result1 = mysql_query($sql1);
while ($arr1 = mysql_fetch_array($result1)) {
$var = $arr1["account_no"];
?>
<script type="text/javascript">
$(document).ready(function() {
$(window).load(function() {
var numValue = <?php echo $var; ?>;
$.getJSON("ajaxtest2.php", {number: numValue}, function(data){
var trHTML = '';
$.each(data, function () {
trHTML += '<td>' + data.bal + '</td><td>' + data.eq + '</td>';
});
$('#location').append(trHTML);
});
}); `
});
</script>
<table id="location" border='1'>
</table>
<?php
}
The below is the response from ajaxtest2.php
echo json_encode(array("bal" => "$balance", "eq" => "$equity"));
?>
Make sure that you have table rows when you generate the cells.
trHTML += '<tr><td>' + data.bal + '</td><td>' + data.eq + '</td></tr>';
Else your cells will always append to the right of the previous cell without changing rows
Also, the your code could all be done using PHP only (no js)
Here's how:
<?php
include_once('database.php');
$sql1 = "select * from account ";
$result1 = mysql_query($sql1);
?>
<table id="location" border='1'>
<?php
while ($arr1 = mysql_fetch_array($result1)) {
$var = $arr1["account_no"];
//your ajaxtest2.php functionnalities go here
//let's say $accBalance and $accEquity contain the information you wanted about that specific row
echo '<tr><td>'.$accBalance.'</td><td>'.$accEquity.'</td></tr>';
}
?>
</table>
And there you have your populated table using database values without using JS.
Hoped it helped!
I have a problem on selecting an id on div. I use a while loop on my div.
So i'am creating a unique ID using the id row on my sql. My question is, is it possible to select the id using Javascript? I use bootstrap modal to update my information details (i dont actually know how to ask this question because my english is poor).
example:
while($row = mysqli_fetch_array($result)) {
<div id="'details-'<?php echo $row['Room_ID'];?>">
//code
</div>
}
To fix your Php code:
while($row = mysqli_fetch_array($result)) {
echo "<div id='details-" . $row['Room_ID'] ."'>";
// CODE
echo "</div>";
}
The problem you got in the id, where you stopped the value by ' already, so the result was something like:
<div id='details-'28>//Code</div> and fixed to <div id='details-28'>//Code</div>
and to select the ID with pure JavaScript use document.getElementById( ID )
If you are not sure of the ID and you just wanna select all items, add a class to the item and select them all by document.getElementsByClassName
So to select all your stuff by javascript:
1) Add into your PHP code class called "details"
2) Create a javascript to select all items with the class name "details"
3) Do a foreach loop for the selected items and split them by "-" to devide the "details" from the actual ID
4) Do whatever you want now with the ID
Practical showcase:
Php:
while($row = mysqli_fetch_array($result)) {
echo "<div class='details' id='details-" . $row['Room_ID'] ."'>";
// CODE
echo "</div>";
}
JavaScript:
<script>
var itemDetails = document.getElementsByClassName("details");
for(var i = 0; i < itemDetails.length; i ++) {
var ID = itemDetails[i].getAttribute("id").split("-")[1];
// Now you got the ID stored in the variable ID
</script>
Here you got an example on JSFiddle
As for as my understanding from your code, you are want to create a div with id details from your database. For that you should correct your code as given blew
<?php
while($row = mysqli_fetch_array($result)) {
echo "<div id='details-'". $row['Room_ID'];">";
//code
echo "</div>";
}
?>
If it is problem to select it and perform some manipulations using jQuery/javascript you may consult the official API documentation at
This link
I am trying to show the results of the status of a bidding item using jQuery every second on every row in MySQL table, however only the result of the last row of the table is returned.
<?php
$query = "SELECT item, description, price, imageData, status, username, item_id FROM items";
$result = mysql_query($query) or die(mysql_error());
$z=0;
while($row = mysql_fetch_array($result))
{
//echo other columns here//
echo "<td><div id=status$z></div></td>";
?>
<script type=text/javascript>
function updatestatus(itemnum)
{
var url="updatestatus.php?auc=<?php echo $row['item_id']; ?>";
jQuery('#status' + itemnum).load(url);
}
setInterval("updatestatus(<? echo $z?>)", 1000);
</script>
<?
$z++;
}
?>
When I view source in the browser, the values for #status and auc for every row are correct. What am I missing here?
Here's the code for updatestatus.php
<?php
session_start();
require_once("connect.php");
$id = $_GET['auc'];
$getstatus = mysql_query("SELECT status FROM items WHERE item_id = '$id' ");
$row = mysql_fetch_array($getstatus);
echo"$row[status]";
?>
Everything looks good, save for the fact that it looks like you're creating multiple references to your updatestatus() function.
In Javascript, if you create multiple functions with the same name, calling them will only result in one of them running, usually the first or last one (depending on the implementation), so all the code you need to run in those functions needs to sit together in one function body.
If you're determined to use the code you've created, you'd need to throw all those update calls into one function body. There would be better ways to achieve what you need, but doing it with the code you've created, this would probably work better:
<?php
$query = "SELECT item, description, price, imageData, status, username, item_id FROM items";
$result = mysql_query($query) or die(mysql_error());
$javascript = "";
$z=0;
while($row = mysql_fetch_array($result))
{
//echo other columns here//
echo "<td><div id=status$z></div></td>";
// build the javascript to be put in the function later over here...
$javascript .= "jQuery('#status". $z ."').load('updatestatus.php?auc=". $row['item_id'] ."');";
$z++;
}
?>
...and then further down the page, create the javascript (modified slightly):
<script type=text/javascript>
function updatestatus()
{
<?php echo $javascript; ?>
}
setInterval(updatestatus, 1000);
</script>
So you're basically building up the Javascript that you'll need in your function, echoing it out inside the function body, and then setting the interval will call all that code, in this case, every second.
Like I said, there are definitely more efficient ways to achieve what you're trying to do, but this should work fine for now. I hope this makes sense, but please let me know if you need any clarity on anything! :)
I don't see that you're populating data using a incrementor. Is this supposed to be adding content to a page or replacing the content? from what it looks like it will just display one item, and then replace that one item with the next until it's done, which is why you see only the last row.
OR ...
the jquery update isn't being fed the $i variable .. change the function to
function updatestatus(itemnum) {
and then jquery echo to jQuery('#status' + itemnum).load(url);
then you can add the on-click/ or whatever to include the number
onclick='updatestatus("1")'
on the other hand you might be needing to pass the total number of items to the function and then creating an if there to cycle through them (not tested, but you get the idea i hope)
function updatestatus(numitems) {
var url = "";
var itemID = "";
for (i = 1; i <= numitems; i++) {
itemid = getElementById('#status'+numitems).getAttribute("itemID")
url="updatestatus.php?auc="+itemID;
jQuery('#status'+numitems).load(url);
}
}
setInterval("updatestatus()", 1000);
and the html element for "#status1" as created by the PHP should look like this:
<div id="status1" itemid="23455">
</div>
i'm having trouble with the serialize Jquery fonction.
Fist, i create my li element with a php script, my data are written in my database (with "id", "contenu", "position") and catch it in my html :
<article>
<ul id="columns">
<?php
$req01=mysql_query("SELECT * FROM mytable ORDER BY id DESC");
$i=0;
while ($res01=mysql_fetch_array($req01)){
$i++;
echo '
<li class="column" id="listItem_'.$res01["position"].'" draggable="true">
<p>'.$res01["contenu"].'</p>
</li>';
}
?>
</ul>
</article>
And here's my script
$(document).ready(function() {
$("#columns").sortable({
column : '.column',
update : function () {
var order = $('#columns').sortable('serialize');
$("#info").load('structure-reform.php?'+order);
//alert("Data Loaded: " + order);
}
});
});
</script>
And here the way i update my DB when my li order is changing
foreach ($_GET['listItem'] as $position => $item) :
$list[] = "$position, $item";
$req03=mysql_query("UPDATE mytable SET position='".$position."' WHERE id='".$item."'");
$result = mysql_query($req03);
endforeach;
The thing is that, when i reload my page, my list isn't sorted the right way...How can i do in order to keep my list in the last order ?
Thanks !
Your logic wasn't correct.
replace your javascript with this:
$("#columns").sortable({ update: function() {
var order = $(this).sortable("serialize");
$.post("structure-reform.php", order);
}
});
replace your list html with this
<li class="column" id="listItem_'.$res01['id'].'" draggable="true" rel="'.$perso.'">
<p>'.$res01["contenu"].'</p>
</li>';
replace your while loop with this
$listingCounter = 1;
foreach ($_POST['listItem'] as $recordIDValue) {
$query = "UPDATE structure SET position = " . $listingCounter . " WHERE id = " . $recordIDValue;
mysql_query($query) or die('Error, insert query failed');
$listingCounter = $listingCounter + 1;
}
echo 'If you refresh the page, you will see that records will stay just as you modified.';
You'll either want to save the order parameter in PHP - store it in $_SESSION, or, set a cookie on the user's computer and retrieve that to sort.
why you don't use jquery ajax using $.ajax() ? may be there is problem with serialize(), have you tried this one ?
$("#columns").sortable({
column : '.column',
update : function () {
var order = $(this).sortable('serialize');
$.ajax({
url : 'structure-reform.php',
type: 'GET',
data: order,
success:function(res){
alert('Data Loaded '+res);
}
});
}
});
and fot the first time, you should debug your parameter from ajax request, using php it quite simple
<?php
print_r($_GET);
?>
then you can do the rest when you have know what paramter are given there
Im trying to copy data to clipboard using zclip jquery. problem that im facing is when i copy it will copy everything in the database in field "name". but what i want is to copy a single name that user clicked. if the click another copy that. not the whole thing. can anyone tell me how to do this. thanks.
this is the zclip code
$(document).ready(function(){
$('p#copy').zclip({
path:'js/ZeroClipboard.swf',
copy:function(){return $('div#copy').text();}
});
MySQL loop:
$query = "SELECT * FROM names ORDER BY id desc";
$result= mysql_query($query) or die ('Mysql Error');
while($row = mysql_fetch_array($result)){
echo '<div id="copy">'.$row['name'].'</div>';
echo '<p id="copy">copy</p>';
}
zclip site: http://www.steamdev.com/zclip/
The HTML you generate is not valid which is hindering you in the end to achieve the result you're looking for: in HTML an ID can only be used once (see: Element identifiers: the id and class attributes). You are using the same ID for multiple DIVs. That can not work, as an ID must be unique across the whole HTML document.
Instead assign one ID to each DIV (e.g. by using a counter) and then apply the jquery function on the specific DIV only.
$idCounter = 0;
while($row = mysql_fetch_array($result))
{
$idCounter++;
echo '<div id="copy-div-', $idCounter, '">', $row['name'], '</div>';
echo '<p id="copy-p-', $idCounter, '" class="copy-click">copy</p>';
}
Code-Example: Create multiple IDs with a counter variable