I am creating tag's input where somebody can write tag. In both languages of course. But the problem is that I can't translate them. I do not know how to do it. Can you help me? Here's my code:
JS:
suggestion: function(data) {
return '<li class="list-group-item">' + "#lang('" + "main." + data.name + "')" + '</li>'
}
Route:
Route::group(['prefix'=>'api','middleware' => 'auth'], function(){
Route::get('find', function(Illuminate\Http\Request $request){
$keyword = $request->input('keyword');
Log::info($keyword);
$positions = DB::table('positions')->where('name','like','%'.$keyword.'%')
->select('positions.id','positions.name','positions.display')
->get();
return json_encode($positions);
})->name('api.positions');
});
The easiest way to do that is by having multiple column in your datase :
• name_en
• name_fr
• name_es
and then
check your targeted local :
$local = 'en';
$positions = DB::table('positions')->where('name_'.
$local,'like','%'.$keyword.'%')
->select('positions.id','positions.name_' . $local .' as
name' ,'positions.display')
->get();
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.
Here is a select list built using PHP, MariaDB, and HTML:
echo "<select name='companylist' id='companylist' size='86' value='' tabindex='1' >";
echo "<option value=''></option>";
echo "<option value='0-Create a New Company'>0-Create a New Company</option>";
foreach ($companyResult as $company) {
echo "<option id='".$company['Company_Key']."'
value='".$company['Company_Key']."'>".$company['Company_Names']."</option>";
}
echo "</select>";
It builds a dropdown list that is appropriate for my application.
Next, I built this testing script to find out if I was on the right track in the use of RegExp to filter the dropdown select list dynamically, and it works well, for its purpose. I only built it because the list following it is giving me fits.
echo "<script>";
echo "$('#companylist option').each(function() {
var Val = this.text;
var Filter='W';
var CompRegex = new RegExp('^'+Filter);
if(CompRegex.test(Val)){
console.log('RegExp with Filter has found the following Val starting with this
Filter: '+Filter);
console.log('Val = ' + Val);
}
})";
echo "</script>";
This above gives me the following console output:
RegExp with Filter has found the following Val starting with this Filter: W
Val = Welch Tile
RegExp with Filter has found the following Val starting with this Filter: W
Val = West Michigan Molding
RegExp with Filter has found the following Val starting with this Filter: W
Val = WL Molding of MI
This is a good start.
echo "<script>";
echo " $('#companylist')";
echo " .editableSelect()";
echo " .on('select.editable-select', function (e, li) {
console.log('value = ' + document.getElementById('companylist').value);
console.log('li.val() = '+li.val());
getCustomer_Names(li.val());
getTool_Numbers(li.val());
getPart_Name(li.val());
newCompany_Name();
})";
echo "</script>";
This above script loads other menus, as expected, once the user selects an item.
The next script here simply will not let me get the option text that the user sees in the list. I have 5 days into this, because I am new to JQuery and not a master of Javascript either, but I do read all kinds of sites for help, including reference guides, and the support boards (thank you for this one!), but I would like a happy ending soon. Any help, as stated, would be very appreciated.
echo "<script>";
echo " $('#companylist')";
echo " .editableSelect()";
echo " .on('input.editable-select', function () {
$(this).each(function() {
var Val = this.text;
var Filter = this.value;
var CompRegExp = new RegExp('^'+Filter);
console.log('Val = '+Val);
console.log('Filter = '+Filter);
console.log('CompRegExp = '+CompRegExp);
if(CompRegExp.test(Val)){
console.log('RegExp with Filter has found the following Val starting with this
Filter: '+Filter);
console.log('Val = ' + Val);
}
else {
// remove from select list
}
});
});";
echo "</script>";
This above script gives me
Val = undefined
Filter = a
CompRegExp = /^a/
It is the "Val = undefined" that is my undoing.
I also took a long-view of this problem and wrote a jQuery/JavaScript program that clears the dropdown list and then recreates the options by having a PHP program re-query the database to get the values that match a SQL LIKE 'Input%' which I will include to show you the depth of effort here. The problem here is that I could not get the dropdown menu to stay open even though I issued .editableSelect('show'); as instructed in the editableSelect git website to open the dropdown menu and show the modified list, although, if I clicked in the field and moved the cursor around, it would pop the menu open with the values that matched the return from MariaDB. It follows:
echo "<script>
function getCompany_Names(comp_val)
{
if(document.getElementById('companylist').value.substring(0,8) != '0-Create'){
$('#companylist').editableSelect('clear');
var xhttp;
if (comp_val === null || comp_val === '' ) {
$('#companylist').editableSelect('add', '<option value=></option>');
$('#companylist').editableSelect('add', '<option value=0-Create a New Company>0-Create a
New Company</option>');
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var select = $('#companylist');
var c_text = this.responseText;
console.log('comp_ctext = ' + c_text);
c_text = JSON.parse(c_text);
$.each($(c_text),function(key,value){
if (value.compname == 'One or more Company Names are Probably Not Entered.')
{
$('#companylist').editableSelect('add','<option value=' + 'One or more Company
Names are Probably Not Entered.' + '>One or more Company Names are Probably Not
Entered.</option>');
}
else
{
console.log('<option id=\'' + value.compkey + '\' value=\'' + value.compkey + '\'>'
+ value.compname + '</option>');
$('#companylist').editableSelect('add','<option id=\'' + value.compkey + '\'
value=\'' + value.compkey + '\'>' + value.compname + '</option>');
}
}); // end .editableSelect('add',...)
}
};
xhttp.open('GET', 'getCompany_Names.php?q='+comp_val, true);
xhttp.send();
}
}
</script>";
This is all because my patron does not like the default filter behavior of the editableSelect package where it matches what is typed to any values anywhere in the dropdown and wants some dropdowns to come up matching the input to the results from first character onward with something like (exactly like) a regex of /^input_variable/.
Thank you for your time.
R
its not a solution, just easier to ask something..i'll delete more later
i dont understand this syntax: no selector before .on??
.on('input.editable-select', function () {
$(this).each(function() {
i see $(this) that means you have more input?
the problem with these lines:
var Val = this.text;
var Filter = this.value;
what is Val? because this.text is not functional for input? (its the reason Val => undefined)
this.value gives what you type in input
This is WAY more complicated than my core problem actually is. I have posted another question that is just my actual failure. It is at: [https://stackoverflow.com/questions/66801231/the-use-of-https-github-com-indrimuska-jquery-editable-select-for-editable-sel]
I think I have an example of an example page the creator put together and it has a function their I am only just starting to understand, but it is all about adding values to the list. I will study it and post my results on the core issue page. Thank you to all who tried to help. Here's one for brevity.
I have been struggling with this for the last two hours and I can't get it to work. Take a look to the following piece of code:
$js = '$.extend($.fn.fmatter , {
userActions : function(cellvalue, options, rowData, addOrEdit) {
var data = cellvalue.split("|");
var id = options.rowId;
var actions = "";';
foreach ($editorActions as $linkType => $value) {
switch ($linkType) {
case 'view':
$js .= "if(data[1] == 1) {
actions += \"<a class='actionimage' href='" . $value . " + options.rowId' title='" . $this->translate->_e('View') . "' onClick='load_start();'><img src='/images/icons/16x16/document_view.png' width='16' height='16' alt='' /></a>\";
}";
}
break;
}
As you can see id is a value coming from Javascript and $value is coming from PHP. The idea is to get an hyperlink as for example:
$value = "/route/to/function/";
id = 19009; // I've omitted the $ sign since this var is coming from JS
var href = "' . $value . '" + id;'
Then I need to use the href var as part of the <a> element shown right after the definition.
With my code above I am getting this error:
Uncaught SyntaxError: Invalid or unexpected token
Can I get some help to get this right?
UPDATE:
This is how the code looks like after I render the page:
$(function () {
$.extend($.fn.fmatter, {
userActions: function (cellvalue, options, rowdata) {
var data = cellvalue.split('|');
var id = options.rowId;
var actions = '';
console.log(id);
if (data[1] == 1) {
actions += "<a class='actionimage' href='/sf/distributor/show/ + options.rowId' title='View' onClick='load_start();'><img src='/images/icons/16x16/document_view.png' width='16' height='16' alt='' /></a>";
}
return actions;
}
});
});
Notice how the function $.extend close properly. console.log(id) did print the value of options.rowId however this value doesn't have any effect on the hyperlink as you may notice this is the value /sf/distributor/show/ + options.rowId.
What is coming in $value is a plain string in the case above /sf/distributor/show/.
You're missing double quotes and to end and reopen the string around options.rowId and a + in:
actions += \"<a class='actionimage' href='" . $value . " + options.rowId'
It should be:
actions += \"<a class='actionimage' href='" . $value . "\" + options.rowId + \"'
Here you are missing "" and that way you are adding options.rowId as a string text.
href='/sf/distributor/show/" + options.rowId + "'
I am working on an app for personal dev and have ran into some trouble. Fairly new to php and javascript so help is appreciated.
It's a simple form with an input and sumbit button. Once the user inputs an ISBN number and clicks search, a div should appear below showing a Google Books results containing title, author and description.
The way I am approaching this is to use the contents of var $isbn in my javascript. This could be the complete wrong way to do it, which is why I'm here. Basically I want to use the inputted ISBN number and 'attach' this to the end of the Google Books search (see below);
var url='https://www.googleapis.com/books/v1/volumes?q='[USER ISBN INPUT HERE];
If I manually set the var $isbn to '0276427343' - I do receive book results and see the div contents successfully. Just not when they are posted by the form to var $isbn.
I will show my code as is now;
HTML Form
<form name="form" method="post" action="">
<input name="isbn_search" id="isbn_search" type="text">
<button id="submit" name="submit">search</button>
</form>
PHP
if(isset($_POST['isbn_search'])){
$isbn = $_POST['isbn_search'];
}
JaveScript
$(document).ready(function() {
var isbn = <?php echo $isbn; ?>;
var url='https://www.googleapis.com/books/v1/volumes?q='+isbn;
$('#submit').click(function() {
$.getJSON(url,function(data){
$('.result').empty();
$.each(data.items, function(entryIndex, entry){
var html = '<div class="results well">';
//html += '<h3>' + entry.id + '</h3>';
html += '<h3>' + entry.volumeInfo.title + '</h3>';
html += '<div class="author">' + entry.volumeInfo.authors + '</div>';
html += '<div class="description">' + entry.volumeInfo.description + '</div>';
$('.result').append(html);
});
});
return false;
});
});
Any help and/or suggestions are welcome.
Your problem is because the form never submits (you stop it with your javascript).
However php is unnecessary for this, you can just extract the value with js:
$(document).ready(function() {
$('#submit').click(function(ev) {
ev.preventDefault();
var isbn = $('#isbn_search').val(); //get isbn direct from input, no need for php
var url='https://www.googleapis.com/books/v1/volumes?q='+isbn;
$.getJSON(url,function(data){
$('.result').empty();
$.each(data.items, function(entryIndex, entry){
var html = '<div class="results well">';
//html += '<h3>' + entry.id + '</h3>';
html += '<h3>' + entry.volumeInfo.title + '</h3>';
html += '<div class="author">' + entry.volumeInfo.authors + '</div>';
html += '<div class="description">' + entry.volumeInfo.description + '</div>';
$('.result').append(html);
});
});
});
});
I think in this case you don't need to use PHP.
but simply try this :
<div>
<input id="isbn_search" type="text">
<button onclick="do_search();" id="submit" name="submit">search</button>
</div>
<div class="result"></div>
<script>
function dosearch(){
var isbn = document.getElementById('isbn_search').value; //$('#isbn_search').val(); : if you like jquery :D
var url='https://www.googleapis.com/books/v1/volumes?q='+isbn;
$.getJSON(url,function(data){
$('.result').empty();
$.each(data.items, function(entryIndex, entry){
var html = '<div class="results well">';
//html += '<h3>' + entry.id + '</h3>';
html += '<h3>' + entry.volumeInfo.title + '</h3>';
html += '<div class="author">' + entry.volumeInfo.authors + '</div>';
html += '<div class="description">' + entry.volumeInfo.description + '</div>';
$('.result').append(html);
});
//here we send this query to database (thanks to AJAX):
//=====================================================
$.ajax({
type: 'POST',
url: './db_insert.php',
data: {'isbn' : isbn },
});
});
}
</script>
if you want to save the search in a database,
we create a php file : db_insert.php
<?php
// first : init access to data base :
//====================================
$user="root"; //user of database
$pass=""; //password of database
$db="test"; //name of database
$host = "localhost"; //host name
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO('mysql:host='.$host.';dbname='.$db, $user, $pass, $pdo_options);
$bdd->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$bdd->query("SET NAMES 'utf8'");
//second : insert in a table named "all_search" in this case :
===============================================================
$req = $bdd->prepare('INSERT INTO all_search(isbn, date_in) VALUES(:isbn, :date_in)');
$req->execute(array(
'isbn' => $_POST['isbn'],
'date_in' => date('Y-m-d H:i:s')
));
//emm... I think thats all, Enjoy :D
?>
You should try to understand the basic concepts of javascript and php before you implement them like this.
It looks like what you want to achieve is sending an ISBN provided by a client to the server.
The client runs Javascript (interpreted by the browser) - the server runs php(interpreted by the server when requested)
A basic classical concept:
split your HTML CSS JAVASCRIPT (HTML5) to your client and let it do all client stuff
get your PHP to do all the server stuff.
You can send information to your PHP server script in different ways now - via ajax or with the submitting the form with a defined action attribute
I hope this helps - you dont need help with the code first of all - spend some (2-3) hours understanding the concepts - then come back and try to get your code right :)
I hope this helps
it's because you are trying to get ISBN entered by user into $_POST. Where your JS is based on button click. So you can't get isbn field value by this way.
Change your JS to below.
var isbn = $('#isbn_search').val();
PHP code is not needed.
if($_POST....
I'm not sure if I understand you correct but you can return the ISBN number from PHP with json and then use it in your JavaScript.
<?php
$isbn = $_POST['isbn'];
json_encode($isbn);
?>
I've got this code, which add videos (and videos infos) of a YouTube channel ($_POST) on a div of the Html code :
var args= "url="+urlchaine;
xhr_object.open("POST", "traitement.php", true);
xhr_object.onreadystatechange = function() {
if(xhr_object.readyState == 4) {
eval(xhr_object.responseText);
}
return xhr_object.readyState;
}
xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr_object.send(args);
traitement.php :
<?php
if ( isset($_POST["url"]) && !empty($_POST["url"]) )
$urlchaine = $_POST["url"];
else
$urlchaine = null;
$stringresult = str_replace("http://www.youtube.com/user/", "",$urlchaine);
require_once "Zend/Loader.php";
Zend_Loader::loadClass('Zend_Gdata_YouTube');
$yt = new Zend_Gdata_YouTube();
//Get Video info with channel name $stringresult
$videoFeed = $yt->getVideoFeed('http://gdata.youtube.com/feeds/users/...');
if ( $stringresult != null){
echo "var mydiv = document.getElementById('vids');";
echo "var newcontent = document.createElement('div');";
foreach ($videoFeed as $v): $thumbs = $v->getVideoThumbnails();
$videoId = $v->getVideoId();
$thumb = $thumbs[0]['url'];
$videoViewCount = $v->getVideoViewCount();
$videoTitle = $v->getVideoTitle();
echo "newcontent.innerHTML =
'<div class=\"videos\">' +
' <div class=\"img_videos\">' +
' <img class=\"img_video\" width=\"250\" idvideo=\"".$videoId."\" ' +
' src=\"".$thumb."\"/>' +
' </div>' +
' <h3>$videoTitle</h3>' +
' <p>$videoViewCount views</p>' +
'</div>' ;";
echo "mydiv.appendChild(newcontent.firstChild);";
endforeach;
?>
The problem is, when I want to do that, it works perfectly with some channels, whereas an error has existed for others (Uncaught SyntaxError: Unexpected identifier). After several tests, I saw that by removing the display of $ videoTitle, every channels test worked. What is wrong with my code? O.o
$videoTitle seems to contains a simple quote in somes cases, which break your JS code.
Try escaping this quotes with something like this :
str_replace("'", "‚", $videoTitle)