Passing a variable from PHP-generated list to jQuery - php

I have a PHP-generated list:
<?php $row_number = 0;
while ($row = $result->fetch_object()) {
$row_number++;
$movie_id = $row->movie_id;
$title = $row->title;
if ($num_rows>0){ ?>
<p class='dragelement' id="<?php echo $movie_id; ?>">
<?php echo $title; ?>
</p>
<?php }
} ?>
and am trying to pass the variable 'movie_id' to jQuery for a drag-and-drop function using the id of the parent p selector:
var parent = $("p.dragelement").closest('p');
var movie_id = parent.attr('id');
The problem is that the resulting value of 'movie_id' is the first one of the list, not the current one.
Any ideas much appreciated!

How about last selector?
http://api.jquery.com/last-selector/
var parent = $(".dragelement:last");
var movie_id = parent.attr('id');

Related

PHP array foreach while loop

I am trying to create javascript variable from php, this is what i want to get.
<?PHP echo "var color_name=[<?PHP echo $color_name;?>]"; //var color_name=["Green","Pink"];
<?PHP echo "var style_name=[<?PHP echo $style_name;?>]"; //var style_name=["Basic","Classic"];
this is my predefined_attributes table
this is what i have tried,
<?php
$predifined_qry = "SELECT attribute_column_name
FROM predefined_attributes
WHERE category_id=$id";
$predifined_result = mysqli_query($predifined_qry);
$columnNames = Array();
while ($predifined_result_row = mysqli_fetch_assoc($predifined_result)) {
$columnNames[] = $predifined_result_row['attribute_column_name'];
}
now i can get the attribute_column_name in an array using a foreach loop, but i dont know how to get the attribute_column_value array in a variable like this $style_name, $color_name. please help.
First of all, if you only need 1 column, and the resource/data you get is not massive, you could just fetch all and extract the column
You could expose your php variables in js through JSON
<?php
$predifined_result = mysqli_query($predifined_qry);
$predifined_rows = mysqli_fetch_all($predifined_result, MYSQLI_ASSOC);
$columnNames = array_column($predifined_rows, 'attribute_column_name');
?>
<script>
var columnames = JSON.parse("<?= json_encode($columnNames); ?>");
</script>
So now if we add in the other field :
<?php
$predifined_result = mysqli_query($predifined_qry);
$predifined_rows = mysqli_fetch_all($predifined_result, MYSQLI_ASSOC);
$columnNames = array_column($predifined_rows, 'attribute_column_name');
$columnValues = array_column($predifined_rows, 'attribute_column_value');
// array_combines uses the first array as the key and the second as the value
$columns = array_combine($columnNames, $columnValues);
?>
<script>
var columns = JSON.parse("<?= json_encode($columns); ?>");
</script>
Edit
as in the comments, a key can only appear once in a hashtable/array
so we need to generate an array of values per key
<?php
$predifined_qry = "SELECT attribute_column_name, attribute_column_value
FROM predefined_attributes
WHERE category_id=$id";
$predifined_result = mysqli_query($predifined_qry);
$columns = [];
while($row = mysqli_fetch_assoc($predifined_result)) {
if(!array_key_exists($row['attribute_column_name'], $columns)) {
$columns[$row['attribute_column_name']] = [];
}
$columns[$row['attribute_column_name']][] = $row['attribute_column_value'];
}
?>
<script>
var columns = JSON.parse("<?= json_encode($columns); ?>");
</script>
1st : You need to select attribute_column_value column too
SELECT attribute_column_name,attribute_column_value FROM predefined_attributes where category_id=$id
2nd : You need push both column value in two different array like this
while ( $predifined_result_row = mysqli_fetch_assoc($predifined_result) ) {
$color_name[] = $predifined_result_row['attribute_column_name'];
$style_name[] = $predifined_result_row['attribute_column_value'];
}
3rd : simple apply json_enocde and echo like this
<script>
var color_name=<?php echo json_encode($color_name); ?>;
var style_name=<?php echo json_encode($style_name); ?>;
</script>
$columnValues[] = $predifined_result_row['attribute_column_value'];
You can paste this code into your while loop
And dont't forget to get the need field form database:
$predifined_qry="SELECT attribute_column_name,attribute_column_value FROM predefined_attributes where category_id=$id";

How to get list of current wordpress categories and inject each in script

I'm trying to create php code that will get the list of categories that are assigned to a wordpress post (of the current page) and then loop through the array list and each category that IS has been assigned to the post and add it to the script.
this is the script i need to inject the category name in:
<script> window.abkw = '<category name>';</script>
so i wrote this but it does not seem to work...
<?php
$ads = the_category();
for ($i = 0; $i < count($ads); ++$i) {
$d = $ads[$i];
<script> window.abkw = $d[$i];</script>
}
?>here
I'm new to php so please excuse my ignorance... and thank you so much.!
use get_categories() (https://developer.wordpress.org/reference/functions/get_categories/)
$categories = get_categories(array('hide_empty' => 0'));
foreach($categories as $category) {
echo '<script> window.abkw = '.$category->cat_name.';</script> ';
}
What if you use jquery data()...
https://api.jquery.com/data/#data-html5
--edited--
I expand the way
template-example.php
...
<?php
$categories = get_categories(array('hide_empty' => 0'));
foreach($categories as $category): ?>
<div class="js-category" style="visibility:hidden;" data-category = "<?php echo $category->cat_name ?>"></div> //invisible div
<?php endforeach; ?>
...
file.js
var categories = $(".js-category").data("category");
...

change div containing checkbox attributes when checked

this is my javascript that allows for a filter search field ...
function escape4regex(text)
{
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
function searchRegExFieldKeyUp()
{
var table = document.getElementById('ModelFilter');
var cells = table.getElementsByTagName('div');
var searchterms = escape4regex(this.value);
var regVar = '(?=.*' + searchterms.replace(/\s/g, '.*)(?=.*') + '.*)';
var i=cells.length;
while (i--)
{
var cell = cells[i];
var rowStr = cell.innerHTML;
// remove all tags
rowStr = rowStr.replace(/<(?:.|\n)*?>/gm, '').replace(/\n|\s{2,}/gm, ' '); // searches whole row
var regex = new RegExp(regVar,"gi");
var result = (regex.test(rowStr));
if(result)
{
cell.style.display = "";// check if compat with IE
}
else
{
cell.style.display = "none";
}
}
}
this creates checkboxes from databse inputs
<div id="ModelFilter">
<?php
while ($row = mysqli_fetch_assoc($result))
{
echo"<div class=\"modelfilter_td\" id=\"modelfilter_td\">";
echo"<input type=\"checkbox\" id = \"$row[ModelID]\"
name = \"selectedModels[]\"value =\"$row[Model]\" onclick=\"chkcontrol.apply(this);\">";
echo "$row[Model]";
echo"</div>";
}
echo"</div>";
I want to do the following :
when the checkbox is checked, it stays visible, even if it is not in the search terms of the filter field.
when the checkbox is checked , the background color is changed.
the checkbox and the title for the checkbox is held within a div, I want to allow the user to click anywhere in the div to allow toggling of the checkbox.
Anyone start me ont the right track with this?
EDIT: here is a solution to problem "3."
<script language="javascript">
$(document).ready(function(){
$(".modelfilter_td").click(function(e){
var chk = $($(this).find("input[type='checkbox']"));
if(chk.attr('checked'))
{
chk.attr('checked',false);
}else{
chk.attr('checked',true);
}
});
});
This is not a solution for you problem, but a recommendation on php-usage in html context:
<div id="ModelFilter">
<?php while ($row = mysqli_fetch_assoc($result)): ?>
<div class="modelfilter_td" id="modelfilter_td">
<input
type="checkbox"
id="<?php echo $row['ModelID'] ?>"
name="selectedModels[]"
value="<?php echo $row['Model'] ?>"
onclick="chkcontrol.apply(this);"
>
<?php echo $row['Model'] ?>
</div>
<?php endwhile ?>
</div>
This enables most IDEs to deal with HTML-autocompletion and code-analysis.

Dynamically add options to a list through a hidden iframe

I want to dynamically add options to a list through a hidden iframe; I suspect my mistake is in the PHP below:
<?php echo 'var oInner = document.createTextNode("'.$donnees["name"].'");'; ?>
because my code works perfectly with:
<?php echo 'var oInner = document.createTextNode("Newoption");'; ?>
I don't know why createtextnode doesn't want to take my PHP var... I thought it could be a same origin policy since the database is located on a server outside my website.
I don't know.
You'll find enclosed the complete code:
In my HTML I have:
//select or change a country will trigger the javascript part
<select name="countrym" id="countrym" onchange="validcountry();">
<option value"France">France</option>
</select>
//Empty region list
<select name="regionm" id="regionm">
</select>
//My Iframe
<iframe name="upload_iframe2" id="upload_iframe2" frameborder="0"></iframe>
In my Javascript I have:
//My function triggering the PHP through the Iframe
function validcountry() {
var countrym = document.getElementById('countrym');
var choixco = countrym.options[countrym.selectedIndex].value;
document.getElementById('upload_iframe2').src = 'region.php?choix='+choixco;
In my PHP region.php file, I have:
<?php
// Get my choice
$codepays = $_GET['choix'];
//Retrieve the regions corresponding to the country
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO(XXX);
$req = $bdd->prepare('SELECT name FROM regions WHERE country = :country');
$req->execute(array('country' => $codepays));
$donnees = $req->fetch();
while($donnees)
{
// I checked the format of the data (no problem so far)
echo var_dump ($donnees['name']);
?>
//I add an option through Javascript
<script language="JavaScript" type="text/javascript">
var oOption = document.createElement("option");
//Here is my big issue:
<?php echo 'var oInner = document.createTextNode("'.$donnees["name"].'");'; ?>
oOption.value = "none";
oOption.appendChild(oInner);
var parDoc = window.parent.document;
var regionm = parDoc.getElementById("regionm");
regionm.appendChild(oOption);
</script>
<?php
$donnees = $req->fetch();
}
$req->closeCursor();
exit();
?>
Have you tried simply oOption.innerHTML = '<?php echo $donnees["name"] ?>'; ?
I am suspecting that the indexed element cannot be found. But is all cases, this below should work.
<?php echo 'var oInner = document.createTextNode("'. (isset($donnees["name"]) ? $donnees["name"] : '') .'");'; ?>
Found the solution: it was the php inserting \n so the solution is to do the following:
$desc= 'var oInner = document.createTextNode("'.$donnees["name"].'");';
$desc= str_replace("\n", "",$desc);
$desc= str_replace("\r", "",$desc);
Thanks everybody

Using jQuery to load a PHP Page in a div

I have this script:
<script type='text/javascript' src='js/jquery-1.4.4.mi.js'></script>
<script type='text/javascript'>
$('.filterMonth').change(function(){
alert('ijijiji');
$.ajax({
url: 'ajax/filterMandays.php',
//type: 'GET',
success: function(data){
//data is returned back
$('#mandayTable').html(data);
}
});
});
</script>
and this html:
<select name ="filterMonth">
<?php
$array_month = array("January","February","March","April","May","June","July","August","September","October","November","December");
foreach($array_month as $key => $month)
{
$value_month = $key+1;
echo "<option value = '$value_month'>$month</option>";
}
?>
</select>
-
<select name = "filterYear" onChange = "filter(filterMonth.value, filterYear.value)">
<?php
$curYear = date('Y');
for($i = 1990; $i<=$curYear+10; $i++)
{
if($i == $curYear)
{
echo "<option value = '$i' selected = 'selected'>$i</option>";
}
else
{
echo "<option value = '$i'>$i</option>";
}
}
?>
</select>
</td>
</tr>
</br>
</br>
<tr>
<div id="mandayTable"></div>
and this php page:
<?php
include("all.php");
$q = "SELECT md.mandays_id,md.employeenum,md.month,md.year,md.required_man_days,d.firstname,d.lastname
FROM tbl_mandays md,tbl_employee_details d
WHERE md.active = '1'
AND md.employeenum = d.employeenum
AND md.month = '10';";
$res = $db->Execute($q);
echo "<table border = 1>";
echo "<tr><th>Employee Number</th><th>First Name</th><th>Last Name</th><th>Month-Year</th><th>Required Man Days</th><th>Edit/Delete</th></tr>";
while($rows = $res->FetchRow())
//for($i=0;$i<5;$i++)
{
//iterating through // check if employee
// // if(isset($row[])) { }
$mandays_id = $rows[0];
$empnum = $rows[1];
$month_year = $rows[2] ."-" .$rows[3];
$required_man_days = $rows[4];
$firstname = $rows['month'];
$lastname = $rows[6];
//echo approvers here are not taken
//<a href=\"view_team.php?id=".$empnum."\" -> for someone to view the people beneath them (like org tree)
echo "<tr><td>".$empnum . "</td><td>".$firstname ."</td><td>".$lastname ."</td><td>" . $month_year ."</td><td>" .$required_man_days . "</td><td width = \"200\" align = \"center\"><a href = 'edit_mandays.php?mandays_id=$mandays_id');'>Edit/Delete</a></td></tr>";
}
echo "</table>";
?>
the script should basically load the php page in the div in the html once the "filterMonth" has been changed. but it doesn't work.
what seems to be the problem? :(
The selector in your jQuery is $('.filterMonth') but your select box doesn't have the filterMonth class. You need to change it to $('select[name=filterMonth]').
In order for the jQuery selector to contain your select, you need to make sure that it runs after the Select element is in the DOM (ie: lower down the HTML), or run your JavaScript once the document has finished loading, for example:
<script type='text/javascript' src='js/jquery-1.4.4.mi.js'></script>
<script type='text/javascript'>
jQuery(function() {
// do your DOM selections here, this function only runs once the document is loaded
});
</script>

Categories