How to store and retrieve materializecss chips? - php

I have a form where I'm putting the chipsData into a hidden input field called #hiddenTags I'm doing this because I don't want you use an AJAX call because I have a pre-exist form. Below is how I'm putting the chip data into the hidden input.
$("form").on("submit", function() {
var tags = M.Chips.getInstance($('.chips')).chipsData;
var sendTags = JSON.stringify(tags);
$('#hiddenTags').val( sendTags );
});
I'm sending it to the database like this: (PHP)
$this->tags = json_encode( $data['tags'] );
However, saving data like this is raising all sorts of issues. I'm using Twig to display the data.
Below is how I'm trying to display it, however with this I get an error unexpected token & in json
$('.chips').chips();
$('.chips-initial').chips({
data: {{ json }}
});
I have also tried putting the json into a hidden input and then putting it into jquery:
<input id="raw_json" type="hidden" hidden value="{{ user.tags }}">
var json = $('#raw_json').val();
$('.chips').chips();
$('.chips-initial').chips({
data: json
});
However, with this I get and error of Cannot read property 'length' of undefined
Apologies if I'm doing something stupid and/or completely wrong, any help is much appreciated.

So the answer to your problems lies in setting the values when initializing the chips object, along with parsing the JSON data.
From there just keep the text box updated on add or delete of a chip.
var chipsData = JSON.parse($("#Tags").val());
$('.chips-placeholder').chips({
placeholder: 'Enter a tag',
secondaryPlaceholder: '+Tag',
data: chipsData,
onChipAdd: (event, chip) => {
var chipsData = M.Chips.getInstance($('.chips')).chipsData;
var chipsDataJson = JSON.stringify(chipsData);
$("#Tags").val(chipsDataJson);
},
onChipSelect: () => {
},
onChipDelete: () => {
var chipsData = M.Chips.getInstance($('.chips')).chipsData;
var chipsDataJson = JSON.stringify(chipsData);
$("#Tags").val(chipsDataJson);
}
});

Related

How to set Jquery Autocomplete to a specific value and display It's Label using a datasource of JSON objects

Background
So I have a table that is populated by a form. Each row can be edited by hitting a edit button. The Edit button opens the form that is populated. I need to auto fill the autocomplete so that the user can see one of His selected course.
How I Cheated
I'm using PHP and Codeigniter server side and am dynamically creating my form based on database. The labels and values are all produced from the Database and populate my JQuery Auto complete (a.k.a datasource variable below). From my controller I'm passing my value to the model and getting the Label from the DB. From there I'm passing it to my view and to my AutoComplete and setting the input value equal to the found label.
I feel dirty having done it this way. The inefficiency of this burns my eyes.
My Goal
I want to use the value that I've gotten and have the autocomplete select it and display it's label client side.
OR
I need to just display the label in the box so the user knows it's not a blank field.
Both options need to allow the user to modify the autocomplete box.
Existing Code
My code for the input looks like this:
<div class="row-start span-2">
<label for="course_code">Course Code </label>
</div>
<div class="row-end span-2">
<input id="course_code">
</div>
My script for the autocomplete looks like this:
<script>
function search_course_code(){
var datasource = [{"value":"1","label":"AAF100 - DL"},{"value":"2","label":"AAF101 - DL+web"},.....];
var searchboxid = "#course_code";
var searchresultid = "#CRSEINVID";
$(searchboxid).autocomplete({
source:datasource,
focus: function( event, ui ) {
$( searchboxid ).val( ui.item.label );
return false;
},
select: function(event,ui){
var UIvalue = ui.item.value;
var UIlabel = ui.item.label;
console.log(UIvalue);
console.log(UIlabel);
$( searchboxid ).val( ui.item.label );
use_search("#search1","#CRSEINVID",UIvalue,UIlabel ); return false;
}
});
};
function use_search(show_select,result_id,uivalue,uilabel){
//loads value to field that takes it's value
$(result_id).val(uivalue);
//Display course below search box
course = "<span>"+uilabel+"</span>";
$(show_select).html(course );
//stops the value from being shown in the search box
return false;
};
$( document ).ready(function() {
search_course_code();
});
</script>
I draw the value from a hidden input with a unique ID simply using JQUERY val() function.
What I've tried
Try 1
Setting value using:
$(searchboxid).val(hiddenInputValue);
Result: Value displayed not the label
Try 2
Using the autocomplete on create method I tried to overwrite the UI object and send it to the select.
ui.item={"value":"","label":""};
ui.item.value=$(hiddenInputValue).val;
this.select(ui);
Result: No observable change, no errors.
Try 3
$(searchboxid).autocomplete("select", hiddenInputValue);
Result:
Uncaught Error: cannot call methods on autocomplete prior to
initialization; attempted to call method 'select'
Try 4
Tried changing value using
$(searchboxid).val(hiddenInputValue);
and having change function detect it and set label with
$( searchboxid ).val( ui.item.label );
Result: Value loaded into input not label
Try 5
Tried Triggering the change function with this:
$("#<?php echo $id;?>").autocomplete("option","change").call(searchBox);
and then setting label. Based on the answer to:
jQuery AutoComplete Trigger Change Event
Result: empty UI object for change function,
Try 6
Tried Triggering the select function with this:
$("#<?php echo $id;?>").autocomplete("option","select",{value:hiddenInputValue}).call(searchBox);
and then using my current select function.
Result: Uncaught Error: undefined is not a function,
Ideas
Ideas 1:
I thought of using the value then searching through the datasource object to find associating label and then using:
$(searchboxid).val(label);
would this work? How would I do it?
Idea 2:
If the value of the input field is set to a value using:
$(searchboxid).val(label);
Would the change function detect it? Not detected used console.log function in change function to give feedback,
So after much research and trying to get this to work I discovered two problems:
that I was using Select2 version 3.5.3 and needed to use text instead of label and :
$myselect.select2("val","somevalue");
The MAJOR source of my problem though was because I was using Web Experience Toolkit tabs and I needed to load the Select 2 after tabs where initialized.
assign the value to the auto complete input element by using
$('#YourAutoCompletBox').val(yourValuefromHiddenControl);
html:
Topic: <input type="text" id="topics" /><input type="hidden" id="topicID" />
<br/><br/><br/><br/>
<p>You selected <span id="results"></span></p>
jQuery:
var topics= [
{
value: "cooking",
label: "Cooking",
id: "1"
},
{
value: "C++",
label: "C++",
id: "2"
},
{
value: "craftsmanship",
label: "Software Craftsmanship",
id: "3"
}
];
$(document).ready(function() {
$( "#topics" ).autocomplete({
minLength: 0,
source: topics,
focus: function( event, ui ) {
$( "#topics" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#topics" ).val( ui.item.label );
$("#topicID").val(ui.item.id);
$( "#results").text($("#topicID").val());
return false;
}
})
});
Playground : jsfiddle

Getting jQuery array into php form

I have a form that includes several input text fields and a list that's sortable (se code below). The function below retrieves the new positions that's saved to an array (order). However, what I want is to include the array in the form so that when the user is finished with the sorting, has filled in the text fields and submits the form this array will be apart of the form.
So, how could I get this array into the form with AJAX?
$('#listElements').sortable({
//revert: true,
update: function(event, ui) {
var order = [];
$('.listObject li').each(function (e) {
order.push($(this).attr('id'));
});
$.ajax({
url: "/index.php?type=list&action=showList&listId=1",
type: "post",
data: {
order_data: order
}
}).success(function (data) {
console.log(data);
});
}
});
NOTE: To make it clear, I want to get the array into the form.
send it as a JSON encoded string and decode it serverside. As far as I know jquery has a array to JSON function and php got json_decode()

JavaScript: Backbone.js populate collection of models

Here is what I have so far:
var Item = Backbone.Model.extend({
defaults: {
id: 0,
pid: 0,
t: null,
c: null
},
idAttribute: 'RootNode_', // what should this be ???
url: 'page.php'
});
var ItemList = Backbone.Collection.extend({
model: Item,
url: 'page.php',
parse: function(data) {
alert(JSON.stringify(data)); // returns a list of json objects, but does nothing with them ???
}
});
var ItemView = Backbone.View.extend({
initialize: function() {
this.list = new ItemList();
this.list.bind('all', this.render, this);
this.list.fetch();
},
render: function() {
// access this.list ???
}
});
var view = new ItemView();
Current (expected) json response:
{
"RootElem_0":{"Id":1,"Pid":1,"T":"Test","C":"Blue"},
"RootElem_1":{"Id":2,"Pid":1,"T":"Test","C":"Red"},
"RootElem_2":{"Id":3,"Pid":1,"T":"Test2","C":"Money"}
}
This successfully polls page.php and the backend acts on $_SERVER['REQUEST_METHOD'] and returns the required information, however I don't know why the collection is not filled.
In the parse function of ItemList it properly shows me all the output, but it does nothing with it.
I left some comments in the code for some more precise questions, but the main question is why doesn't the collection populate with the obviously received data?
Modify your parse method to:
parse: function(response){
var parsed = [];
for(var key in response){
parsed.push(response[key]);
}
return parsed;
}
To follow conventions, change list inside ItemView to model. Also in render():
render: function() {
var template = _.template("<div>some template</div>");
this.model.each(function(item){
this.$el.append(template(item.toJSON()));
}, this);
return this;
}
The parse method you're supposed to be returning the data after doing whatever necessary parsing is required for it.
The common use case for parse would be if you're sending back an object of a form like:
{ "id" : "NaN", "tasks": [ *all your models in a list here *] }
then you'd use parse like so:
parse: function (data) {
return data.tasks
}
Backbone then handles the rest.
Is there a particular reason why you're sending the data back in that dictionary format? It's not exactly clear how you intend to map that to each model of the collection. Is the key irrelevant? if so, you should be passing back a list of the objects in the values.(Although see note at bottom). If not, and you want to attach it to the models, it should be moved to the object you're using as a value and send back a list.
* Note: Don't actually send back a JSON list bare. There is an exploit for GET requests that relies on lists being valid javascript on their own, where a malicious site can use the Array object and override it to use a script tag to your API to use the users credentials to pull down whatever information is available in that call. Instead, when wanting to send back a list you should use something like this:
{ result: [*list here*] }
Then you just use the parse method above to extract the list.

MYSQL data + PHP to FLOTgraphing

im quite new to mysql and flot graphing, but i get the general idea.
This is my scenario:
I receive data from a device, in which i put into mysql database.
am i wrong in saying that the new data will replace the existing data in the database?
i then need to plot that on a graph, how do i get(store) the old values so i can put in the data in this line?
$(function () {
var d4 = [[36,37],[50,51],null,[23,24],[18,17]];
$.plot($("#placeholder"), [d4]);
});
if not, i'll only be getting the current data... and that doesnt give me a line.. it'll give me datapoints haha
Thanks for your help!
First, you'll want to set the stage for a graph that you can recreate dynamically. To do so, grab your container then fire off an ajax call to the script that wraps up your data. Within the ajax success call, catch the script's results within a function and send it off to a method such as resetGraph that will reset the graph according to the new information found within the database.
var dataview = $("#placeholder");
$.ajax({
url: "index.php",
data: "stuff&junk&things",
method: 'GET',
dataType: 'json',
success: function(msg){
resetGraph(msg);
}
});
function resetGraph( data ){
plot = $.plot(dataview, data.data, {
points: { show: true, radius: 5 },
xaxis: { ticks: data.ticks, tickSize: 7 },
yaxis: {labelHeight: 2}
});
}
Your script should be populating arrays with the necessary information then json_encoding it before sending it back to Jquery. For example,
echo json_encode(
array(
"data" => array(
array("data" => array(1,2,3))
),
"ticks" => array(2, "two")
)
);

jQuery Connected Sortable Lists, Save Order to MySQL

Hoping that using something like this demo it is possible to drag items within and between two columns, and update their order either live or with a "save" button to MySQL. Point being that you can make changes and return to the page later to view or update your ordering.
http://pilotmade.com/examples/draggable/
Doing it for just one column is fine, but when I try to pass the order of both columns, the issue seems to be passing multiple serialized arrays with jQuery to a PHP/MySQL update script.
Any insight would be much appreciated.
If you look below, I want to pass say...
sortable1entry_1 => 0entry_5 => 1
sortable2entry_3 => 0entry_2 => 1entry_4 => 2
EDIT: This ended up doing the trick
HTML
<ol id="sortable1"><li id="entry_####">blah</li></ol>
jQuery
<script type="text/javascript">
$(function()
{
$("#sortable1, #sortable2").sortable(
{
connectWith: '.connectedSortable',
update : function ()
{
$.ajax(
{
type: "POST",
url: "phpscript",
data:
{
sort1:$("#sortable1").sortable('serialize'),
sort2:$("#sortable2").sortable('serialize')
},
success: function(html)
{
$('.success').fadeIn(500);
$('.success').fadeOut(500);
}
});
}
}).disableSelection();
});
This is the PHP query
parse_str($_REQUEST['sort1'], $sort1);
foreach($sort1['entry'] as $key=>$value)
{
do stuff
}
what I would do is split them up
data :
{
sort1:$('#sortable1').sortable('serialize'),
sort2:$('#sortable2').sortable('serialize')
}
then when you post you can get the request and set them as needed, I hope that makes sense
so what I do is this
parse_str($_REQUEST['sort1'],$sort1);
foreach($sort1 as $key=>$value){
//do sutff;
}

Categories