Remote data loading from SQL with Selectize.js - selectize.js

As you will notice, I am a data scientist and not a programmer / developper.
In SQL, I have a database with ten-thousands of names. I managed to implement the selectize.js tool in my twitter bootstrap website, but it loads way to slow. On the help page from Selectize.js, https://github.com/brianreavis/selectize.js/blob/master/docs/usage.md, I read that it is possible to load options on the fly when the user enters something.
But from the examples I can not find out how to do this from an SQL table. Can somebody write in pseudo code what I would have to do?
In short, when the user types some names, I want the script to go find in the SQL table these names and make select html tags, rather than downloading everyname already at the beginning.
This is the code I have at the moment:
<div class="control-group">
<select id="select-yourself" class="demo-default" placeholder="Type your name...">
<option value="">Type your name ...</option>
<?php
for($row = 0; $row < sizeof($race_table); $row++){
echo("<option value=".$row.">".
$race_table[$row]['Name']."</option>");
}
?>
</select>
</div>
<script>
$('#select-yourself').selectize({
create: false,
maxOptions: 100,
//sortField: {
//field: 'text',
//direction: 'asc'
//},
dropdownParent: 'body'
});

You could try something like:
HTML:
<div class="control-group">
<select id="select-yourself" class="demo-default" placeholder="Type your name...">
<option value="">Type your name ...</option>
</select>
</div>
JavaScript:
$('#select-yourself').selectize({
valueField: 'name',
labelField: 'name',
searchField: 'name',
options: [],
create: false,
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: 'http://127.0.0.1:8080/getnames.php',
type: 'GET',
dataType: 'json',
data: {
name: query,
},
error: function() {
callback();
},
success: function(res) {
callback(res);
}
});
}
});
PHP file (getnames.php) is used only to create json file from mysql database data:
<?php
// parameters from URL
$urlparam_name = $_GET['name'] ."%";
// connect to the database
include("mysql.inc");
$link = mysqli_connect($host, $user, $pass, $db) or die("Error " .mysqli_error($link));
$sql = "
SELECT `race_table`.`name`
FROM `race_table`
WHERE `race_table`.`name` like '$urlparam_name'
GROUP BY `race_table`.`name` ASC
";
$result = mysqli_query($link, $sql) or die("Error " .mysqli_error($link));
$rows = array();
while ($row = mysqli_fetch_assoc($result))
{
extract($row);
$rows[] = "{ \"name\": \"$name\" }";
}
// output to the browser
header('Content-Type: text/javascript; charset=UTF-8');
echo "[\n" .join(",\n", $rows) ."\n]";
?>

Related

Uncaught TypeError: Cannot read property 'addEventListener' of null in .net on clear filter

I'm using Tabulator to implement search
Here's my html -- no problems until I try to search, then, I receive the above-captioned error:
<div>
<select id="filter-field">
<option></option>
<option value="custId">Customer ID</option>
<option value="custType">Customer Type</option>
<option value="custName">Customer Name</option>
<option value="groupId">Group ID</option>
</select>
<select id="filter-type">
<option value="=">=</option>
<option value="<"><</option>
<option value="<="><=</option>
<option value=">">></option>
<option value=">=">>=</option>
<option value="!=">!=</option>
<option value="like">like</option>
</select>
<input id="filter-value" type="text" placeholder="value to filter">
</div>
<div id="example-table"></div>
I'm receiving an error in the JavaScript:
````<script>
var table;
function handleCellUpdated(cell) {
console.log(cell);
console.log(cell.getRow());
console.log(cell.getRow().getData());
var record = cell.getRow().getData();
$.ajax({
url: "api/SalesTrackerCustomers/" + record.id,
data: JSON.stringify(record),
contentType: 'application/json',
type: "PUT",
success: function (response, textStatus, xhr) {
console.log("success")
},
error: function (XMLHttpRequest, textStatus, error) {
console.log("error")
}
});
}
function initTable() {
//Build Tabulator
table = new Tabulator("#customers", {
height: "90vh",
placeholder: "Loading...",
addRowPos: "bottom",
columns: [
{ title: "Customer ID", field: "custId", width: 150, editor: "input" },
{ title: "Customer Type", field: "custType", width: 130, editor: "input" },
{ title: "Customer Name", field: "customerName", editor: "input" },
{ title: "Group ID", field: "groupId", editor: "number" }
],
cellEdited: handleCellUpdated
});
loadCustomers();
}
function loadCustomers() {
console.log("loading data");
$.ajax({
url: "/api/SalesTrackerCustomers",
method: "GET"
}).done(function (result) {
table.setData(result);
});
}
// javascript for add/delete
//Add row on "Add Row" button click
document.getElementById("add-row").addEventListener("click", function () {
table.addRow({});
});
//Delete row on "Delete Row" button click
document.getElementById("del-row").addEventListener("click", function () {
table.deleteRow(1);
});
// javascript for search
//Define variables for input elements
var fieldEl = document.getElementById("filter-field");
var typeEl = document.getElementById("filter-type");
var valueEl = document.getElementById("filter-value");
//Custom filter example
function customFilter(data) {
return data.car && data.rating < 3;
}
//Trigger setFilter function with correct parameters
function updateFilter() {
var filterVal = fieldEl.options[fieldEl.selectedIndex].value;
var typeVal = typeEl.options[typeEl.selectedIndex].value;
var filter = filterVal == "function" ? customFilter : filterVal;
if (filterVal == "function") {
typeEl.disabled = true;
valueEl.disabled = true;
} else {
typeEl.disabled = false;
valueEl.disabled = false;
}
if (filterVal) {
table.setFilter(filter, typeVal, valueEl.value);
}
}
//Update filters on value change
document.getElementById("filter-field").addEventListener("change", updateFilter);
document.getElementById("filter-type").addEventListener("change", updateFilter);
document.getElementById("filter-value").addEventListener("keyup", updateFilter);
//Clear filters on "Clear Filters" button click
document.getElementById("filter-clear").addEventListener("click", function () {
fieldEl.value = "";
typeEl.value = "=";
valueEl.value = "";
table.clearFilter();
});
Can anyone add insight on this error? I have tried moving JavaScript around, and I think it may have to do with the placement of the JavaScript. It is displaying above captioned error on on //Clear filters on "Clear Filters" button click; it could also be on the load tabulator javascript function on table
The error you are receiving is because you are trying to add an eventListener to a null value. When using document.getElementById(''), if it does not find an element it returns null. Because you are not checking that you found an element, your .addEventListener tries to attach to a null value, so the error is thrown.
Looking at your code, there are three areas that do not have an html element (from what is included in the question)
There is not a filter-clear, add-row, or del-row element in your HTML. Based on you seeing the error above the document.getElementById('filter-clear').addEventListener(), it looks like your filter-clear element does not exist.
Here is an example that catches the error and appends the error to the body.
https://jsfiddle.net/nrayburn/58he2jr6/6/

Dgrid + Selection Issue

Still trying to work with Dgrid (0.4) and dojo (1.10), I have now another issue with the selection.
My web page contain a Dialog opened when you click on a button.
Inside this dialog, we have the following code which display a grid with data coming from a database through a Json HTTP page. This is working fine, even sorting and query filtering.
What I want to do know is to allow the user to double click on a row, get the selected row Id contains in the first column to update the form in the main page. I use the dgrid/selection for this. However, it always return the last row of the grid instead of the one the user selected.
The selection code is based on this :
http://dgrid.io/tutorials/0.4/hello_dgrid/
Any idea?
Thanks
<script language="javascript">
require
(
[
"dojo/_base/declare",
"dojo/_base/array",
"dgrid/OnDemandList",
"dgrid/OnDemandGrid",
"dgrid/Keyboard",
"dgrid/Selection",
"dgrid/Editor",
"dgrid/extensions/ColumnHider",
"dstore/Memory",
"dstore/RequestMemory",
"dojo/_base/lang",
"dojo/dom-construct",
"dojo/dom",
"dojo/on",
"dojo/when",
"dojo/query",
"dojo/store/Observable",
"dstore/Rest",
"dojo/_base/Deferred",
"dojo/store/Cache",
"dojo/domReady!",
],
function(
declare, arrayUtil, OnDemandList, OnDemandGrid, Keyboard, Selection, Editor, ColumnHider, Memory, RequestMemory, lang, ObjectStore, dom, on, when, query, Observable, Rest, Deferred
){
var fform = dom.byId("filterForm");
var ContactColumns = [
{ label: "", field: "contact_id", hidden: true, unhidable: true},
{ label: "Company Name", field: "company_name", unhidable: true },
{ label: "Contact Name", field: "contact_name", unhidable: true },
{ label: "Email", field: "contact_email", unhidable: true }
];
var ContactGrid=declare([OnDemandGrid, Keyboard, Selection,ColumnHider]);
var contactlist = new Observable(new Rest({ target: './ajax.contactsLoader.php' }));
var selection = [];
window.contactgrid = new ContactGrid(
{
className: "dgrid-selectors",
collection: contactlist,
maxRowsPerPage:10,
selectionMode: 'single',
cellNavigation: false,
columns: ContactColumns
}, "contacttable"
);
on(fform, "submit", function (event) {
var cpy_filter = fform.elements.fcompany_name.value;
var ct_filter = fform.elements.fcontact_name.value;
var email_filter = fform.elements.fcontact_email.value;
contactgrid.set('collection',contactlist.filter({contact_name: ct_filter, company_name: cpy_filter, contact_email: email_filter }));
contactgrid.refresh();
event.preventDefault();
});
contactgrid.on('dgrid-select', function (event) {
// Report the item from the selected row to the console.
console.log('Row selected: ', event.rows[0].data);
});
contactgrid.on('dgrid-deselect', function (event) {
console.log('Row de-selected: ', event.rows[0].data);
});
contactgrid.on('.dgrid-row:click', function (event) {
var row = contactgrid.row(event);
console.log('Row clicked:', row.data);
});
}
);
</script>
<div class="dijitDialogPaneContentArea" style="width:96%;margin-left:5px">
<form id="filterForm">
<div class="dijitDialogPaneActionBar" >
<button data-dojo-type="dijit.form.Button" type="submit">Filter</button>
<button
data-dojo-type="dijit.form.Button"
data-dojo-attach-point="submitButton"
type="submit"
>
Select
</button>
<button
data-dojo-type="dijit.form.Button"
data-dojo-attach-point="cancelButton"
>
Close
</button>
</div>
<div data-dojo-attach-point="contentNode" >
<input type="text" data-dojo-type="dijit.form.TextBox" name="fcompany_name" id="fcompany_name" style="width:33%">
<input type="text" data-dojo-type="dijit.form.TextBox" name="fcontact_name" id="fcontact_name" style="width:32%">
<input type="text" data-dojo-type="dijit.form.TextBox" name="fcontact_email" id="fcontact_email" style="width:33%">
<div id="contacttable">
</div>
</div>
</form>
</div>
Just found the reason.
the columns need to have a 'id' column called ID. I just change the 'contact_id' column to 'id' and it works fine.
thanks

Uploadifive does not apply on dynamically created INPUT elements

This is my uploadifive setup:
Inside body:
<div id="file_rows_wrapper">
<div class="file_row">
<input class="file_upload" name="file_upload" type="file" multiple="false">
</div>
</div>
Add Another File
While this is the javascript part:
$(function() {
uploadify();
});
function uploadify() {
<?php $timestamp = time();?>
$('.file_upload').uploadifive({
'auto' : true,
'checkScript' : '/files/check_exists',
'formData' : {
'timestamp' : '<?php echo $timestamp;?>',
'token' : '<?php echo md5('hiall' . $timestamp);?>'
},
'queueID' : 'queue',
'uploadScript' : '/files/upload_file',
'multi' : false,
'buttonText' : 'Upload File',
});
};
function add_file()
{
var file = $('.file_row:first').clone();
file.css('margin-top', '20px');
file.fadeIn().appendTo($('#file_rows_wrapper'));
uploadify();
}
All works as expected. The "file_row" div is being cloned but when clicking on the "Add Another File" and choosing the local file, nothing happens. There is no upload. If I maually copy the "file_row" div more times then the upload works fine, even more uploads at once. What am I doing wrong?
I think you need a unique id in your file input to have multiple instances on one page.

Angularjs jQuery FIle Upload

I'm new at Angularjs and I'm trying to create an AngularJS project with jQuery File Upload but I could not distinguish between directives file controllers file and the view.
Can anyone help me by providing me a clear structure of how files should be placed? (controllers, directives, and view)
I wrote something for my very first Angular.js project. It's from before there was an Angular.js example, but if you want to see the hard way, you can have it. It's not the best, but it may be a good place for you to start. This is my directives.js file.
(function(angular){
'use strict';
var directives = angular.module('appName.directives', []);
directives.directive('imageUploader', [
function imageUploader() {
return {
restrict: 'A',
link : function(scope, elem, attr, ctrl) {
var $imgDiv = $('.uploaded-image')
, $elem
, $status = elem.next('.progress')
, $progressBar = $status.find('.bar')
, config = {
dataType : 'json',
start : function(e) {
$elem = $(e.target);
$elem.hide();
$status.removeClass('hide');
$progressBar.text('Uploading...');
},
done : function(e, data) {
var url = data.result.url;
$('<img />').attr('src', url).appendTo($imgDiv.removeClass('hide'));
scope.$apply(function() {
scope.pick.photo = url;
})
console.log(scope);
console.log($status);
$status.removeClass('progress-striped progress-warning active').addClass('progress-success');
$progressBar.text('Done');
},
progress : function(e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$progressBar.css('width', progress + '%');
if (progress === 100) {
$status.addClass('progress-warning');
$progressBar.text('Processing...');
}
},
error : function(resp, er, msg) {
$elem.show();
$status.removeClass('active progress-warning progress-striped').addClass('progress-danger');
$progressBar.css('width', '100%');
if (resp.status === 415) {
$progressBar.text(msg);
} else {
$progressBar.text('There was an error. Please try again.');
}
}
};
elem.fileupload(config);
}
}
}
]);
})(window.angular)
I didn't do anything special for the controller. The only part of the view that matters is this:
<div class="control-group" data-ng-class="{ 'error' : errors.image }">
<label class="control-label">Upload Picture</label>
<div class="controls">
<input type="file" name="files[]" data-url="/uploader" image-uploader>
<div class="progress progress-striped active hide">
<div class="bar"></div>
</div>
<div class="uploaded-image hide"></div>
</div>
</div>

webpart form submit to custom list in sharepoint

Is it possible to create a form visual webpart with fields like name, email, address and submit button. After user submit data should be submitted to sharepoint custom list here custom list will have same fields like name, email, address. I created one custom list.
I search on internet but i didn't find any solutions for that. Also am new to sharepoint. If any one can provide some links it will be helpful.
Thanks
Yes, this is very possible using jQuery and AJAX.
So, lets say that, just to be brief, this is your input:
<input type='text' id='name' />
<input type='submit' id='submitdata' value='submit />
Using jquery, you would do this:
$(function(){
$('#submitdata').click(function(){
//this gets the value from your name input
var name = $('#name').val();
var list = "PutYourListNameHere";
addListItem(name, list);
});
});
function addListItem(name, listname) {
var listType = "PutTheTypeOfListHere";
// Prepping our update & building the data object.
// Template: "nameOfField" : "dataToPutInField"
var item = {
"__metadata": { "type": listType},
"name": name
}
// Executing our add
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
console.log("Success!");
console.log(data); // Returns the newly created list item information
},
error: function (data) {
console.log("Error!");
console.log(data);
}
});
}
This SHOULD work. I am not at work where my SharePoint station is, so if you are still having issues with this, let me know.
You may use SPServices also, It will work
<script type="text/javascript" src="~/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="~/jquery.SPServices-0.7.2.min.js"></script>
HTML
<input type='text' id='name' />
<input type='text' id='email' />
<input type='text' id='mobile' />
<input type='submit' id='submit' value='Submit' />
SPServices
<script type="text/javascript">
$("#submit").click(function(){
var Fname=$("#name").val();
var Email =$("#email").val();
var Mobile =$("#mobile").val();
$().SPServices({
operation: "UpdateListItems",
async: false,
batchCmd: "New",
listName: "YourCustomListName",
valuepairs: [["Fname", Fname], ["Email", Email], ["Mobile", Mobile]], //"Fname","EMail" and "Mobile" are Fields Name of your custom list
completefunc: function(xData, status) {
if (status == "success") {
alert ("Thank you for your inquiry!" );
}
else {
alert ("Unable to submit your request at this time.");
}
}
});
});
</script>

Resources