I'm working on a website with comparing multiple products (Link). The productnames are in a box. With a mouseover I can see their specification in the box. The problem is that I have multiple boxes with different products and all of the specification are loading inside one box. I hope someone can help me.
(It's partly Dutch)
if($nieuws['relateditem'])
{
$array1 = explode(",", $nieuws['relatedoption']);
foreach($array1 as $key2)
{
print_r($key2);
}
$content .='
<h2>Gerelateerde producten</h2>
<div id="product-grid">
<div id="product-grid-inner">
';
$array = explode(",", $nieuws['relateditem']);
$i = 0;
$id = 0;
foreach($array as $key1)
{
$id++;
$i++;
$key1 = trim($key1);
$query4x = $mysqli->query("SELECT * FROM producten WHERE productcode='".$key1."'");
$row2x = $query4x->fetch_assoc();
$hammer = str_replace("XXX", $row2x['id'], $hammertimePro);
$content .='
<div id="'.$id.'blok" class="product-grid-item3" onMouseOver="this.style.border = \'1px solid #007fff\'" onMouseOut="this.style.border = \'1px solid #CCCCCC\'">
<h2 class="titel">'.$row2x['naam'].$hammer.'<br /></h2><br />';
//----
$options2 = explode(",", $row2x['relatedoption']);
foreach($options2 as $option2)
{
$query2 = $mysqli->query("SELECT * FROM producten WHERE productcode = '".$option2."'");
while($row2 = $query2->fetch_assoc())
{
$content.= "<div onMouseOver=\"this.style.backgroundColor='#f0f0f0'; this.style.cursor='pointer'; showConc(".$row2['id'].",1)\" onMouseOut=\"this.style.backgroundColor='#ffffff';\">".substr($row2['naam'], 13, 4)."</div>";
}
}
//---- onMouseOver='showInformation(".$prods['id'].")'
$content.='<div id="specs"></div></div>';
}
$content .= '</div></div>';
}
?>
function showConc(id,box) {
$.ajax({
url: 'http://www.ledisvet.nl/A3/concept_prod.php',
type: 'get',
data: 'id='+id,
success: function(result) {
$('#specs').html(result);
}
});
}
Thanks
There are multiple problems here. The #1 problem is that you have three divs with the id specs. Ids must be unique - the browser doesn't know which #specs box you mean so it picks the first it finds.
You never use the showConc() function's second parameter (box). Even if you did, you have it hardcoded to 1: showConc(".$row2['id'].",1).
Change the showConc() function to something like this:
function showConc(id,box) {
$.ajax({
// ... other parameters here
success: function(result) {
$('#specs'+box).html(result);
}
});
}
Then change the specs ids to specs1, specs2 and specs3 and call the function with the correct number.
Related
There are tons of questions about this, but none of them really deal with Select Options.
My question: I have 4 selects all with multiple values pulled from the database. I want to database information to display, and as the user selects each item it only shows what the user has selected.
For example: Box 1 - A (Show all A) box 2 - year (Show all A with year, if none then display "Nothing matches your search" box 3 ect...
My Code:
if(isset($_POST["action"]))
{
$query = "
SELECT * FROM DB";
if(isset($_POST["producer"]))
{
$producer_filter = implode("','", $_POST["producer"]);
$query .= "
WHERE producer=('".$producer_filter."')
";
}
if(isset($_POST["size"]))
{
$size_filter = implode("','", $_POST["size"]);
$query .= " OR size=('".$size_filter."')
";
}
if(isset($_POST["model"]))
{
$model_filter = implode("','", $_POST["model"]);
$query .= "OR model=('".$model_filter."')";
}
if(isset($_POST["year"]))
{
$year_filter = implode("','", $_POST["year"]);
$query .= "OR year=('".$year_filter."')";
}
$statement = $conn->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if($total_row > 0)
{
foreach($result as $row)
{
$output .= '
<tr><td>'.$row['producer'].'</td>
<td>'.$row['size'].'</td>
<td>'.$row['model'].'</td>
<td>'.$row['year'].'</td>
<td>'.$row['salesman'].'</td>
<td>'.$row['country'].'</td></tr>
';
}
}
else
{
$output = 'Please User Filters to Search for Parts';
}
echo $output;
}
And then my Jquery:
$(document).ready(function() {
filter_data();
function filter_data() {
const action = 'fetch_data';
let producer = get_filter('producer');
let size = get_filter('size')
let model = get_filter('model')
let year = get_filter('year')
$.ajax({
url: "search.php",
method: "POST",
data: {
action: action,
producer: producer,
size: size,
model: model,
year: year
},
success: function(data) {
$('.prod').html(data);
},
});
}
function get_filter(class_name) {
var filter = [];
$('.' + class_name).each(function() {
filterData = $(this).val();
filter.push(filterData)
});
console.log(filter)
return filter;
}
$('.form-control').change(function() {
filter_data();
});
});
This works, however, it displays everything regardless if it matches my filters or not. Is there something I can add in the Jquery?
I appreciate all the help.
How to recover data from research by json? I would like to recover the separate items as the result show in php page to create new elements, for example recover item.f, item.m to create new elements like item.f < / div> < span > item.m. .. thank you
(error presented at)
Error Can not read property of items " of null
Php page ( does the query )
if ($_GET['action'] == "chatheartbeat") { chatHeartbeat(); }
function chatHeartbeat() {
$sql = "select * from mensagens ";
$query = mysql_query($sql);
$items = '';
$chatBoxes = array();
while ($chat = mysql_fetch_array($query)) {
$items. = << < EOD
{
"s": "0",
"f": "{$chat['de']}",
"m": "{$chat['mensagem']}",
"i": "{$chat['img']}"
},
EOD;
}
}
Index ( calls the pair query present the results - error here - need help here)
$.ajax({
url: "asd.php?action=chatheartbeat",
cache: false,
dataType: "json",
success: function(data) {
$.each(data.items, function(i, item) {
alert(item.f)
});
}
});
As #jeroen says dont manually generate JSON Strings use json_encode() to create a JSONString from a PHP array or an object.
if ($_GET['action'] == "chatheartbeat") {
$sql = "select * from mensagens ";
$query = mysql_query($sql);
$chatBoxes = array();
while ($chat = mysql_fetch_array($query)) {
$t - new stdClass();
$t->s = "0";
$t->f = $chat['de'];
$t->m = $chat['mensagem'];
$t->i = $chat['img'];
$chatBoxes[] = $t;
}
$items = json_encode($chatBoxes);
// now just echo $items to return it to the javascript in the browser
// here or later in the code if there is more to your code than you showed us
echo $items;
}
References:
json_encode()
json_decode()
Thank you all for the help, I managed to solve the problem as follows
Php page ( does the query )
$result = mysql_query("SELECT * FROM mensagens");
while( $array = mysql_fetch_assoc($result)){
$table[]= array("de"=>$array['de'],"mensagem"=>$array['mensagem']); }
echo json_encode($table);
Index
$.ajax({
url: 'asd.php',
dataType: 'json',
success: function(data)
{
for($i=0; $i < data.length; $i++){
$("#chatbox_"+chatboxtitle+" .chatboxcontent").append(
'<div class="message"><span class="from">'+data[$i].de+':
</span><span class=content">'+data[$i].mensagem+'</span></div>');
}}
});
I have a problem when trying to select the <li> inside a <ul> list from an ajax response using jQuery.html();
This is my AJAX request:
if (searchid != '') {
$.ajax({
type: "POST",
url: "/service/search.php",
data: dataString,
cache: false
}).done(function (html) {
$("#result").html(html).show();
var images = $("#result").find(".dbRows.sixth").html();
console.debug(images);
})
.fail(function (jqXHR, textStatus) {
$("#explainMessage").html('Unable to check at the moment. Please retry later').show();
})
}
return false;
and in php I have this code:
if ( mysqli_num_rows($result)==0)
{
$display = '<div id="explainMessage" class="explainMessage">Sorry, this was not found.</div>';
echo $display;
} else {
$counter = 0;
while ($row = $result->fetch_assoc()) {
++$counter;
$image_filename = $row['image_filename'];
$imageFolder = $_SERVER['DOCUMENT_ROOT'] . '/service/img/';
$imageList = scandir($imageFolder, 1);
$imageLink = '/service/img/' . $image_filename;
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $image_filename);
$pattern = '/^(' . quotemeta($withoutExt) . ').*$/';
$display = '<div class="dbRows sixth" style="display:none"><ul>';
foreach ($imageList as $image) {
if (preg_match($pattern, $image)) {
if (in_array($image, $imageList)) {
$display .= '<li><img src="' . $imageLink . '" /></li>';
}
}
};
$display .= '</ul></div>';
echo $display;
the problem is that when I try to use the AJAX.done(); function, in my console I have just <ul></ul> without the list of images.My question is, why i can't select the code inside the <ul> tags even if the list of images is actually in the code? I'm pretty new with PHP, any help will be really appreciated. Thanks in advance.
You are doing it wrong. As I doubt before asking you for response HTML, you have blank `'.
$("#result").find(".dbRows.sixth").html() will print html for first matched element only.
Try this, if you want to fetch html for all matched element:
$("#result").find(".dbRows.sixth").each(function(){
console.log($(this).html());
});
From a quick look I can see a few problems. In your php change your first line of code from <div class="dbRows sixth" style="display:none"><ul>'; to $display = '<div class="dbRows sixth" style="display:none"><ul>';
I'd probably change this: var images = $("#result").find(".dbRows.sixth").html(); to this: var images = $("#result > .dbRows.sixth");.
Then add images.show(); and console.log(images.html());. Not tested but might get you on the right track.
I have a search function that calls a php file onkeyup. Now in JQuery i have a onClick function that when you click a div from that same JSON call it alerts something, maybe it will be easier to understand from my code below:
<?php
$Connect = new mysqli("localhost", "root", "", "Data");
$Val = $_POST['Val'];
if($Val)
{
$Search = 'SELECT * FROM Users WHERE ';
$Term = explode(" ", $Val);
foreach($Term as $Key)
{
$I = 0;
$I++;
if($I == 1)
{
$Search .= 'Username LIKE "'.$Key.'%" LIMIT 0, 10 ';
}
else
{
$Search .= 'OR Username LIKE "'.$Key.'%" LIMIT 0, 10 ';
}
}
if($Result = $Connect->query($Search))
{
while($Row = $Result->fetch_assoc())
{
$User = $Row['Username'];
$USearch['S'][] = '<div class="Result"><label class="TText" style="cursor:pointer;">' . $User . '</label></div>';
}
}
}
echo json_encode($USearch);
?>
Now, as you can see, once the user types into a box a div shows up showing all LIKE records of Users, once the div is clicked on nothing happens.
$('.Result').click(function()
{
alert('Hi');
});
When the ajax call return a state of success you can use for example the jquery bind method. (see here for more info http://api.jquery.com/bind/ )
function myAjaxFunct(val){
$.ajax(
{
type: "POST",
url: myPhpFile.php,
datatype: "jsonp",
data: {val: val},
success: function (result) {
$("#jsonResultDisplay").text(result);
$('.Result').bind('click', function() {
alert('hi');
});
}
});
}
You are dynamically creating element that is why it doesn't work.
Use on()method.
Check an example:
http://jsfiddle.net/pZQ8T/
I made an ajax form with json response. The json array contains information out of a mysql database. Now I want to show these datas in a table.
I made a placeholder in the html file which is hidden.
Here my Code for the ajax/json part:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: "include/scripts/select_event.php",
type: "POST",
data: data,
dataType: 'json',
success: function (select) {
//alert(select.ID[0]);
//alert(select.ID[1]);
//alert(select.ID.length);
$("#coffee_talk").fadeOut();
$("#coffee_talk").fadeIn();
}
});
return false;
});
This is my html:
<p class="bold underline headline">Bereits eingetragen:</p>
<form id="coffee_talk_year" action="include/scripts/select_event.php" method="post" accept-charset="utf-8">
<select name="year_coffee_talk" id="year_coffee_talk">
<option value="none" class="bold italic">Jahr</option>
<?php
for($i=2008; $i<=$year; $i++){
if ($i == $year) {
echo "<option value=\"".$i."\" selected=\"$i\">".$i."</option>\n";
} else echo "<option value=\"".$i."\">".$i."</option>\n";
}
?>
</select>
<button id="select_coffee_talk_year">anzeigen</button>
<input type="hidden" name="coffee_talk_year_submit" value="true" />
</form>
<br />
<div id="coffee_talk"></div>
<br />
<button id="add_coffee_talk">hinzufügen</button>
select_event.php:
if ('POST' == $_SERVER['REQUEST_METHOD']) {
/*******************************/
/** Erzaehlcafe auswählen
/*******************************/
if (isset($_POST['coffee_talk_year_submit'])) {
$getID = array();
$getDate = array();
$getTheme = array();
$getContributer = array();
$getBegin = array();
$getPlace = array();
$getEntrance = array();
$getFlyer = array();
$sql = "SELECT
ID,
Date,
Theme,
Contributer,
Begin,
Place,
Entrance,
Flyer
FROM
Coffee_talk
WHERE
YEAR(Date) = '".mysqli_real_escape_string($db, $_POST['year_coffee_talk'])."'
";
if (!$result = $db->query($sql)) {
return $db->error;
}
while ($row = $result->fetch_assoc()) {
$getID[$i] = $row['ID'];
$getDate[$i] = $row['Date'];
$getTheme[$i] = $row['Theme'];
$getContributer[$i] = $row['Contributer'];
$getBegin[$i] = $row['Begin'];
$getPlace[$i] = $row['Place'];
$getEntrance[$i] = $row['Entrance'];
$getFlyer[$i] = $row['Flyer'];
$i++;
}
$result->close();
$response['ID'] = $getID;
$response['Date'] = $getDate;
$response['Theme'] = $getTheme;
$response['Contributer'] = $getContributer;
$response['Begin'] = $getBegin;
$response['Place'] = $getPlace;
$response['Entrance'] = $getEntrance;
$response['Flyer'] = $getFlyer;
echo json_encode($response);
}
}
Div with id=coffee_talk is my placeholder. Now I wish to fade in the table with its data and if I change the year and submit it with the button I wish to fade the old one out and fade new in.
My only problem is that I need to write this table in php with loops. But I think its not possible in Java Script. What should I do?
PS I used ajax cause I dont want to have a reload all the time.
Your quick solution would be:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: "include/scripts/select_event.php",
type: "POST",
data: data,
dataType: 'json',
success: function (select) {
var coffee_talk = $("#coffee_talk");
coffee_talk.fadeOut('fast', function() {
for(i in select) {
row = select[i];
div = coffee_talk.append('<div id="row_'+i+'" />');
for(column in row) {
div.append('<span class="column_'+column+'">'+row[column]+'</span>');
}
}
coffee_talk.fadeIn();
});
}
});
return false;
});
For a nicer approach you should lookup Moustache.js which is a client side JavaScript templating engine (which has equivalents in PHP/Java/Ruby/Python/Go and other languages and is based on Google CTemplates).
It will allow you to create HTML templates and populate them with the data you have in a variable such as the JSON variable an AJAX request might receive.