How to use javascript and HTML to add a sql and button? - javascript

I have an application where I want to ADD an AND button that, than creates the option to add an AND statement to the query. This is the php and html code I have to do this at the moment. The problem is I don't know how to connect the php part to the javascript part to create a button that adds exacte the same code?
This the html code:
This is the php code:
<?php
include "connect.php";
$table = $_POST['tableSelected'];
$field = $_POST['fieldSelected'];
$attribute = $_POST['attributeSelected'];
$operator = $_POST['operatorSelected'];
$fieldList = $_POST['fieldList'];
if (!empty($table)){
if (!empty($fieldList)){
$fieldstr = $fieldList . ",ST_AsGeoJSON(ST_Transform(l.geom,4326),6)";
} else {
$fieldstr = "";
}
$pairs = [];
foreach ($_POST['fieldSelected'] as $key => $field) {
if (!empty($field) && !empty($_POST['operatorSelected'][$key]) && !empty($_POST['attributeSelected'][$key])) {
$pairs[] = $field . " " . $_POST['operatorSelected'][$key] . " '" . $_POST['attributeSelected'][$key] . "'";
}
}
if (count($pairs) > 0) {
$sql .= ' WHERE ' . implode(' AND ', $pairs);
}
//echo ($sql);
?>
And this my html at the moment:
<select name="field[]">...</select>
<select name="operator[]">...</select>
<select name="value[]">...</select>
This is what I want:

Button click should produce something like it Javascript (jQuery):
newElement = $("#someSelector").clone(false);
// Some modification of new element. Change id for example
$(newElement).attr("id",newIdValue);
newElement.appendTo("#parentElement");

Related

PHP modify fetched variable and return to frontend for JS

Im fetching Product Attributes from Woocommerce, and echo them out in a script tag as variable to use with javascript in frontend.
This might be a bad practice, feel free to enlighten me.
Example:
Product Attributes:
Total height: 43m
Total length: 55m
PHP queries "Total-height" as Attribute Name and "43m" as Attribute Value.
PHP replaces empty space with "-".
I can't define a javascript var with "-" in var name.
Example: var Total-height = "43m";
How could I fix this issue?
Here is my code.
Thanks in advance.
function product_attribute_dimensions(){
global $product;
foreach ($product->get_attributes() as $taxonomy => $attribute_obj ) {
// Get the attribute label
$attribute_label_name = wc_attribute_label($taxonomy);
$value = $product->get_attribute($taxonomy);
if ($value) {
$label = get_taxonomy($taxonomy)->labels->singular_name;
$profile_one = $value;
echo '<script>' . $attribute_label_name . ' = "' . $value . '";
</script>';
}
}
try using window["variable_name"]
do this:
echo '<script>window["' . $attrname . '"]=' . $attrval
then in your js:
let this_var = window[attrname]
It seems like the clearest shortest way to do this.
As I understand the generated string in the variable "$attribute_label_name" is the problem? Take a look at https://www.php.net/manual/de/function.str-replace.php
With this native PHP function you can search for a character (eg."-") and replace with something else (eg. "_")
echo '<script>' . str_replace("-", "_", $attribute_label_name) . ' = "' . $value . '";
But as you said, this might not be the best approach. I personally would add this kind of information into a "data-X" HTML attribute in some HTML element and would extract this in my JS. Similar to this:
<div id="some_element" class="could be hidden" data-total-height="<?= $value ?>"></div>
You could Query something like this with jQuery $("#some_element").attr("data-total-height")
function product_attribute_dimensions() {
global $product;
$product_atrributes = array();
foreach ($product->get_attributes() as $taxonomy => $attribute_obj) {
// Get the attribute label
$attribute_label_name = wc_attribute_label($taxonomy);
$attribute_label_name = str_replace(' ', '_', $attribute_label_name);
$value = $product->get_attribute($taxonomy);
if ($value) {
$product_atrributes[$attribute_label_name] = $value;
}
}
echo '<script type="text/javascript">var product_atrributes = ' . json_encode($product_atrributes) . ';</script>';
}
Now you can use in JS like product_atrributes.Total_height.value
This way the redundant script tag also can be avoided.

I'm trying to use some data i pulled from a php database as information in a clickable SVG picture (javascript)

<?php
require_once('dbconn.php');
$arm = "SELECT problem, description, reason, reg_date FROM body_arm";
$result = $conn->query($arm);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo " " . $row["problem"].
" - " . $row["description"].
" - reason: " . $row["reason"].
" - TIMESTAMP:" . $row["reg_date"].
"<br/>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<!--
Here I have some code for the SVG
-->
<script>
window.onload = function () {
const pieces = document.getElementsByTagName('svg');
for (var i = 0; pieces.length; i++) {
let _piece = pieces[i];
_piece.onclick = function(t) {
if (t.target.getAttribute('data-position') != null)
document.getElementById('data').innerHTML = t.target.getAttribute('data-position');
if (t.target.parentElement.getAttribute('data-position') != null)
document.getElementById('data').innerHTML = t.target.parentElement.getAttribute('data-position');
}
}
}
</script>
I have tried to use the function ob_get_contents, couldn't really get it working.
I have tried to echo the php variable to javascript like: var val = "";
As I'm starting to understand I can't really find the php variable in javascript and need to find a way around that or maybe use something like node.js to open a connection to the server with something closer to javascript? I'm a beginner by the way!
For me the solution I found was json_encode!
$example_array_variable = json_encode($example);
//Doing this in the PHP.
//Then later in the JavaScript decode it.
echo json_encode($example_array_variable);
Eureka!!

how to generate this code mysql_fetch_array in codeigniter

how do I write mysql_fetch_array code in codeigniter
<?php
$result = mysql_query("select * from tb_mhs");
$jsArray = "var dtMhs = new Array();\n";
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['nim'] . '">' . $row['nim'] . '</option>';
$jsArray .= "dtMhs['" . $row['nim'] . "'] = {nama:'" . addslashes($row['nama']) .
"',jrsn:'".addslashes($row['jurusan'])."'};\n";
}
?>
Form Input :
<td><input type="text" name="nm" id="nm"/></td>
<td><input type="text" name="jrsn" id="jrsn"/></td>
Javascript :
<script type="text/javascript">
<?php echo $jsArray; ?>
function changeValue(nim) {
document.getElementById('nm').value = dtMhs[nim].nama;
document.getElementById('jrsn').value = dtMhs[nim].jrsn;
};
</script>
If you want to return result as a array from the database, you can use something like this
// in application/config/autoload.php, make database available globally
$autoload['libraries'] = array('database');
// fetch the results from the database
$query = $this->db->get('tb_mhs'); // produces select * from tb_mhs
// get the result as a array
$result = $query->result_array();
// to do the other operations you were doing you can use a loop
foreach ($result as $key => $item) {
// do stuff
}

Alert box not showing when action from php js php

I have a problem in showing the alert box. This code for the rating star.
rating.js
$(document).ready(function(){
$('.post li').mouseout(function(){
$(this).siblings().andSelf().removeClass('selected highlight')
}).mouseover(function(){
$(this).siblings().andSelf().removeClass('selected');
$(this).prevAll().andSelf().addClass('highlight');
})
$('.post li').click(function(){
$(this).prevAll().andSelf().addClass('selected');
var parent = $(this).parent();
var oldrate = $('li.selected:last', parent).index();
parent.data('rating',(oldrate+1))
data = new Object();
data.id = parent.data('id');
data.rating = parent.data('rating')
$.ajax({
url: "add_rating.php",// path of the file
data: data,
type: "POST",
success: function(data) {
}
});
})
/* reset rating */
jQuery('.post ul').mouseout(function(){
var rating = $(this).data('rating');
if( rating > 0) {
$('li:lt('+rating+')',this).addClass('selected');
}
})
})
add_rating.php
<?php
include("dbconnection.php");
session_start();
$myid = $_SESSION['id'];
// echo "".$myid;
$sql_notification ="SELECT * FROM table_user_skills where user_id='$myid' and rating=5";
$result = $conn->query($sql_notification);
$count = 0;
while ($row=$result->fetch_assoc()) {
if ($row['rating']==5) {
$count = $count +1;
}
}
// echo "Count: ".$count;
if(!empty($_POST["rating"]) && !empty($_POST["id"])) {
$myrate=$_POST["rating"];
if($count<5){
$query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' where rating_id='".$_POST['id']."'";
$result = $conn->query($query);
print '<script type="text/javascript">';
print 'alert("Less than 5");';
print '</script>';
} else if($myrate<5){
$query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' where rating_id='".$_POST['id']."'";
$result = $conn->query($query);
print '<script type="text/javascript">';
print 'alert("Rate Less than 5");';
print '</script>';
}else if($count>5){
print '<script type="text/javascript">';
print 'alert("Lpas 5 stars");';
print '</script>';
}
// $query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' WHERE skills_id='" . $_POST["skills_id"] . "'";
// $query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' WHERE user_id='" . $_POST["userid"] . "' and skills_id='" . $_POST["id"] . "' and category_id='" . $_POST["category"] . "'";
}
?>
My problem is that the alert box is not showing. I have to limit the number of 5 stars being updated. If anyone could help me figure out what's wrong with my code, I would appreciate it.
Look at the success callback function for your AJAX call - it's empty. You're having PHP print out the alert box code in the ajax call and then never doing anything with that output.
To make the alert show up, you would have to append the code your AJAX call returns to the DOM. However, it would probably be better to just return just the message and let the JavaScript code take care of raising the alert box. Just a simple alert(data) should do the trick.

JS - constructingan array - SyntaxError: missing ] after element list

I'm trying to make autocomplete on a research of elements from my Database (wich is on SQL Server).
Here is my PHP request :
public function getNomProduitsAutocomplete() {
$q = ' SELECT NomProduit
FROM Produit
WHERE NomProduit LIKE \'a%\' OR NomProduit LIKE \'b%\'
ORDER BY NomProduit';
$qResults = $this->fetchAll($q);
$numItems = count($qResults);
$i = 0;
//var_dump($numItems);
$result = '[ ';
foreach($qResults as $res){
if(++$i === $numItems) {
$result .= '"' .$res['NomProduit'] . '"' ;
}
else {
$result .= '"' .$res['NomProduit'] . '", ';
}
}
$result .= ' ]';
return $result;
}
And the auto complete in js here :
$(function () {
<?php
$p = new Produit();
$produits = $p->getNomProduitsAutocomplete();
//var_dump($produits);
?>
var availableTags2 = <?php echo ($produits); ?>;
$( "#tags" ).autocomplete({
source: availableTags2
});
});
and finaly the input for the auto complete :
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
All of this works fine, but ONLY when I have, less than 1 000 elements in the array, it seems.
It actually works with 700 elements (" WHERE NomProduit LIKE \'a%\' OR NomProduit LIKE \'b%\' " as you see), and I would like to get ALL the elements (+/- 4 800 elements) if possible, not only 700...
If you have any ideas... :)
Thanks.
Why are you not using josn_encode function in your getNomProduitsAutocomplete function?
You are manually creating the javascript array in PHP, instead collect all your $res['NomProduit'] in an array say $js_array and then use return json_encode($js_array)

Categories