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)
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 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 working on a search form which have a drop down menu filter. And the site is created by Yii.
My filter form looks like this before it's submitted: PIC 1
Form when I select the filters: PIC 2
But after I click the filter button it comes again like this: PIC3
But I want the form should remain as PIC 2 after I submit the form when it shows the results.
My form is:
<div class="row">
<div style="float: left">
<label class="form_controller required">By Brand</label>
<select style="width: 148px;" id="select_options" name="SCDcustomer_contacts_cms[brand_select_option]">
<option value="none">Select an option</option>
<option value="brand_preference">Brand Preference</option>
<option value="brand_purchased">Brand Purchased</option>
</select>
</div>
<div id="select_a_brand" name="select_a_brand">
<?php echo $form->dropDownList($model,'brand_id', gGetBrandList('brand_id', 'brand_id, brand_name'), array('prompt'=>'Select a brand')); ?>
</div>
<script type="text/javascript">
$(document).ready(function(){
jQuery('#select_a_brand').hide();
$("#select_options").change(function(){
$( "select option:selected").each(function(){
if(($(this).attr("value")=="brand_preference") || ($(this).attr("value")=="brand_purchased") ){
$("#select_a_brand").show();
}
if($(this).attr("value")=="none"){
$("#select_a_brand").hide();
}
});
});
});
</script>
</div>
Rules function is:
public function rules()
{
return array(
array('scd_cust_id,cust_id,order_first_name,order_surname,order_email,order_postcode, brand_id, brand_select_option', 'safe', 'on'=>'search'),
);
}
Form filter is :
if(!empty($filter)) {
if ($this->brand_select_option == "brand_preference") {
$criteria->select .= ', COUNT(*) as brand_preference';
$criteria->join .= ' INNER JOIN order_table ot ON ot.billing_contactid = t.contactid';
$criteria->join .= ' INNER JOIN order_item oi ON ot.scd_order_id = oi.scd_order_id';
$criteria->join .= ' INNER JOIN johnanthony_rstest.product p ON p.product_id = oi.product_id';
$criteria->condition .= (!empty($criteria->condition) ? ' AND ' : '') . 'p.brand_id=:brand_id';
$criteria->group = 't.contactid';
$criteria->order = 'COUNT(*) DESC';
$criteria->params = array(':brand_id'=>$this->brand_id);
$paging['pagination']['route']='report/index?SCDcustomer_contacts_cms[brand_id]=' . $this->brand_id;//For ajax pagination URL
}
if ($this->brand_select_option == "brand_purchased") {
$criteria->select .= ', SUM(product_price) AS brand_purchased';
$criteria->join .= ' INNER JOIN order_table ot ON ot.billing_contactid = t.contactid';
$criteria->join .= ' INNER JOIN order_item oi ON ot.scd_order_id = oi.scd_order_id';
$criteria->join .= ' INNER JOIN johnanthony_rstest.product p ON p.product_id = oi.product_id';
$criteria->condition .= (!empty($criteria->condition) ? ' AND ' : '') . 'p.brand_id=:brand_id';
$criteria->group = 't.contactid';
$criteria->order = 'SUM(product_price) DESC';
$criteria->params = array(':brand_id'=>$this->brand_id);
$paging['pagination']['route']='report/index?SCDcustomer_contacts_cms[brand_id]=' . $this->brand_id;//For ajax pagination URL
}
}
Ajax file is:
if (!empty($model->brand_id) && ($model->brand_select_option == "brand_preference")) {
array_push($options['columns'], array(
'name'=>'brand_preference',
'filter'=>false,
'header'=>'Brand Preference (No of purchased items)',
'type'=>'raw',
'value'=>'$data->brand_preference',
));
}
if (!empty($model->brand_id) && ($model->brand_select_option == "brand_purchased")) {
array_push($options['columns'], array(
'name'=>'brand_purchased',
'filter'=>false,
'header'=>'Brand Purchased (Sum of purchased items)',
'type'=>'raw',
'value'=>'$data->brand_purchased',
));
}
Main problem is DOM refreshes page, because probably regular submit is made. Without submit method can't tell anything more specifically. If you do ajax, you get all data in json data holder. Then you parse it into object and html required parts to where you want to show results. All filtering and etc. has to happen in model. Controller only passes values over to it.
Make filter button as ajaxButton:
<?php echo CHtml::ajaxSubmitButton(
'Filter',
Yii::app()->createUrl('report/index'),
array(
'type'=>'POST',
'data'=> 'js:{"SCDcustomer_contacts_cms[brand_select_option]": $('#select_options').val(), "SCDcustomer_contacts_cms[brand_id]": $('#select_brand').val() }',
'success'=>'js:function(data){ var data = JSON.parse(data);
$('#search-result-holder').html(data.search-results); }'
)); ?>
UPDATE: 2014 - 09 - 30 Some extra data for processing.
You should make some extra view with html of the way you would want your results to look like. Pass attribute values to that view via renderPartial (this has to happen within controller). For example:
//Controller part which passes posted data to model
<?php
public function actionIndex() {
....
if(Yii::app()->request->isAjaxRequest){
$attributes = Yii::app()->request->getParam('SCDcustomer_contacts_cms');
$model->attributes = $attributes;
}
...
//Part of the controller which returns resulting model after specific functions
$model = $model->getDataByFilterQuery();
$search_results = $this->renderPartial('report/extra-views/search-results', array('model'=>$model), true);
echo CJSON::encode(array('search-results'=>$search_results));
...
}
?>
//In model
public function brandPreference() {
$criteria = new CDbCriteria;
$criteria->select .= ', COUNT(*) as brand_preference';
$criteria->join .= ' INNER JOIN order_table ot ON ot.billing_contactid = t.contactid';
$criteria->join .= ' INNER JOIN order_item oi ON ot.scd_order_id = oi.scd_order_id';
$criteria->join .= ' INNER JOIN johnanthony_rstest.product p ON p.product_id = oi.product_id';
$criteria->condition .= (!empty($criteria->condition) ? ' AND ' : '') . 'p.brand_id=:brand_id';
$criteria->group = 't.contactid';
$criteria->order = 'COUNT(*) DESC';
$criteria->params = array(':brand_id'=>$this->brand_id);
$paging['pagination']['route']='report/index?SCDcustomer_contacts_cms[brand_id]=' . $this->brand_id;//For ajax pagination URL
return new CActiveDataProvider($this, array(
'criteria' => $criteria, $paging
));
}
public function brandPurchased() {
$criteria = new CDbCriteria;
$criteria->select .= ', SUM(product_price) AS brand_purchased';
$criteria->join .= ' INNER JOIN order_table ot ON ot.billing_contactid = t.contactid';
$criteria->join .= ' INNER JOIN order_item oi ON ot.scd_order_id = oi.scd_order_id';
$criteria->join .= ' INNER JOIN johnanthony_rstest.product p ON p.product_id = oi.product_id';
$criteria->condition .= (!empty($criteria->condition) ? ' AND ' : '') . 'p.brand_id=:brand_id';
$criteria->group = 't.contactid';
$criteria->order = 'SUM(product_price) DESC';
$criteria->params = array(':brand_id'=>$this->brand_id);
$paging['pagination']['route']='report/index?SCDcustomer_contacts_cms[brand_id]=' . $this->brand_id;//For ajax pagination URL
return new CActiveDataProvider($this, array(
'criteria' => $criteria, $paging
));
}
public function getDataByFilterQuery() {
if($this->brand_select_option == 'brand_preference')
return $this->brandPreference();
elseif($this->brand_select_option == 'brand_purchased')
return $this->brandPurchased();
else
return null //or whatever you want
}
//Search result file
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'id',
'brand',
'product_title',
'description' => array(
'name' => 'description',
'value' => html_entity_decode(CHtml::decode($model->description)), //this is only for example purposes
),
'price',
'date',
),
));?>
//Index file
...
<?php echo CHtml::ajaxSubmitButton(
'Filter',
Yii::app()->createUrl('report/index'),
array(
'type'=>'POST',
'data'=> 'js:{"SCDcustomer_contacts_cms[brand_select_option]": $('#select_options').val(), "SCDcustomer_contacts_cms[brand_id]": $('#select_brand').val() }',
'success'=>'js:function(data){ var data = JSON.parse(data);
$('#search-result-holder').html(data.search-results); }'
)); ?>
...
<div id="search-result-holder"></div>
...
As well you have to modify it specifically for your case. And I'm in doubt that $paging variable will work there as it is. I prefer using pagination parameter in CActiveDataProvider object. In second option you can open array and within that array open pagination parameters array. Or do like here: CPagination documentation it is up to you.
It seems you are loading the page every time when you click on button Filter,if you using Ajax you can to this click event with out postback,or if you have to refresh page the simplest way it just to save drop down menu Index's that was selected before you do the filter event button, and when you load your page again you just will pass to you drop down menu's with index's is need to be selected when you load the page.I hope it will help you.
Below is my PHP MySQL Query and getting the last value result, I want to add 10 Javascript functions into my PHP page at end of page, however counting of variable works but I am not able to concat that value to function and other variable names.
Below is my code:
<script>
<?php
$brSql = "SELECT BRANCH_ID FROM `tb_um_client_branches` ORDER BY BRANCH_ID DESC LIMIT 1";
$brRset = mysql_query($brSql) or die('BRANCH LAST ID QUERY FAIL: '.mysql_error());
$brRID = mysql_fetch_row($brRset);
for($i = 0; $i < 10; $i++){
?>
cnter = (<?php echo $brRID[0]; ?> + <?php echo $i; ?>)
function getChecked_+cnter(){
var nodes+cnter = $('#tt_+cnter').tree('getChecked');
//var nodes = $('#tt').tree(data-options="method:'get',animate:true,checkbox:true");
var s_+cnter = '';
for(var i_+cnter=0; i_+cnter<nodes_+cnter.length; i_+cnter++){
if (s_+cnter != '') s_+cnter += ',';
s_+cnter += nodes_+cnter[i_+cnter].id + ' ' + nodes_+cnter[i_+cnter].text;
}
//$('#OLD_BRANCH_FILTERS_+cnter').value = s_+cnter;
$('#OLD_BRANCH_FILTERS_'+cnter).attr('value', s_+cnter);
//alert(s_+cnter);
}
console.log(cnter);
<?php
}
?>
</script>
Below is error, I am getting:
SyntaxError: missing ( before formal parameters
function getChecked_[cnter](){
Earliest help will be appreciated.
Thanks in advance !
This syntax
function getChecked_+cnter(){
is not valid.
You should use something of that
this["getChecked_"+cnter] = function() {
Important: there is a little difference with this declaration.
I have a script which fetches options from a script php to populate a drop down list on the main page.
Here's the javascript
<script>
//# this script uses jquery and ajax it is used to set the values in
$(document).ready(function(){
//# the time field whenever a day is selected.
$("#day").change(function() {
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
dataType : 'json'
success: function(data) {
//# $("#time").html(data);
var option = '';
$.each(data.d, function(index, value) {
option += '<option>' + value.timing + '</option>';
});
$('#timing').html(option);
}
});
});
});
</script>
Here's the php script which gets data from a database.
<?php
$con = mysqli_connect("localhost","clinic","myclinic","myclinic");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$doctor = $_POST['doctor'];
$day = $_POST['day'];
$query = "SELECT * FROM schedule WHERE doctor='" .$doctor."'AND day='" .$day. "'";
$result = mysqli_query($con, $query);
//$res = array();
echo "<select name='timing' id='timing'>";
//Initialize the variable which passes over the array key values
$i = 0;
//Fetches an associative array of the row
$row = mysqli_fetch_assoc($result);
// Fetches an array of keys for the row.
$index = array_keys($row);
while($row[$index[$i]] != NULL)
{
if($row[$index[$i]] == 1) {
//array_push($res, $index[$i]);
json_encode($index[$i]);
echo "<option value='" . $index[$i]."'>" . $index[$i] . "</option>";
}
$i++;
}
echo json_encode($res);
echo "</select>";
?>
It's not working. I get an error from console saying missing '}' in javasrcipt on line
$("#day").change(function(){
I can't seem to find an error either.
You need to add a comma on the line above the one triggering the error :
dataType : 'json',
It's because you don't have a comma on the line above it...
It's hard to say where is problem, because you mixed things together. On Javascript side you expect JSON but on PHP side you generate HTML.
Use JSON for sending data between server and browser. Ensure that you actually generate valid JSON and only JSON.
This line does nothing (function returns value, but not modifies it)
json_encode($index[$i]);
This line does not make sense - variable $res is not initialized;
echo json_encode($res);