Currently I am learning Php. For an Ebay shop I try to get my page free of JS and to switch to pure CSS via PHP.
For this I have so far a backend, into which I enter my links and texts. These are stored in my menu.js.
$remote_directory = UPLOAD_PATH;
$renaming_file = $remote_directory . '/js/menu.js';
$renaming_file_to = $remote_directory . '/js/menu.old';
$_remc = new Admin_Remote_Copy(ADMIN_UPLOAD_SERVER_HOST, ADMIN_UPLOAD_USER_NAME, ADMIN_UPLOAD_PASSWORD, ADMIN_UPLOAD_SSH_PORT);
$_remc->remote_copy($renaming_file, $renaming_file_to);
if ($_remc->remote_is_writeable($renaming_file)) {
$menu_string = "document.getElementById('categories_menu').innerHTML='";
for ($z = 0; $z < count($_POST['menu_lvl1_text']); $z++) {
$menu_string .= '<li>' . htmlentities($_POST['menu_lvl1_text'][$z], ENT_QUOTES, "UTF-8") . '';
if (isset($_POST['menu' . $z . '_lvl2_text']) && !empty($_POST['menu' . $z . '_lvl2_text'])) {
$menu_string .= '<ul>';
for ($zs = 0; $zs < count($_POST['menu' . $z . '_lvl2_text']); $zs++) {
$menu_string .= '<li>' . htmlentities($_POST['menu' . $z . '_lvl2_text'][$zs], ENT_QUOTES, "UTF-8") . '';
}
$menu_string .= '</ul>';
}
$menu_string .= '</li>';
}
$menu_string .= "';";
$_remc->remote_content_copy($renaming_file, $menu_string);
$local_renaming_file = ADMIN_LOCAL_PATH . '/js/menu.js';
$_remc->local_content_copy($local_renaming_file, $menu_string);
} else {
$file_error = true;
}
Now I had thought to pass these values into an array and save it via JSON PrittyPrint. However, I have no idea at all how to build this array.
My idea is to build a navigation with fixed IDs and fill it with the JSON file.
In the latter I see no problems, but the array is not clear to me.
Let's assume that array would look something like this:
$m =array(
"10100" => array('menu_lvl1_text' => 'menu_lvl1_link'),
"10101" => array('menu_lvl2_text' => 'menu_lvl2_link'),
"10102" => array('menu_lvl2_text' => 'menu_lvl2_link'),
"10103" => array('menu_lvl2_text' => 'menu_lvl2_link')
);
Am I on the wrong path?
And how does my array know that it is to assign value 1 to ID 10000?
Thanks,
Patrick
I think that you forgot to open a folder first! You can use some php functions like opendir at first then get or create a new file there.
Related
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 get this error when I refresh the page:
Uncaught TypeError: listaDeAutos.autos.foreach is not a function
I built the data here, which iterates and gets the data from the database and stores it in "salidaJson":
<?php
$salidaJson = '{"autos": [';
while ($row = $result->fetch_assoc()) {
$salidaJson = $salidaJson. '{';
$salidaJson = $salidaJson. '"idAuto":"' . $row['idAuto'] . '",';
$salidaJson = $salidaJson. '"Marca":"' . $row['Marca'] . '",';
$salidaJson = $salidaJson. '"Modelo":"' . $row['Modelo'] . '",';
$salidaJson = $salidaJson. '"idTipoDeVehiculo":"' . $row['idTipoDeVehiculo'] . '",';
$salidaJson = $salidaJson. '"FechaDeLanzamiento":"' . $row['FechaDeLanzamiento'] . '"';
$salidaJson = $salidaJson. '},';
}
$salidaJson = $salidaJson. '{"idAuto":"FIN", "Marca":"FIN","Modelo":"FIN","idTipoDeVehiculo":"FIN","FechaDeLanzamiento":"FIN"}';
$salidaJson = $salidaJson . ']}';
?>
Now this is the Javascript with the function that I'm trying to make, the objective is pretty simple, build a table with the data from the collection, I half wrote the table-building, but wanted to see if it was working at least the first part and I got the error:
<script>
var miTabla = $("#tableBody");
var listaDeAutos = <?php echo $salidaJson ?>;
console.log(listaDeAutos);
function cargaTabla() {
listaDeAutos.autos.foreach(function() {
var html = '<tr><td>'+ idAuto + '</td><td>' + Marca + '</td><td>'+ Modelo + '</td></tr>';
miTabla.append(html);
})
}
From what I understand forEach is used on Arrays but my data is an object because it contains "autos" that contains the arrays but I don't know how to make that function work with my object.
This is the data more clearly seen:
console.log output
Not sure where you got your foreach formatting there, but this should be the correct syntax
$.each(listaDeAutos.autos, function(i, item) {
var html = '<tr><td>'+ item.idAuto + '</td><td>' + item.Marca + '</td><td>'+ item.Modelo + '</td></tr>';
miTabla.append(html);
});
or using the forEach syntax if you prefer
(FWIW it's slightly slower)
listaDeAutos.autos.forEach(function(e, i) {
var html = '<tr><td>'+ e.idAuto + '</td><td>' + e.Marca + '</td><td>'+ e.Modelo + '</td></tr>';
miTabla.append(html);
});
This is based on this Plunker
While you're at it, you can use .= in PHP to clean up your code a bit.
$salidaJson .= '{';
...
First of all, the way you create the JSON is not elegant and kinda difficult to create with all these quotes and everything. You better create a PHP array and then json_encode that array.
$res = array("autos" => array());
while ($row = $result->fetch_assoc())
{
$res['autos'][] = array("idAuto" => $row['idAuto'],
"Marca" => $row['Marca'],
"Modelo" => $row['Modelo'],
"idTipoDeVehiculo" => $row['idTipoDeVehiculo'],
"FechaDeLanzamiento" => $row['FechaDeLanzamiento']);
}
$res['autos'][] = array("idAuto" => "FIN",
"Marca" => "FIN",
"Modelo" => "FIN",
"idTipoDeVehiculo" => "FIN",
"FechaDeLanzamiento" => "FIN");
$res = json_encode($res);
Secondly, in your JS script, you need to parse that variable listaDeAutos and then you can iterate through autos as mentioned by adriani6
var listaDeAutos = JSON.parse(<?php echo $res ?>);
Secondly, you don't need to parse it as you inject a JSON object already by <?php echo $res ?>. This was edited after nico-westerdale comment on this answer.
Thirdly, be careful with the camel case forEach as #JaromandaX pointed out. There is no foreach in JS.
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");
I am very new to AngularJS and started to rebuild a restaurant finder app i have previously written in pure PHP. However i would now like to achieve faster database access and asynchronous sorting, hence the desire to learn AngularJS.
I have not used JSON for a while and i am literally stuck with getting basic queries back to AngularJS. Otherwise the syntax is correct but i am unable to get additional data from another table.
So first the basic controller to fetch the data from a PHP file:
var app = angular.module('Dinneri', []);
app.controller('showContent', function($scope, $http) {
$http.get("server/showcontent.php")
.success(function (response) {$scope.restaurants = response.records;});
});
And then we have the showcontent.php file to perform the queries and return the data in JSON.
To clarify: The SQL table populated with restaurants is restaurants and the entries are populated with hashjoins that include a reference to the restaurant and the hashtag associated. The hashtag table includes the actual hashtags. Any tips on shortening the SQL in this conjunction would also be welcomed.
<?php
// Set JSON for Angular
header("Content-Type: application/json; charset=UTF-8");
// Include DB credentials
include('db_con.php');
// Get Restaurants
$result = $mysqli->query("SELECT * FROM `restaurant`");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
// Add restaurant to array
$outp .= '{"ID":"' . $rs["restaurant_id"] . '",';
$outp .= '"Name":"' . $rs["restaurant_title"] . '",';
$outp .= '"Description":"' . $rs["restaurant_description"] . '",';
$outp .= '"Address":"' . $rs["restaurant_address"] . '",';
$outp .= '"LocLat":"' . $rs["restaurant_loc_lat"] . '",';
$outp .= '"LocLong":"' . $rs["restaurant_loc_long"] . '",';
$outp .= '"Added":"' . $rs["restaurant_added"] . '",';
// Get current while loop restaurant
$restaurant = $rs["restaurant_id"];
// Get joined hashtags
$result_hash = $mysqli->query("SELECT * FROM `hash_join` WHERE `restaurant_hash` = $restaurant");
while($hashjoin = $result_hash->fetch_row())
{
$hashtag_id = $hashjoin[1];
// Get hashtag information
$hashtags = $mysqli->query("SELECT * FROM `hashtags` WHERE `hashtag_id` = $hashtag_id ORDER BY `restaurant_type` DESC");
while($hash = $hashtags->fetch_row())
{
// Add hashtags to array
$outp .= '"HashtagID":"' . $hash[0] . '",';
$outp .= '"HashtagName":"' . $hash[1] . '",';
$outp .= '"HashtagType":"' . $hash[2] . '"}';
}
}
}
// Finalize output array
$outp ='{"records":['.$outp.']}';
// Deliver output array
echo($outp);
// Close mysqli
$mysqli->close();
?>
The first set of results are returned to Angular like expected and all code works until i try to output the "Hashtags". The PHP page "showcontent.php" outputs the JSON code as expected but for some reason the Angular controller is being picky about the hashtags.
Deleting this section of the code where the hashtags are outputted makes everything work like a charm, but without the desired output.
Thank you in advance <3
I am attempting to use JSONP to return an array from PHP to JavaScript. Hopefully, my code will demonstrate exactly what I'm trying to do because I am not even so sure how to word it...
My PHP file, port 80, hence the need to use JSONP and not JSON (I tried already)
I am not sure if I am forming the $_GET variables correctly either, I'm pretty certain it's wrong though and my lack of knowledge is the reason for this...
<?php
$directory = './thumbnails/';
// create a handler to the directory
$dirhandler = opendir($directory);
// read all the files from directory
$nofiles=0;
while (false !== ($file = readdir($dirhandler))) {
// if $file isn't this directory or its parent
//add to the $files array
if ($file != '.' && $file != '..')
{
$thumbs[$nofiles]= 'http://localhost:80/mapScripts/thumbnails/' . $file;
$nofiles++;
}
}
//$i = rand(0, 3);
//$output = "{";
for($i=0; $i < 3; $i++){
$json[i] = json_encode($thumbs[$i]);
$output = $output . $_GET['thumbnails' . $i]. "(".$json[i].")";
//$output = $output . "'thumb" . $i . "':'" . $thumbs[$i] . "',";
}
//$output = $output . "}";
//echo $_GET['thumbnails'] ."(".$json.")";
echo $output;
?>
Then in JavaScript on port 8080 (cross-domain and yes it worked fine until I tried to use this array as opposed to just passing one image url) I want to get each image url from the PHP array so that I can make icons using the image..
function makeThumbs(data, layer){
var icon = new OpenLayers.Icon(data);
layer.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(93.9, 29.53).transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")),icon));
for(var m = 0; m < layer.markers.length; m++){
layer.markers[m].events.register("click", layer.markers[m], function clickIcon(e){alert("How are you?");});
$("[id$=innerImage]").css({"border-style":"solid","border-width":"3px","border-color": "white"});
}
}
$.getJSON('http://localhost:80/mapScripts/getThumbs.php?thumbnails2=?', function(data) {makeThumbs(data, markers);});
again the url I am passing to the $.getJSON method is also probably wrong. I need to know how to select the exact photo url from the array being passed, not all the JSONP data.
I appreciate your time and feedback for helping me with this.
elshae
I actually found one way of doing it..Here goes..
<?php
$directory = './thumbnails/';
// create a handler to the directory
$dirhandler = opendir($directory);
// read all the files from directory
$nofiles=0;
while (false !== ($file = readdir($dirhandler))) {
// if $file isn't this directory or its parent
//add to the $files array
if ($file != '.' && $file != '..')
{
$thumbs[$nofiles]= 'http://localhost:80/mapScripts/thumbnails/' . $file;
$nofiles++;
}
}
//$i = rand(0, 3);
$output = $_GET['thumbnails'] . "({";
for($i=0; $i < 3; $i++){
//$json[i] = json_encode($thumbs[$i]);
//$output = $output . $_GET['thumbnails' . $i]. "(".$json[i].")";
$output = $output . "'thumb" . $i . "':'" . $thumbs[$i] . "',";
}
$output = $output . "})";
//echo $_GET['thumbnails'] ."(".$json.")";
echo $output;
?>
That outputs:
({'thumb0':'http://localhost:80/mapScripts/thumbnails/Tibet2.jpeg','thumb1':'http://localhost:80/mapScripts/thumbnails/lhasa.jpeg','thumb2':'http://localhost:80/mapScripts/thumbnails/Tibet.jpg',})
Then in JavaScript I just:
function makeThumbs(data, layer){
alert("already Here "+ data);
var icon = new OpenLayers.Icon(data);
alert(icon.url);
layer.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(93.9, 29.53).transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")),icon));
for(var m = 0; m < layer.markers.length; m++){
layer.markers[m].events.register("click", layer.markers[m], function clickIcon(e){alert("How are you?");});
$("[id$=innerImage]").css({"border-style":"solid","border-width":"3px","border-color": "white"});
}
}
$.getJSON('http://localhost:80/mapScripts/getThumbs.php?thumbnails=?', function(data) {makeThumbs(data.thumb2, markers);});
So it seems after the $_GET variable you can put typical JSON data and fetch it as you normally would (notice the data.thumb2 in the JavaScript).