I am trying to use http://podio.github.com/jquery-mentions-input/ to add the #mentions functionality to my website. I'm trying ajax to get a JSON response from a .php file that queries the database onkeyup, but I don't know where in the code to put the ajax call.
I know I am asking for people to basically do the work for me, but I am dying here, I have been trying this for about 2-3 days now
here are two JavaScript functions from the plugin, I just an example ajax function that would link to my PHP script that searches for users %LIKE% the query.
BASIC EXAMPLE FROM PLUGIN
$(function () {
$('textarea.mention').mentionsInput({
onDataRequest:function (mode, query, callback) {
var data = [
{ id:1, name:'Kenneth Auchenberg', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' },
{ id:2, name:'Jon Froda', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' },
{ id:3, name:'Anders Pollas', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' },
{ id:4, name:'Kasper Hulthin', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' },
{ id:5, name:'Andreas Haugstrup', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' },
{ id:6, name:'Pete Lacey', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' },
{ id:7, name:'kenneth#auchenberg.dk', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' },
{ id:8, name:'Pete Awesome Lacey', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' },
{ id:9, name:'Kenneth Hulthin', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' }
];
data = _.filter(data, function(item) { return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 });
callback.call(this, data);
}
});
$('.get-syntax-text').click(function() {
$('textarea.mention').mentionsInput('val', function(text) {
alert(text);
});
});
$('.get-mentions').click(function() {
$('textarea.mention').mentionsInput('getMentions', function(data) {
alert(JSON.stringify(data));
});
}) ;
});
AJAX EXAMPLE(i don't know how to get the JSON from a .php file)
$(function () {
$('textarea.mention-example2').mentionsInput({
onDataRequest:function (mode, query, callback) {
$.getJSON('assets/data.json', function(responseData) {
responseData = _.filter(responseData, function(item) { return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 });
callback.call(this, responseData);
});
}
});
});
i figured it out, i just added a variable query with the value of query, and sent it to my script, which then searches the db and sends back the result
$('textarea.mention-example2').mentionsInput({
onDataRequest:function (mode, query, callback) {
var myquery = 'query='+query;
$.getJSON('data.php', myquery, function(responseData) {
responseData = _.filter(responseData, function(item) { return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 });
callback.call(this, responseData);
});
}
});
I have read up a bit on the plugin on the Gitpage, I am not sure on what you have, but this is what you need to make it work:
jQuery js file, and the plugin script.
JS Code:
$(function () {
$('textarea.mention-example2').mentionsInput({
onDataRequest:function (mode, query, callback) {
$.getJSON('assets/data.json', function(responseData) {
responseData = _.filter(responseData, function(item) {
return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 }); callback.call(this, responseData);
});
}
});
});
JSON file in the folder assets with the filename data.json 'assets/data.json':
[
{
"id": 1,
"name": "Kenneth Auchenberg",
"avatar": "http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif",
"type": "contact"
}
]
Now all you need is a textarea with the class mention-example2. You might need some css files include aswell. But try this out and come back with feedback.
this is how i did in codeigniter
create a function that will get the data for me
function getDataMention(mode, query, callback){
var path = '<?=site_url()?>users/get_user_search_string/'+query;
$.ajax({
url: path,
dataType: 'json', // Choosing a JSON datatype
}).done(function(retdata) {
var data = retdata;
data = _.filter(data, function(item) {return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 });
callback.call(this, data);
});
}//end getDataMention();
then call the library on document ready
$('textarea.mention').mentionsInput({
onDataRequest:getDataMention,
minChars: 1,
templates:{
wrapper: _.template('<div class="mentions-input-box"></div>'),
autocompleteList: _.template('<div class="mentions-autocomplete-list"></div>'),
autocompleteListItem: _.template('<li data-ref-id="<%= id %>" data-ref-type="<%= type %>" data-display="<%= display %>"><%= content %></li>'),
autocompleteListItemAvatar : _.template('<img src="<%= avatar %>" />'),
autocompleteListItemIcon: _.template('<div class="icon <%= icon %>"></div>'),
mentionsOverlay: _.template('<div class="mentions"><div></div></div>'),
mentionItemSyntax: _.template('#[<%= value %>](<%= type %>:<%= id %>)'),
mentionItemHighlight: _.template('<a target="__blank" class="mlink" href="<?=site_url()?>users/profile/profile_id=<%= id %>"><%= value %></a>')
}
});
Related
I'm creating page in PHP but when I use AJAX to send data, echo function start to printing data in console instead in DOM elements.
I want to add Quagga barcode reader to my page. Quagga is write in JS but my page is in php. So I have to use Ajax to send barcode result to my php code. And there is a problem. After sending data (POST) and using echo to display that on the screen, every data that echo should display are showing up in console. Not only data I send but whole page html code too. Even header('Location: ') doesn't work correctly. Because I'm sending readed code to barcodereaded.php where I put POST data inside SESSION var, and I try to echo that on the screen in different file barcoderesult.php but everytime data is printed in console log in barcode.php (which code is below). On every other subpage php echo and header functions works fine, only this one case causing troubles.
<div id="scanner-container"></div>
<input type="button" id="btn" value="Start/Stop" />
<script src="js/quagga.min.js"></script>
<script>
var _scannerIsRunning = false;
function startScanner() {
var barcode = {};
Quagga.init({
inputStream: {
name: "Live",
type: "LiveStream",
numOfWorkers: navigator.hardwareConcurrency,
target: document.querySelector('#scanner-container'),
constraints: {
size: 1920,
width: 200,
height: 480,
facingMode: "environment"
},
},
config: {
frequency: 5,
},
locator: {
patchSize: "x-large",
},
decoder: {
readers: [
"code_128_reader",
"ean_reader",
"ean_8_reader",
"code_39_reader",
"code_39_vin_reader",
"codabar_reader",
"upc_reader",
"upc_e_reader",
"i2of5_reader"
],
debug: {
showCanvas: true,
showPatches: true,
showFoundPatches: true,
showSkeleton: true,
showLabels: true,
showPatchLabels: true,
showRemainingPatchLabels: true,
boxFromPatches: {
showTransformed: true,
showTransformedBox: true,
showBB: true
}
}
},
}, function (err) {
if (err) {
console.log(err);
return
}
console.log("Initialization finished. Ready to start");
Quagga.start();
// Set flag to is running
_scannerIsRunning = true;
});
Quagga.onProcessed(function (result) {
var drawingCtx = Quagga.canvas.ctx.overlay,
drawingCanvas = Quagga.canvas.dom.overlay;
if (result) {
if (result.boxes) {
drawingCtx.clearRect(0, 0, parseInt(drawingCanvas.getAttribute("width")), parseInt(drawingCanvas.getAttribute("height")));
result.boxes.filter(function (box) {
return box !== result.box;
}).forEach(function (box) {
Quagga.ImageDebug.drawPath(box, { x: 0, y: 1 }, drawingCtx, { color: "green", lineWidth: 2 });
});
}
if (result.box) {
Quagga.ImageDebug.drawPath(result.box, { x: 0, y: 1 }, drawingCtx, { color: "#00F", lineWidth: 2 });
}
if (result.codeResult && result.codeResult.code) {
Quagga.ImageDebug.drawPath(result.line, { x: 'x', y: 'y' }, drawingCtx, { color: 'red', lineWidth: 3 });
}
}
});
Quagga.onDetected(function (result) {
Quagga.stop();
barcode.code = result.codeResult.code;
$.ajax({
url: "barcodereaded.php",
method: "POST",
data: barcode,
success: function(res){
console.log(res);
}
});
});
}
// Start/stop scanner
document.getElementById("btn").addEventListener("click", function () {
if (_scannerIsRunning) {
Quagga.stop();
_scannerIsRunning = false;
} else {
startScanner();
}
}, false);
</script>
I just want to send readed barcode to other file to convert it into data I want to add to database (quantity of elements on the pallet, production date, etc.)
Look at this part of your code :
$.ajax({
url: "barcodereaded.php",
method: "POST",
data: barcode,
success: function(res){
console.log(res);
}
});
The success method tells what to do with the result of your ajax code.
And here you specifically tell to log the response (res) to the console.
Instead you can use the content of res to append it to your dom via your preferred Javascript solution (vanilla, jQuery,...).
With jQuery you could (if the result from your php code is some text):
$('#my-return-container').text(res)
I'm trying to use DataTable to show all fields of my JSON, but I'm not understand how to use it.
I just need how to populate dataset correctly to read data.
<script>
<?php
var jqxhr = $.ajax({url: api_ricerca_ingredienti, type: "GET",dataType: "json", data: {all: 1, ln : "it",completo:"-1",conteggio: 1}} )
var max=json.items.length;
for (i=0;i<max;i++){
var el=json.items[i];
}
$(".risultato_ricerca").click(function() {
carica_ingrediente($(this).attr('data-id'));
});
})
<?php }?>
var dataSet = [
/*HOW?*/
];
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet,
columns: [
{ title: "Nome" },
{ title: "Stato" },
{ title: "Home" },
{ title: "Utente" },
{ title: "Mi piace" },
{ title: "Contributi" }
]
} );
} );
</script>
<table id="example" class="table table-responsive table-hover table-dynamic filter-head"></table>
First, two comments about your code.
As #Patrick Q stated, your PHP tags are useless: you are writing Javascript, PHP is another things that has nothing to do with your code, so remove <?php and <?php }?>
Then, i can't understand this code:
for (i=0;i<max;i++){
var el=json.items[i];
}
This for is completely useless. you cycle through every element in json.items without performing any operation. At the end you just store the last json.items in the el (without even using el in your code).
By the way, your main question:
As said in the official documentation, your dataSet must contain an array for every row of your table in the format:
var dataSet = [
["john","italy","home","john",15,20],
["john","italy","home","john",15,20]
]
This example will create two identical rows with random data inside.
Assuming every item in your json has name country home user likes contribs fields you will need something like that:
var dataSet = [];
for (i=0;i<json.items.length;i++){
var el = [json.items[i].name,json.items[i].country, json.items[i].home, json.items[i].user, json.items[i].likes, json.items[i].contribs]
dataSet[i] = el;
}
Sorry guys. I've truncated my prev code. Now the building of data array works like a charm. I've just a doubt about a console error:
"jquery.dataTables.min.js:5 Uncaught TypeError: Cannot read property 'aDataSort' of undefined"
I can't show my rows. According with your opinion, what's the problem?
Thank you!
<script>
< ?php
if (isset($_GET) && isset($_GET['id'])){
?>
$( document ).ready(function() {
carica_ingrediente('<?php echo $_GET['id'];?>');
});
<?php }else {?>
$('#query').keypress(function(e) {
if (e.keyCode == $.ui.keyCode.ENTER) {
$('#cerca').click();
}
});
$(document).ready(function() {
var jqxhr = $.ajax({url: api_ricerca_ingredienti, type: "GET",dataType: "json", data: {all: 1, ln : "it",completo:"-1",conteggio: 1}} )
.done(function(json) {
if (json.res==0){
alert( "Inserisci una parola per iniziare la ricerca " );
return;
}
var dataSet = [];
for (i=0;i<json.items.length;i++){
var el = [json.items[i].nome,json.items[i].completo, json.items[i].home, json.items[i].utente, json.items[i].likes, json.items[i].countingredienti];
dataSet[i] = el;
console.log(el);
}
$(".risultato_ricerca").click(function() {
carica_ingrediente($(this).attr('data-id'));
});
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet,
columns: [
{ title: "Nome" },
{ title: "Stato" },
{ title: "Home" },
{ title: "Utente" },
{ title: "Mi piace" },
{ title: "Contributi" }
]
} );
} );
})
.fail(function() {
alert( "error" );
});
});
<?php }?>
</script>
I am using PHP at server side to get json formatted output as below. At client side I use jQuery to display the results but it displays null. Please let me know where I went wrong. Any help is appreciated.
PHP
while ($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
echo json_encode($rows);
Output
[
{
"a_name": "affles",
"bname": "bua",
"c_number": "10101010",
"dateandtime": "2013-11-30 17:50:04"
},
{
"a_name": "affles",
"bname": "bua",
"c_number": "10101010",
"dateandtime": "2013-11-30 17:50:04"
},
{
"a_name": "anan",
"bname": "nesh",
"c_number": "2017439441",
"dateandtime": "2013-12-04 17:50:04"
}
]
Client side
$.getJSON("http://apip.com/results.php", function (data) {
$.each(data, function (index, value) {
$('<li>' + value.a_name + '</li>').appendTo('#groups');
});
});
Client side code using JSONP: I modified client side to use JSONP but still it returns null. An help is appreciatd
<script>
(function() {
var flickerAPI = "http://apip.com/results.php?jsoncallback=?";
$.getJSON( flickerAPI,
(function( data ) {
$.each( data.items, function( index, value ) {
$('<li>' + value.a_name + '</li>').appendTo('#groups');
});
});
})();
</script>
As you can see from this fiddle, it is working fine. What I do suspect is going wrong is that you're using http://apip.com/results.php and you might be fooling jQuery into thinking you're doing a cross-domain request (which you might be doing), which is generally prohibited by browsers unless you use JSONP. If you own http://apip.com/, use
$.getJSON("/results.php", function (data) {
$.each(data, function (index, value) {
$('<li>' + value.a_name + '</li>').appendTo('#groups');
});
});
i am trying to create a service for angular which should get the data from a php that generates a json. Right now my service looks like this
fixEvents.service('contactService', function($http, $q) {
this.getallContact = function() {
var json = $q.defer();
$http.get('models/contact.getall.json')
.success(function(data) {
json.resolve(data);
})
.error(function() {
json.reject();
});
return json.promise;
};
});
and my controller looks like this
fixEvents.controller('contactCtrl', function($scope, contactService) {
$scope.title = "CONTACT";
$scope.jsonContact = contactService.getallContact();
$scope.showMessage = function() {
alert($scope.jsonContact.length);
}
});
the problem is my jsonContact does not get any result. It seems to be undefined. Is there something i did wrong? And by the way is there a better way to do this ? Thank you, Daniel!
You have to use .then back in the controller to work with the data:
var jsonContactPromise = contactService.getallContact();
jsonContactPromise.then(function(data) {
$scope.jsonContact = data
}, function(error) {
console.log("ERROR: " + error);
});
I've been trying for days to get this working and I just cannot figure out why when I have my view to destroy a model which belongs to a collection (which properly has a url attribute for the beginning fetch of models' data), only fires the destroy 'event' which is bubbled up to the collection for easy binding by my list view. But it does not ever send an actual DELETE request or any request to the server at all. Everywhere I look, I see everyone using either the collection's url attr, or urlRoot if the model is not connected to a collection. I've even tested before the actual this.model.destroy() to check the model < console.log(this.model.url());
I have not overwritten the destroy nor sync methods for backbone. Also each model does have an id attribute which is populated via the collection's fetch (from database records).
The destroy takes place in the list item view, and the collection's "destroy" event is bound in the list view. All that works well (the event handling), but the problem, again, is there's no request to the server.
I was hoping that backbone.js would do it automatically. That was what the documentation implies, as well as the numerous examples everywhere.
Much thanks to anyone who can give some useful input.
FYI: I'm developing on wampserver PHP 5.3.4.
ListItemView = BaseView.extend({
tagName: "li",
className: "shipment",
initialize: function (options) {
_.bindAll(this);
this.template = listItemTemplate;
this.templateEmpty = listItemTemplateEmpty;
},
events: {
'click .itemTag' : 'toggleData',
'click select option' : 'chkShipper',
'click .update' : 'update',
'click button.delete' : 'removeItem'
},
// ....
removeItem: function() {
debug.log('remove model');
var id = this.model.id;
debug.log(this.model.url());
var options = {
success: function(model, response) {
debug.log('remove success');
//debug.log(model);
debug.log(response);
// this.unbind();
// this.remove();
},
error: function(model, response) {
debug.log('remove error');
debug.log(response);
}
};
this.model.destroy(options);
//model.trigger('destroy', this.model, this.model.collection, options);
}
});
Collection = Backbone.Collection.extend({
model: Model,
url: '?dispatch=get&src=shipments',
url_put : '?dispatch=set&src=shipments',
name: 'Shipments',
initialize: function () {
_.bindAll(this);
this.deferred = new $.Deferred();
/*
this.fetch({
success: this.fetchSuccess,
error: this.fetchError
});
*/
},
fetchSuccess: function (collection, response) {
collection.deferred.resolve();
debug.log(response);
},
fetchError: function (collection, response) {
collection.deferred.reject();
debug.log(response);
throw new Error(this.name + " fetch failed");
},
save: function() {
var that = this;
var proxy = _.extend( new Backbone.Model(),
{
url: this.url_put,
toJSON: function() {
return that.toJSON();
}
});
var newJSON = proxy.toJSON()
proxy.save(
newJSON,
{
success: that.saveSuccess,
error: that.saveError
}
);
},
saveSuccess: function(model, response) {
debug.log('Save successful');
},
saveError: function(model, response) {
var responseText = response.responseText;
throw new Error(this.name + " save failed");
},
updateModels: function(newData) {
//this.reset(newData);
}
});
ListView = BaseView.extend({
tagName: "ul",
className: "shipments adminList",
_viewPointers: {},
initialize: function() {
_.bindAll(this);
var that = this;
this.collection;
this.collection = new collections.ShipmentModel();
this.collection.bind("add", this.addOne);
this.collection.fetch({
success: this.collection.fetchSuccess,
error: this.collection.fetchError
});
this.collection.bind("change", this.save);
this.collection.bind("add", this.addOne);
//this.collection.bind("remove", this.removeModel);
this.collection.bind("destroy", this.removeModel);
this.collection.bind("reset", this.render);
this.collection.deferred.done(function() {
//that.render();
that.options.container.removeClass('hide');
});
debug.log('view pointers');
// debug.log(this._viewPointers['c31']);
// debug.log(this._viewPointers[0]);
},
events: {
},
save: function() {
debug.log('shipments changed');
//this.collection.save();
var that = this;
var proxy = _.extend( new Backbone.Model(),
{
url: that.collection.url_put,
toJSON: function() {
return that.collection.toJSON();
}
});
var newJSON = proxy.toJSON()
proxy.save(
newJSON,
{
success: that.saveSuccess,
error: that.saveError
}
);
},
saveSuccess: function(model, response) {
debug.log('Save successful');
},
saveError: function(model, response) {
var responseText = response.responseText;
throw new Error(this.name + " save failed");
},
addOne: function(model) {
debug.log('added one');
this.renderItem(model);
/*
var view = new SB.Views.TicketSummary({
model: model
});
this._viewPointers[model.cid] = view;
*/
},
removeModel: function(model, response) {
// debug.log(model);
// debug.log('shipment removed from collection');
// remove from server
debug.info('Removing view for ' + model.cid);
debug.info(this._viewPointers[model.cid]);
// this._viewPointers[model.cid].unbind();
// this._viewPointers[model.cid].remove();
debug.info('item removed');
//this.render();
},
add: function() {
var nullModel = new this.collection.model({
"poNum" : null,
"shipper" : null,
"proNum" : null,
"link" : null
});
// var tmpl = emptyItemTmpl;
// debug.log(tmpl);
// this.$el.prepend(tmpl);
this.collection.unshift(nullModel);
this.renderInputItem(nullModel);
},
render: function () {
this.$el.html('');
debug.log('list view render');
var i, len = this.collection.length;
for (i=0; i < len; i++) {
this.renderItem(this.collection.models[i]);
};
$(this.container).find(this.className).remove();
this.$el.prependTo(this.options.container);
return this;
},
renderItem: function (model) {
var item = new listItemView({
"model": model
});
// item.bind('removeItem', this.removeModel);
// this._viewPointers[model.cid] = item;
this._viewPointers[model.cid] = item;
debug.log(this._viewPointers[model.cid]);
item.render().$el.appendTo(this.$el);
},
renderInputItem: function(model) {
var item = new listItemView({
"model": model
});
item.renderEmpty().$el.prependTo(this.$el);
}
});
P.S... Again, there is code that is referenced from elsewhere. But please note: the collection does have a url attribute set. And it does work for the initial fetch as well as when there's a change event fired for saving changes made to the models. But the destroy event in the list-item view, while it does trigger the "destroy" event successfully, it doesn't send the 'DELETE' HTTP request.
Do your models have an ID? If not, the HTTP request won't be sent. –
nikoshr May 14 at 18:03
Thanks so much! Nikoshr's little comment was exactly what I needed. I spent the last 5 hours messing with this. I just had to add an id to the defaults in my model.