Three.js : change texture at runtime - javascript

I'm creating an UI in which the user will be able to change the texture of the selected object by clicking on the desired textures picture.
The problem is that I can only use the last texture added in the array.
Here is my php which lists the textures in my specified folder:
<ul id="textureH">
<script type="text/javascript">
texArray = [];
</script>
<?php
for($index=0; $index < $indexCount; $index++) {
$extension = substr($dirArray[$index], -3);
if ($extension == 'jpg'){
$texName = $dirArray[$index];
$texId = "texture". $index;
?>
<script type="text/javascript">
var texName = '<?php echo $texName ?>';
var texId = '<?php echo $texId ?>';
texArray.push(texId);
</script>
<?php
echo "<li id='".$texId."'><table><tr><td><img class='texture-image-list' src='img/" . $texName . "' alt='Image' /></td><td><span id='texture-item-name'>" . $texName . "</span></td></tr></table></li>";
}
}
?>
</ul>
And here's my function:
var uTexture = document.getElementById(texId);
uTexture.addEventListener("click", updateTexture, false);
function updateTexture(){
var texMap = "./img/" + texName;
for (var i in texArray) {
if ((texArray[i] == texId) && (SELECTED instanceof THREE.Mesh)) {
SELECTED.material.map = THREE.ImageUtils.loadTexture(texMap);
SELECTED.material.needsUpdate = true;
}
}
}
I think the problem comes from the array.

Thanks to 2pha I could achieve what I wanted to do.
Here's my new code:
(The php/html)
<div class="right-panel-textures">
<h3 id="cat-hierarchy">Textures</h3>
<?php
$myDirectory = opendir('img/textures');
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
sort($dirArray);
closedir($myDirectory);
$indexCount = count($dirArray);
?>
<ul id="textureH">
<?php
for($index=0; $index < $indexCount; $index++) {
$extension = substr($dirArray[$index], -3);
$texName = $dirArray[$index];
$texId = "texture". $index;
if ($extension == 'jpg'){
?>
<script type="text/javascript">
var texName = '<?php echo $texName ?>';
var texId = '<?php echo $texId ?>';
</script>
<?php
echo "<li class='texture-single-item' data-texture-name='".$texName."' data-texture-id='".$texId."' id='texture-single-item'><table><tr><td><img class='texture-image-list' src='img/textures/" . $texName . "' alt='Image' /></td><td><span id='texture-item-name'>" . $texName . "</span></td></tr></table></li>";
}
}
?>
</ul>
</div>
(And the JavaScript)
var uTexture = document.getElementById("texture-single-item");
uTexture.addEventListener("click", updateTexture, false);
function updateTexture(){
$(".texture-single-item").bind("click", function(event) {
var nameT = $(this).attr("data-texture-name");
if (SELECTED instanceof THREE.Mesh) {
var texMap = "./img/textures/" + nameT;
SELECTED.material.map = THREE.ImageUtils.loadTexture(texMap);
SELECTED.material.needsUpdate = true;
}
});
}
Thank you :)

Related

Call PHP function inside JavaScript inside echo

I have read the other similar questions, but not found the answer, so here it is:
<?php
function load($page) {
echo "page: ".$page;
}
echo "
<script type='text/javascript'>
var page = 0;
window.addEventListener(...., function(){
var x = .....
......
if(x = ....)
{
page = page + 1;
var runQuery = '<?php load(page); ?>'
}
})
</script>
";
?>
The problem is that <?php load(page); ?> is not executed. If I write load(page); outside the echo, it works. Can anyone help me ?
Change the function to return:
function load($page) {
return "page: ".$page;
}
You're executing PHP with the echo so just use the return of load():
echo "
<script type='text/javascript'>
var page = 0;
window.addEventListener(...., function(){
var x = .....
......
if(x = ....)
{
page = page + 1;
var runQuery = '" . load($page) . "'
}
})
</script>
";

How to put validation on a dynamic dropdown when inserting in PHP?

I'm constructing a survey and I have a textbox that generates dynamic dropdowns based on user input which displays the same data.
This is the script
<script>
function load_questions(){
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php??main=1&subcategory="+document.getElementById("subcategorydd").value +"&cnt="+document.getElementById("q_num").value,false);
xmlhttp.send(null);
document.getElementById("question").innerHTML=xmlhttp.responseText;
}
function checkValues() {
_values = [];
$('.form-control-static').each(function() {
_values.push($(this).val());
//console.log($(this).val());
});
sameValue = false;
for ($i = 0; $i < (_values).length; $i++) {
for ($w = 0; $w < (_values).length; $w++) {
if (_values[$i] === _values[$w] && $i != $w) {
sameValue = true;
}
}
}
if (sameValue) {
alert('has the same value .');
return false;
}
alert('there is no the same value');
//do something .
}
</script>
This is the insert code when I'm creating the survey
<?php
$con = mysqli_connect("localhost","root","","imetrics");
if(isset($_POST['submit'])){
$title = $_POST['surveytitle'];
$catdd = $_POST['catdd'];
$subcatdd = $_POST['subcatdd'];
$gender = $_POST['gender'];
$age = $_POST['age'];
$occupation = $_POST['occupation'];
$occupationtwo = $_POST['occupdd'];
$relstatus = $_POST['relationshipstatus'];
$q_num = $_POST['q_num'];
$insert = mysqli_query($con, "INSERT INTO `surveyform` (`surveytitle`,`surveycategory`,`surveysubcategory`,`gender`,`age`,`occupation`,`occupation_status`,`status`) VALUES ('$title','$catdd','$subcatdd','$gender','$age','$occupation','$occupationtwo','$relstatus')");
if(!$insert){
echo mysqli_errno();
}
else{
$getMaxID = mysqli_query($con, "SELECT MAX(survey_id) as maxid FROM surveyform");
$row_2 = mysqli_fetch_array($getMaxID);
$survey_id = $row_2[0];
for( $a = 1; $a <= $q_num; $a++)
{
mysqli_query($con, "INSERT INTO surveyform_questions ( survey_id, question_id) VALUES ('$survey_id', ". $_POST['question_dropdowns'.$a] .")");
//echo "INSERT INTO surveyform_questions ( survey_id, question_id) VALUES ('$survey_id', ". $_POST['question_dropdowns'.$a] .")";
}
echo '<script language="javascript">';
echo 'alert("Survey Created!")';
echo '</script>';
}
}
?>
And this is my dropdown code
if($question !="" && $cnt!="" && $addQues!="yes" && $main != 1){
$i = 0;
for ($i = 1; $i <= $cnt; $i++)
{
$query=mysqli_query($con, "SELECT * FROM question WHERE question_subcat = $question ");
echo "<b>Question #". $i."</b>";
echo "<select id='question_dropdown".$i."' class='form-control-static' name='question_dropdowns".$i."'>";
echo "<option selected>"; echo "Select"; echo "</option>";
while($row=mysqli_fetch_array($query))
{
echo "<option value='$row[question_id]'>";
echo $row["questiontitle"];
echo "</option>";
}
echo "</select>";
echo "<br />";
}
echo "<div id='insertQuesHere".$i."'></div>";
echo "<a href='#add_question' onclick='return addQues();'>Add Question</a>";
}
here's my submit button
<input type="submit" name="" id="btnSaveSurvey" class="form-control-static" onclick="checkValues();" value="check" />
What's the validation code that will prevent me from inserting if the data chosen from the dropdown is the same? For example I generated 2 dropdowns and I chose the same datas from the dropdown, what's the validation code for it?
Please call checkValues method your submit button click
<input type="submit" name="" id="btnSaveSurvey" class="form-control-static" onclick="checkValues();" value="check" />
checkValues method below :
function checkValues() {
_values = [];
$('.form-control-static').each(function() {
_values.push($(this).val());
//console.log($(this).val());
});
sameValue = false;
for ($i = 0; $i < (_values).length; $i++) {
for ($w = 0; $w < (_values).length; $w++) {
if (_values[$i] === _values[$w] && $i != $w) {
sameValue = true;
}
}
}
if (sameValue) {
alert('has the same value .');
return false;
}
alert('there is no the same value');
//do something .
}
Also , you can see an example Example

How to pass a PHP array to another PHP page with ajax

I have been looking for this answer without success.
I have three files: index.php, actions.js and devices.php
My index.php have this code:
<?php
$file = "canvas/interactiveWorkstations/".$roomData['id'].".json";
if(file_exists($file)){
$map = "interactiveWorkstation";
$lines = file($file);
$nPolygon = $lines[count($lines) - 4];
$counterPolygon = 0;
$pos = 4;
$areas = array();
while($counterPolygon !== $nPolygon && $pos < count($lines)){
$lines[$pos] = json_decode($lines[$pos], true);
if($counterPolygon !== 0)
$lines[$pos] = array_diff_assoc($lines[$pos], $lines[$pos-9]);
$coords = "";
foreach($lines[$pos] as $line)
foreach($line as $k => $v)
if($k !== "color" && $v !== -1)
$coords .= $v . ", ";
$coords = trim($coords, ', '); //Delete last space and last comma
$lines[$pos-3] = trim($lines[$pos-3], '#');
$areas[trim($lines[$pos-3])] = $coords;
$counterPolygon++;
$pos = $pos + 9;
}
?>
<script>
var img = document.getElementsByClassName('connection')[0];
img.setAttribute('usemap', '<?php echo "#".$map; ?>');
img.insertAdjacentHTML('afterend', '<map name="<?php echo $map; ?>" id="<?php echo $map; ?>"></map>');
var points = <?php echo json_encode($areas);?>;
</script>
<?php
}
if($bookingActive) {
echo '<script type="text/javascript">reloadDevices("'.$workstationName.'","'.$randomKey.'","'.$bookingData['ical_uid'].'",points); initCountdown('.$remainingTime.');</script>';
}
At this point I have passed my $areas variable to JS using json_encode, and my functions reloadDevices() and UpdateDevices() receive it correctly because I checked before.
In my actions.js file have this code:
function updateDevices(workstation,randomKey,z,points){
var parameters = {
"workstation" : workstation,
"randomKey" : randomKey,
"z" : z,
"points" : points
};
$.ajax({
data: parameters,
url: 'workstation/devices.php',
type: 'post',
success: function (response) {
$("#devices").html(response);
}
});
}
function reloadDevices(workstation,randomKey,z,points) {
updateDevices(workstation,randomKey,z, points);
setInterval(function () { updateDevices(workstation,randomKey,z, points); }, 6000);
}
I do an ajax call to devices.php, but when I wanna get my $_POST['points'] variable is empty.
The part of code from my devices.php where I use this variable:
<?php
$areas = json_decode($_POST['points'], true);
?>
<script>
var map = document.getElementById('interactiveWorkstation');
var area = document.getElementById('<?php echo $deviceName; ?>');
if(!area)
map.insertAdjacentHTML('beforeend', '<area id="<?php echo $deviceName; ?>" shape="polygon" coords="<?php echo $areas[$deviceName]; ?>" href=\'javascript:createTerminal(<?php echo "\"".$deviceName."\""; ?>, <?php echo "\"".$deviceIp; ?>-<?php echo $randomKey."\""; ?>, <?php echo "\"".$uid."\""; ?>, <?php echo "\"".$deviceName."\""; ?>);\'/>');
</script>
Honestly, I can't see the error. If someone helps me appreciate it.
Thanks so much.
Regards.

nested categories dropdown in magento

I have the following working code in magento frontend in a form for customer "add a product" functionality that Im developing:
Helper area:
public function getCategoriesDropdown() {
$categoriesArray = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('name')
->addAttributeToSort('path', 'asc')
->addFieldToFilter('is_active', array('eq'=>'1'))
->load()
->toArray();
foreach ($categoriesArray as $categoryId => $category) {
if (isset($category['name'])) {
$categories[] = array(
'label' => $category['name'],
'level' =>$category['level'],
'value' => $categoryId
);
}
}
return $categories;
}
PHTML File:
<select id="category-changer" name="category-changer" style="width:150px;">
<option value="">--Select Categories--</option>
<?php
$_CategoryHelper = Mage::helper("marketplace")->getCategoriesDropdown();
foreach($_CategoryHelper as $value){
foreach($value as $key => $val){
if($key=='label'){
$catNameIs = $val;
}
if($key=='value'){
$catIdIs = $val;
}
if($key=='level'){
$catLevelIs = $val;
$b ='';
for($i=1;$i<$catLevelIs;$i++){
$b = $b."-";
}
}
}
?>
<option value="<?php echo $catIdIs; ?>"><?php echo $b.$catNameIs ?></option>
<?php
}
?>
</select>
this code generates a dropdown with categories and subcategories. like this one:
my main idea is to create n level nested chained dropdowns for subcategories like this example:
or this layout would be better:
any guidance or code example to modify the proposed php in order to include an ajax call, or javascript to generate those frontend chained frontends will be appreciated
brgds!
Here is my way:
In helper class, add method:
public function getCategoriesDropdown() {
$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('name')
->addAttributeToSort('path', 'asc')
->addFieldToFilter('is_active', array('eq'=>'1'));
$first = array();
$children = array();
foreach ($categories->getItems() as $cat) {
if ($cat->getLevel() == 2) {
$first[$cat->getId()] = $cat;
} else if ($cat->getParentId()) {
$children[$cat->getParentId()][] = $cat->getData();
}
}
return array('first' => $first, 'children' => $children);
}
In PHTML File:
<?php $tree = $this->helper('xxx')->getCategoriesDropdown(); ?>
<script type="text/javascript">
var children = $H(<?php echo json_encode($tree['children']) ?>);
function showCat(obj, level) {
var catId = obj.value;
level += 1;
if ($('cat_container_' + level)) {
$('cat_container_' + level).remove();
}
if (children.get(catId)) {
var options = children.get(catId);
var html = '<select id="cat_' + catId + '" onchange="showCat(this, ' + level + ')">';
for (var i = 0; i < options.length; i++) {
html += '<option value="' + options[i].entity_id + '">' + options[i].name + '</option>';
}
html += '</select>';
html = '<div id="cat_container_' + level + '">' + html + '</div>';
$('sub_cat').insert(html);
}
}
</script>
<select id="first_cat" onchange="showCat(this, 2)">
<?php foreach ($tree['first'] as $cat): ?>
<option value="<?php echo $cat->getId() ?>"><?php echo $cat->getName() ?></option>
<?php endforeach ?>
</select>
<div id="sub_cat"></div>
$rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
/* You can play with this code */
echo '<select>';
echo getChildrenCategoryOptions($rootCategoryId);
echo '</select>';
/* You can play with this code */
function getChildrenCategoryOptions($categoryId) {
$html = '';
$_categoryCollection = Mage::getModel('catalog/category')->load($categoryId)->getChildrenCategories();
if( $_categoryCollection->count() > 0 ) {
foreach($_categoryCollection as $_category) {
$html .= '<option value="'.$_category->getId().'">'.str_repeat("-", ($_category->getLevel() - 2)).$_category->getName().'</option>';
$html .= getChildrenCategoryOptions($_category->getId());
}
return $html;
}
else {
return '';
}
}
$rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
$categoriesHierachy = getChildrenCategoryOptions($rootCategoryId);
function getChildrenCategoryOptions($categoryId) {
$html = '';
$_categoryCollection = Mage::getModel('catalog/category')->load($categoryId)->getChildrenCategories();
if( $_categoryCollection->count() > 0 ) {
foreach($_categoryCollection as $_category) {
$array[$_category->getLevel()][$_category->getId()]['name'] = $_category->getName();
$array[$_category->getLevel()][$_category->getId()]['subcategories'] = getChildrenCategoryOptions($_category->getId());
}
return $array;
}
else {
return array();
}
}

No output from hidden Div with javascript

This is the java script function.I want it to make the div "resultss" visible and show the output.
But it's not displaying results, php code is executed without errors. Whys is this not displaying any output.
I'm trying to append the results at the bottom of same page where user submits some data
<script>
function myFunction()
{
var e = document.getElementById("resultss");
e.style.display = "block";
<?php
$format = $_SESSION["ff"];
$ses_id = $_SESSION["id"];
$filena = $_SESSION["filename"];
//$pubquery = $_SESSION["pubquery"];
$result1 = shell_exec("C:\Python27\python.exe C:\Python27\PredictoR\Model_desc.py $format $ses_id $filena 2>&1");
$properties = explode(" ", $result1);
if($properties[0] == 1)
{
$property = "Substrate";
} else {
$property = "Non-substrate";
}
$molwt = trim(preg_replace('/\s+/', ' ', $properties[1]));
$nhd = trim(preg_replace('/\s+/', ' ', $properties[2]));
$nha = trim(preg_replace('/\s+/', ' ', $properties[3]));
$logp = trim(preg_replace('/\s+/', ' ', $properties[4]));
?>
var molwt = <?php echo json_encode( $molwt); ?>;
var nhd = <?php echo json_encode( $nhd); ?>;
var nha = <?php echo json_encode( $nha); ?>;
var logp = <?php echo json_encode( $logp); ?>;
var property = <?php echo json_encode( $property); ?>;
document.getElementById('properties').innerHTML="Molecule is : "+property+" \n\
<br/>Molecular weight is : "+molwt+" \n\
<br/>No. of hydrogen bond donors = "+nhd+"\n\
<br/>No. of hydrogen bond acceptors = "+nha+"\n\
<br/>Log P : = "+logp+";
}
First of all close the script tag </script>
Secondly I can not see you calling your function myFunction(). Try calling it.
I hope it helps.
So you code should look something like:
<script>
function myFunction()
{
var e = document.getElementById("resultss");
e.style.display = "block";
<?php
$format = $_SESSION["ff"];
$ses_id = $_SESSION["id"];
$filena = $_SESSION["filename"];
//$pubquery = $_SESSION["pubquery"];
$result1 = shell_exec("C:\Python27\python.exe C:\Python27\PredictoR\Model_desc.py $format $ses_id $filena 2>&1");
$properties = explode(" ", $result1);
if ($properties[0] == 1) {
$property = "Substrate";
} else {
$property = "Non-substrate";
}
$molwt = trim(preg_replace('/\s+/', ' ', $properties[1]));
$nhd = trim(preg_replace('/\s+/', ' ', $properties[2]));
$nha = trim(preg_replace('/\s+/', ' ', $properties[3]));
$logp = trim(preg_replace('/\s+/', ' ', $properties[4]));
?>
var molwt = <?php echo json_encode($molwt); ?>;
var nhd = <?php echo json_encode($nhd); ?>;
var nha = <?php echo json_encode($nha); ?>;
var logp = <?php echo json_encode($logp); ?>;
var property = <?php echo json_encode($property); ?>;
document.getElementById('properties').innerHTML = "Molecule is : " + property + " \n\
<br/>Molecular weight is : " + molwt + " \n\
<br/>No. of hydrogen bond donors = " + nhd + "\n\
<br/>No. of hydrogen bond acceptors = " + nha + "\n\
<br/>Log P : = " + logp;
}
myFunction();
</script>

Categories

Resources