Why is my Ajax cannot save data into database? Laravel with Ajax - javascript

I am trying to save data using ajax. The ajax is inside my javascript file and passed to my controller and route. However the issue is it cannot save the data into my database.
Here is my jquery.hotspot.js file that include ajax:
(function ($) {
var defaults = {
// Object to hold the hotspot data points
data: [],
// Element tag upon which hotspot is (to be) build
tag: 'img',
// Specify mode in which the plugin is to be used
// `admin`: Allows to create hotspot from UI
// `display`: Display hotspots from `data` object
mode: 'display',
// HTML5 LocalStorage variable where hotspot data points are (will be) stored
LS_Variable: '__HotspotPlugin_LocalStorage',
// CSS class for hotspot data points
hotspotClass: 'HotspotPlugin_Hotspot',
// CSS class which is added when hotspot is to hidden
hiddenClass: 'HotspotPlugin_Hotspot_Hidden',
// Event on which the hotspot data point will show up
// allowed values: `click`, `hover`, `none`
interactivity: 'hover',
// Action button CSS classes used in `admin` mode
save_Button_Class: 'HotspotPlugin_Save',
remove_Button_Class: 'HotspotPlugin_Remove',
send_Button_Class: 'HotspotPlugin_Send',
// CSS class for hotspot data points that are yet to be saved
unsavedHotspotClass: 'HotspotPlugin_Hotspot_Unsaved',
// CSS class for overlay used in `admin` mode
hotspotOverlayClass: 'HotspotPlugin_Overlay',
// Enable `ajax` to read data directly from server
ajax: false,
ajaxOptions: { url: '' },
listenOnResize: true,
// Hotspot schema
schema: [
{
'property': 'Title',
'default': ''
},
{
'property': 'Message',
'default': ''
}
]
};
// Constructor
function Hotspot(element, options) {
var widget = this;
// Overwriting defaults with options
this.config = $.extend(true, {}, defaults, options);
this.element = element;
// `tagElement`: element for which hotspots are being done
this.tagElement = element.find(this.config.tag);
// Register event listeners
$.each(this.config, function (index, fn) {
if (typeof fn === 'function') {
widget.element.on(index + '.hotspot', function (event, err, data) {
fn(err, data);
});
}
});
if (this.config.mode != 'admin' && this.config.listenOnResize) {
$(window).on('resize', function () {
$(element).find('.' + widget.config.hotspotClass).remove();
widget.init();
});
}
if (this.config.tag !== 'img') {
widget.init();
return;
}
if (this.tagElement.prop('complete')) {
widget.init();
} else {
this.tagElement.one('load', function (event) {
widget.init();
});
}
}
Hotspot.prototype.init = function () {
this.parseData();
// Fetch data for `display` mode with `ajax` enabled
if (this.config.mode != 'admin' && this.config.ajax) {
this.fetchData();
}
// Nothing else to do here for `display` mode
if (this.config.mode != 'admin') {
return;
}
this.setupWorkspace();
};
Hotspot.prototype.createId = function () {
var id = "";
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < 7; i++) {
id += letters.charAt(Math.floor(Math.random() * letters.length));
}
return id;
};
Hotspot.prototype.setupWorkspace = function () {
var widget = this;
// `data` array: to contain hotspot objects
var data = [];
var tHeight = $(widget.tagElement[0]).height(),
tWidth = $(widget.tagElement[0]).width(),
tOffset = widget.tagElement.offset(),
pHeight = $(widget.element[0]).height(),
pWidth = $(widget.element[0]).width(),
pOffset = widget.element.offset();
// Create overlay for the tagElement
$('<span/>', {
html: '<p>Click this Panel to Store Messages</p>'
}).css({
'height': (tHeight / pHeight) * 100 + '%',
'width': (tWidth / pWidth) * 100 + '%',
'left': (tOffset.left - pOffset.left) + 'px',
'top': (tOffset.top - pOffset.top) + 'px'
}).addClass(widget.config.hotspotOverlayClass).appendTo(widget.element);
// Handle click on overlay mask
this.element.delegate('span', 'click', function (event) {
event.preventDefault();
event.stopPropagation();
// Get coordinates
var offset = $(this).offset(),
relativeX = (event.pageX - offset.left),
relativeY = (event.pageY - offset.top);
var height = $(widget.tagElement[0]).height(),
width = $(widget.tagElement[0]).width();
var hotspot = { x: relativeX / width * 100, y: relativeY / height * 100 };
var schema = widget.config.schema;
for (var i = 0; i < schema.length; i++) {
var val = schema[i];
var fill = prompt('Please enter ' + val.property, val.default);
if (fill === null) {
return;
}
hotspot[val.property] = fill;
}
data.push(hotspot);
// Temporarily display the spot
widget.displaySpot(hotspot, true);
});
// Register admin controls
var button_id = this.createId();
$('<button/>', {
text: "Save data"
}).prop('id', ('save' + button_id)).addClass(this.config.save_Button_Class).appendTo(this.element);
$('<button/>', {
text: "Remove data"
}).prop('id', ('remove' + button_id)).addClass(this.config.remove_Button_Class).appendTo(this.element);
$(this.element).delegate('button#' + ('save' + button_id), 'click', function (event) {
event.preventDefault();
event.stopPropagation();
widget.saveData(data);
data = [];
});
$(this.element).delegate('button#' + ('remove' + button_id), 'click', function (event) {
event.preventDefault();
event.stopPropagation();
widget.removeData();
});
if (this.config.ajax) {
$('<button/>', {
text: "Send to server"
}).prop('id', ('send' + button_id)).addClass(this.config.send_Button_Class).appendTo(this.element);
$(this.element).delegate('button#' + ('send' + button_id), 'click', function (event) {
event.preventDefault();
event.stopPropagation();
widget.sendData();
});
}
};
Hotspot.prototype.fetchData = function () {
var widget = this;
// Fetch data from a server
var options = {
data: {
HotspotPlugin_mode: "Retrieve"
}
};
$.ajax($.extend({}, this.config.ajaxOptions, options))
.done(function (data) {
// Storing in localStorage
localStorage.setItem(widget.config.LS_Variable, data);
widget.parseData();
})
.fail($.noop);
};
Hotspot.prototype.parseData = function () {
var widget = this;
var data = this.config.data,
data_from_storage = localStorage.getItem(this.config.LS_Variable);
if (data_from_storage && (this.config.mode === 'admin' || !this.config.data.length)) {
data = JSON.parse(data_from_storage);
}
$.each(data, function (index, hotspot) {
widget.displaySpot(hotspot);
});
};
Hotspot.prototype.displaySpot = function (hotspot, unsaved) {
var widget = this;
var spot_html = $('<div/>');
$.each(hotspot, function (index, val) {
if (typeof val === "string") {
$('<div/>', {
html: val
}).addClass('Hotspot_' + index).appendTo(spot_html);
}
});
var height = $(this.tagElement[0]).height(),
width = $(this.tagElement[0]).width(),
offset = this.tagElement.offset(),
parent_offset = this.element.offset();
var spot = $('<div/>', {
html: spot_html
}).css({
'top': (hotspot.y * height / 100) + (offset.top - parent_offset.top) + 'px',
'left': (hotspot.x * width / 100) + (offset.left - parent_offset.left) + 'px'
}).addClass(this.config.hotspotClass).appendTo(this.element);
if (unsaved) {
spot.addClass(this.config.unsavedHotspotClass);
}
if (this.config.interactivity === 'hover') {
return;
}
// Overwrite CSS rule for `none` & `click` interactivity
spot_html.css('display', 'block');
// Initially keep hidden
if (this.config.interactivity !== 'none') {
spot_html.addClass(this.config.hiddenClass);
}
if (this.config.interactivity === 'click') {
spot.on('click', function (event) {
spot_html.toggleClass(widget.config.hiddenClass);
});
} else {
spot_html.removeClass(this.config.hiddenClass);
}
};
Hotspot.prototype.saveData = function (data) {
if (!data.length) {
return;
}
// Get previous data
var raw_data = localStorage.getItem(this.config.LS_Variable);
var hotspots = [];
if (raw_data) {
hotspots = JSON.parse(raw_data);
}
// Append to previous data
$.each(data, function (index, node) {
hotspots.push(node);
});
this.data=data;
$.ajax({
type:"POST",
url:"/store",
dataType:'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data:{
Title:$('#Title').val(),
Message: $('#Message').val(),
x:$('#relativeX').val(),
y: $('#relativeY').val(),
},
success: function(data){
console.log(data,d);
},
error: function(data)
{
console.log(data);
},
});
localStorage.setItem(this.config.LS_Variable, JSON.stringify(hotspots));
this.element.trigger('afterSave.hotspot', [null, hotspots]);
};
Hotspot.prototype.removeData = function () {
if (localStorage.getItem(this.config.LS_Variable) === null) {
return;
}
if (!confirm("Are you sure you wanna do everything?")) {
return;
}
localStorage.removeItem(this.config.LS_Variable);
this.element.trigger('afterRemove.hotspot', [null, 'Removed']);
};
Hotspot.prototype.sendData = function () {
if (localStorage.getItem(this.config.LS_Variable) === null || !this.config.ajax) {
return;
}
var widget = this;
var options = {
data: {
HotspotPlugin_data: localStorage.getItem(this.config.LS_Variable),
HotspotPlugin_mode: "Store"
}
};
$.ajax($.extend({}, this.config.ajaxOptions, options))
.done(function () {
widget.element.trigger('afterSend.hotspot', [null, 'Sent']);
})
.fail(function (err) {
widget.element.trigger('afterSend.hotspot', [err]);
});
};
$.fn.hotspot = function (options) {
new Hotspot(this, options);
return this;
};
}(jQuery));
Here is my route:
Route::get('hotspots','ImageController#getPin');
Route::post('store','ImageController#storePin')->name('store.storePin');
Here is my ImageController.php:
public function getPin()
{
$pin= Pin::select('Title','Message','x','y');
return hotspot::of($pin)->make(true);
}
public function storePin(Request $request)
{
$validation = Validator::make($request->all(), [
'Title' => 'required',
'Message' => 'required',
'x'=>'required',
'y'=>'required',
]);
if ($request->get('save','button_id') == "insert")
{
$pin = new Pin();
$pin->Title=$request->Title;
$pin->Message= $request->Message;
$pin->x = $request->relativeX;
$pin->y =$request->relativeY;
$pin->save();
//return Request::json($request);
}
}
Here is my hotspot.blade.php:
<!DOCTYPE html>
<html>
<head>
<title>Picomment Hotspot</title>
<link rel="stylesheet" type="text/css" href="{{ asset ('css/bootsrap.min.css') }}">
<script type="text/javascript" src="{{ asset ('js/jquery.min.js') }}"></script>
<link rel="stylesheet" type="text/css" href="{{ asset ('css/jquery.hotspot.css') }}">
<link rel="stylesheet" type="text/css" href="{{ asset ('css/style.css') }}">
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<div class="container">
<div class="col-md-6" style="margin-top: 40px;">
<div id="theElement-a">
<img src="{{ asset('storage/'.$files) }}" alt="" title="">
</div>
</div>
</div>
<script type="text/javascript" src="{{ asset ('js/jquery.hotspot.js') }}"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#theElement-a").hotspot({
mode: "admin",
// uncomment
/*ajax: true,
ajaxOptions: {
'url': 'links.to.server'
},*/
interactivity: "click",
LS_Variable: "HotspotPlugin-a",
afterSave: function(err, data) {
if (err) {
console.log('Error occurred', err);
return;
}
alert('Saved');
// `data` in json format can be stored
// & passed in `display` mode for the image
localStorage.clear();
console.log(data);
},
afterRemove: function(err, message) {
if (err) {
console.log('Error occurred', err);
return;
}
alert(message);
window.location.reload();
},
afterSend: function(err, message) {
if (err) {
console.log('Error occurred', err);
return;
}
alert(message);
}
});
});
</script>
</body>
</html>

Related

Return text when checkbox selected

In my site, I have a form that users can click on a checkbox to select "available". I want to have "Yes" or "No" returned in the displayArticle function based on whether the box is checked or not. Right now it returns True or False, which is not optimal. How can I code this?
Here is my entire JS code:
App = {
web3Provider: null,
contracts: {},
account: 0x0,
loading: false,
init: function() {
return App.initWeb3();
},
initWeb3: function() {
// initialize web3
if(typeof web3 !== 'undefined') {
//reuse the provider of the Web3 object injected by Metamask
App.web3Provider = web3.currentProvider;
} else {
//create a new provider and plug it directly into our local node
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
}
web3 = new Web3(App.web3Provider);
App.displayAccountInfo();
return App.initContract();
},
displayAccountInfo: function() {
web3.eth.getCoinbase(function(err, account) {
if(err === null) {
App.account = account;
$('#account').text(account);
web3.eth.getBalance(account, function(err, balance) {
if(err === null) {
$('#accountBalance').text(web3.fromWei(balance, "ether") + " ETH");
}
})
}
});
},
initContract: function() {
$.getJSON('RentalContract.json', function(chainListArtifact) {
//added May24 to json file name
// get the contract artifact file and use it to instantiate a truffle contract abstraction
App.contracts.RentalContract = TruffleContract(chainListArtifact);
// set the provider for our contracts
App.contracts.RentalContract.setProvider(App.web3Provider);
// listen to events
App.listenToEvents();
// retrieve the article from the contract
return App.reloadArticles();
});
},
reloadArticles: function() {
//avoid reentry bugs
if(App.loading){
return;
}
App.loading = true;
// refresh account information because the balance might have changed
App.displayAccountInfo();
var chainListInstance;
App.contracts.RentalContract.deployed().then(function(instance) {
chainListInstance = instance;
return chainListInstance.getArticlesForSale();
}).then(function(articlesIds) {
// retrieve the article placeholder and clear it
$('#articlesRow').empty();
for(var i = 0; i < articlesIds.length; i++){
var articleId = articlesIds[i];
chainListInstance.articles(articleId.toNumber()).then(function(article){
App.displayArticle(article[0], article[1], article[3], article[4], article[5], article[6], article[7]);
});
}
App.loading = false;
}).catch(function(err) {
console.error(err.message);
App.loading = false;
});
},
//displayArticle: function(id, seller, beds, baths, propaddress, rental_price, property_type, description, available, contact_email) {
displayArticle: function(id, seller, propaddress, rental_price, description, available, contact) {
var articlesRow = $('#articlesRow');
//var etherPrice = web3.fromWei(price, "ether");
var articleTemplate = $("#articleTemplate");
//articleTemplate.find('.panel-title').text(propaddress);
//articleTemplate.find('.beds').text(beds);
//articleTemplate.find('.baths').text(baths);
articleTemplate.find('.propaddress').text(propaddress);
articleTemplate.find('.rental_price').text('$' + rental_price);
//articleTemplate.find('.property_type').text(property_type);
articleTemplate.find('.description').text(description);
articleTemplate.find('.available').text(available);
articleTemplate.find('.contact').text(contact);
// articleTemplate.find('.article_price').text(etherPrice + " ETH");
articleTemplate.find('.btn-buy').attr('data-id', id);
// articleTemplate.find('.btn-buy').attr('data-value', etherPrice);
//seller
if(seller == App.account){
articleTemplate.find('.article-seller').text("You");
articleTemplate.find('.btn-buy').hide();
}else{
articleTemplate.find('.article-seller').text(seller);
articleTemplate.find('.btn-buy').show();
}
//add this new article
articlesRow.append(articleTemplate.html());
},
sellArticle: function() {
// retrieve the detail of the article
// var _article_name = $('#article_name').val();
var _description = $('#description').val();
//var _beds = $('#beds').val();
//var _baths = $('#baths').val();
var _propaddress = $('#propaddress').val();
var _rental_price = $('#rental_price').val();
//var _property_type = $('#property_type').val();
var _available = $('#available').val();
var _contact = $('#contact').val();
// var _article_price = $('#article_price').val();
// var _price = web3.toWei(parseFloat($('#article_price').val() || 0), "ether");
// if((_description.trim() == '') || (rental_price == 0)) {
// nothing to sell
// return false;
// }
App.contracts.RentalContract.deployed().then(function(instance) {
//return instance.sellArticle(_description, _beds, _baths, _propaddress, _rental_price, _property_type, _available, _contact_email, {
return instance.sellArticle(_propaddress, _rental_price, _description, _available, _contact,{
from: App.account,
gas: 500000
});
}).then(function(result) {
}).catch(function(err) {
console.error(err);
});
},
// listen to events triggered by the contract
listenToEvents: function() {
App.contracts.RentalContract.deployed().then(function(instance) {
instance.LogSellArticle({}, {}).watch(function(error, event) {
if (!error) {
$("#events").append('<li class="list-group-item">' + event.args._propaddress + ' is now for sale</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
instance.LogBuyArticle({}, {}).watch(function(error, event) {
if (!error) {
$("#events").append('<li class="list-group-item">' + event.args._buyer + ' bought ' + event.args._propaddress + '</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
});
},
buyArticle: function() {
event.preventDefault();
// retrieve the article price and data
var _articleId = $(event.target).data('id');
var _price = parseFloat($(event.target).data('value'));
App.contracts.RentalContract.deployed().then(function(instance){
return instance.buyArticle(_articleId, {
from: App.account,
value: web3.toWei(_price, "ether"),
gas: 500000
});
}).catch(function(error) {
console.error(error);
});
}
};
$(function() {
$(window).load(function() {
App.init();
});
});
If I understand what you're trying to do, perhaps this will work for you.
var isChecked = '';
if (articleTemplate.find('.available').checked === true)
{ isChecked = 'yes'} else
{ isChecked = 'no'}
.
.
.
return isChecked;
Do this:
articleTemplate.find( '.available' ).text( available ? 'Yes' : 'No' );
Example:
function returnValue() {
$( '#val' ).text( $( '#chk' ).is( ':checked' ) ? 'Yes' : 'No' )
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="chk" onclick="returnValue()" />
<label for="chk">Available</label>
<h2 id="val"></h2>

How to use the points which come from the leaflet file layer plugin?

/*
* Load files *locally* (GeoJSON, KML, GPX) into the map
* using the HTML5 File API.
*
* Requires Mapbox's togeojson.js to be in global scope
* https://github.com/mapbox/togeojson
*/
(function (factory, window) {
// define an AMD module that relies on 'leaflet'
if (typeof define === 'function' && define.amd && window.toGeoJSON) {
define(['leaflet'], function (L) {
factory(L, window.toGeoJSON);
});
} else if (typeof module === 'object' && module.exports) {
// require('LIBRARY') returns a factory that requires window to
// build a LIBRARY instance, we normalize how we use modules
// that require this pattern but the window provided is a noop
// if it's defined
module.exports = function (root, L, toGeoJSON) {
if (L === undefined) {
if (typeof window !== 'undefined') {
L = require('leaflet');
} else {
L = require('leaflet')(root);
}
}
if (toGeoJSON === undefined) {
if (typeof window !== 'undefined') {
toGeoJSON = require('togeojson');
} else {
toGeoJSON = require('togeojson')(root);
}
}
factory(L, toGeoJSON);
return L;
};
} else if (typeof window !== 'undefined' && window.L && window.toGeoJSON) {
factory(window.L, window.toGeoJSON);
}
}(function fileLoaderFactory(L, toGeoJSON) {
var FileLoader = L.Class.extend({
includes: L.Mixin.Events,
options: {
layer: L.geoJson,
layerOptions: {},
fileSizeLimit: 1024
},
initialize: function (map, options) {
this._map = map;
L.Util.setOptions(this, options);
this._parsers = {
geojson: this._loadGeoJSON,
json: this._loadGeoJSON,
gpx: this._convertToGeoJSON,
kml: this._convertToGeoJSON
};
},
load: function (file, ext) {
var parser,
reader;
// Check file is defined
if (this._isParameterMissing(file, 'file')) {
return false;
}
// Check file size
if (!this._isFileSizeOk(file.size)) {
return false;
}
// Get parser for this data type
parser = this._getParser(file.name, ext);
if (!parser) {
return false;
}
// Read selected file using HTML5 File API
reader = new FileReader();
reader.onload = L.Util.bind(function (e) {
var layer;
try {
this.fire('data:loading', { filename: file.name, format: parser.ext });
layer = parser.processor.call(this, e.target.result, parser.ext);
this.fire('data:loaded', {
layer: layer,
filename: file.name,
format: parser.ext
});
} catch (err) {
this.fire('data:error', { error: err });
}
}, this);
// Testing trick: tests don't pass a real file,
// but an object with file.testing set to true.
// This object cannot be read by reader, just skip it.
if (!file.testing) {
reader.readAsText(file);
}
// We return this to ease testing
return reader;
},
loadMultiple: function (files, ext) {
var readers = [];
if (files[0]) {
files = Array.prototype.slice.apply(files);
while (files.length > 0) {
readers.push(this.load(files.shift(), ext));
}
}
// return first reader (or false if no file),
// which is also used for subsequent loadings
return readers;
},
loadData: function (data, name, ext) {
var parser;
var layer;
// Check required parameters
if ((this._isParameterMissing(data, 'data'))
|| (this._isParameterMissing(name, 'name'))) {
return;
}
// Check file size
if (!this._isFileSizeOk(data.length)) {
return;
}
// Get parser for this data type
parser = this._getParser(name, ext);
if (!parser) {
return;
}
// Process data
try {
this.fire('data:loading', { filename: name, format: parser.ext });
layer = parser.processor.call(this, data, parser.ext);
this.fire('data:loaded', {
layer: layer,
filename: name,
format: parser.ext
});
} catch (err) {
this.fire('data:error', { error: err });
}
},
_isParameterMissing: function (v, vname) {
if (typeof v === 'undefined') {
this.fire('data:error', {
error: new Error('Missing parameter: ' + vname)
});
return true;
}
return false;
},
_getParser: function (name, ext) {
var parser;
ext = ext || name.split('.').pop();
parser = this._parsers[ext];
if (!parser) {
this.fire('data:error', {
error: new Error('Unsupported file type (' + ext + ')')
});
return undefined;
}
return {
processor: parser,
ext: ext
};
},
_isFileSizeOk: function (size) {
var fileSize = (size / 1024).toFixed(4);
if (fileSize > this.options.fileSizeLimit) {
this.fire('data:error', {
error: new Error(
'File size exceeds limit (' +
fileSize + ' > ' +
this.options.fileSizeLimit + 'kb)'
)
});
return false;
}
return true;
},
_loadGeoJSON: function _loadGeoJSON(content) {
var layer;
if (typeof content === 'string') {
content = JSON.parse(content);
}
layer = this.options.layer(content, this.options.layerOptions);
if (layer.getLayers().length === 0) {
throw new Error('GeoJSON has no valid layers.');
}
if (this.options.addToMap) {
layer.addTo(this._map);
}
return layer;
},
_convertToGeoJSON: function _convertToGeoJSON(content, format) {
var geojson;
// Format is either 'gpx' or 'kml'
if (typeof content === 'string') {
content = (new window.DOMParser()).parseFromString(content, 'text/xml');
}
geojson = toGeoJSON[format](content);
return this._loadGeoJSON(geojson);
}
});
var FileLayerLoad = L.Control.extend({
statics: {
TITLE: 'Load local file (GPX, KML, GeoJSON)',
LABEL: '⌅'
},
options: {
position: 'topleft',
fitBounds: true,
layerOptions: {},
addToMap: true,
fileSizeLimit: 1024
},
initialize: function (options) {
L.Util.setOptions(this, options);
this.loader = null;
},
onAdd: function (map) {
this.loader = L.Util.fileLoader(map, this.options);
this.loader.on('data:loaded', function (e) {
// Fit bounds after loading
if (this.options.fitBounds) {
window.setTimeout(function () {
map.fitBounds(e.layer.getBounds());
}, 500);
}
}, this);
// Initialize Drag-and-drop
this._initDragAndDrop(map);
// Initialize map control
return this._initContainer();
},
_initDragAndDrop: function (map) {
var callbackName;
var thisLoader = this.loader;
var dropbox = map._container;
var callbacks = {
dragenter: function () {
map.scrollWheelZoom.disable();
},
dragleave: function () {
map.scrollWheelZoom.enable();
},
dragover: function (e) {
e.stopPropagation();
e.preventDefault();
},
drop: function (e) {
e.stopPropagation();
e.preventDefault();
thisLoader.loadMultiple(e.dataTransfer.files);
map.scrollWheelZoom.enable();
}
};
for (callbackName in callbacks) {
if (callbacks.hasOwnProperty(callbackName)) {
dropbox.addEventListener(callbackName, callbacks[callbackName], false);
}
}
},
_initContainer: function () {
var thisLoader = this.loader;
// Create a button, and bind click on hidden file input
var fileInput;
var zoomName = 'leaflet-control-filelayer leaflet-control-zoom';
var barName = 'leaflet-bar';
var partName = barName + '-part';
var container = L.DomUtil.create('div', zoomName + ' ' + barName);
var link = L.DomUtil.create('a', zoomName + '-in ' + partName, container);
link.innerHTML = L.Control.FileLayerLoad.LABEL;
link.href = '#';
link.title = L.Control.FileLayerLoad.TITLE;
// Create an invisible file input
fileInput = L.DomUtil.create('input', 'hidden', container);
fileInput.type = 'file';
fileInput.multiple = 'multiple';
if (!this.options.formats) {
fileInput.accept = '.gpx,.kml,.geojson';
} else {
fileInput.accept = this.options.formats.join(',');
}
fileInput.style.display = 'none';
// Load on file change
fileInput.addEventListener('change', function () {
thisLoader.loadMultiple(this.files);
// reset so that the user can upload the same file again if they want to
this.value = '';
}, false);
L.DomEvent.disableClickPropagation(link);
L.DomEvent.on(link, 'click', function (e) {
fileInput.click();
e.preventDefault();
});
return container;
}
});
L.Util.FileLoader = FileLoader;
L.Util.fileLoader = function (map, options) {
return new L.Util.FileLoader(map, options);
};
L.Control.FileLayerLoad = FileLayerLoad;
L.Control.fileLayerLoad = function (options) {
return new L.Control.FileLayerLoad(options);
};
}, window));
<!DOCTYPE html>
<html lang="en">
<head>
<title>Leaflet Filelayer </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/4.2.0/normalize.min.css">
<link rel="stylesheet" href="https://unpkg.com/leaflet#0.7.7/dist/leaflet.css">
<link rel="stylesheet" href="style.css">
<script src="https://unpkg.com/leaflet#1.2.0/dist/leaflet.js"></script>
<script src="https://unpkg.com/togeojson#0.14.2"></script>
<script src="https://unpkg.com/leaflet-filelayer#0.6.0"></script>
<script src="me.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="menu.js"></script>
<script src="index.js"></script>
</head>
<body>
<header>
<h1>A Visual Isarithmic Mapping Tool For Online Maps</h1>
<div id="controls" class="bar"></div>
<button class="menu-toggle">
<span class="bar"></span>
<span class="bar"></span>
<span class="bar"></span>
</button>
</header>
<main>
<div id="map" style="width: 100%; height: 100%; display: block;"></div>
</main>
<script>
var points = data:loaded;
L.geoJson(points).addTo(map);
</script>
</body>
</html>
I am using leaflet file layer plugin.I have added a kml file which includes some points. I want to do sth by using these points. But I don't know if the plugin saves this data or not. How can I use these points?
https://github.com/makinacorpus/Leaflet.FileLayer/issues/24
In the link you can see what I mentioned.

Jquery Apprise Plugin not working properly

here is my problem :)
i try to add "Apprise-v2" plugin to my website,
i include both files, css and js, this way :
<!--TOP OF MY PAGE-->
<html>
<body>
<link rel="stylesheet" type="text/css" href="css/apprise-v2.css"/>
<!--MY PAGE CONTENTS...-->
...........
<!--BOTTOM OF MY PAGE-->
<script src="js/jquery-1.10.2.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/raphael-min.js"></script>
<script src="js/tablesorter/jquery.tablesorter.js"></script>
<script src="js/tablesorter/tables.js"></script>
<script type="text/javascript" src="JS/jquery.fancybox.js"></script>
<script type="text/javascript" src="JS/jquery.fancybox.pack.js"></script>
<script src='js/apprise-v2.js'></script>
<script>Apprise("test");</script>
</body>
</html>
my firebug warns me with this :
TypeError: $Apprise is null
if($Apprise.is(':visible')) {
Thanks for help! :)
EDIT : Here is the apprise-v2.js file contents :
// Global Apprise variables
var $Apprise = null,
$overlay = null,
$body = null,
$window = null,
$cA = null,
AppriseQueue = [];
// Add overlay and set opacity for cross-browser compatibility
$(function() {
$Apprise = $('<div class="apprise">');
$overlay = $('<div class="apprise-overlay">');
$body = $('body');
$window = $(window);
$body.append( $overlay.css('opacity', '.94') ).append($Apprise);
});
function Apprise(text, options) {
// Restrict blank modals
if(text===undefined || !text) {
return false;
}
// Necessary variables
var $me = this,
$_inner = $('<div class="apprise-inner">'),
$_buttons = $('<div class="apprise-buttons">'),
$_input = $('<input type="text">');
// Default settings (edit these to your liking)
var settings = {
animation: 700, // Animation speed
buttons: {
confirm: {
action: function() { $me.dissapear(); }, // Callback function
className: null, // Custom class name(s)
id: 'confirm', // Element ID
text: 'Ok' // Button text
}
},
input: false, // input dialog
override: true // Override browser navigation while Apprise is visible
};
// Merge settings with options
$.extend(settings, options);
// Close current Apprise, exit
if(text=='close') {
$cA.dissapear();
return;
}
// If an Apprise is already open, push it to the queue
if($Apprise.is(':visible')) {
AppriseQueue.push({text: text, options: settings});
return;
}
// Width adjusting function
this.adjustWidth = function() {
var window_width = $window.width(), w = "20%", l = "40%";
if(window_width<=800) {
w = "90%", l = "5%";
} else if(window_width <= 1400 && window_width > 800) {
w = "70%", l = "15%";
} else if(window_width <= 1800 && window_width > 1400) {
w = "50%", l = "25%";
} else if(window_width <= 2200 && window_width > 1800) {
w = "30%", l = "35%";
}
$Apprise.css('width', w).css('left', l);
};
// Close function
this.dissapear = function() {
$Apprise.animate({
top: '-100%'
},
settings.animation, function() {
$overlay.fadeOut(300);
$Apprise.hide();
// Unbind window listeners
$window.unbind("beforeunload");
$window.unbind("keydown");
// If in queue, run it
if(AppriseQueue[0]) {
Apprise(AppriseQueue[0].text, AppriseQueue[0].options);
AppriseQueue.splice(0,1);
}
});
return;
};
// Keypress function
this.keyPress = function() {
$window.bind('keydown', function(e) {
// Close if the ESC key is pressed
if(e.keyCode===27) {
if(settings.buttons.cancel) {
$("#apprise-btn-" + settings.buttons.cancel.id).trigger('click');
} else {
$me.dissapear();
}
} else if(e.keyCode===13) {
if(settings.buttons.confirm) {
$("#apprise-btn-" + settings.buttons.confirm.id).trigger('click');
} else {
$me.dissapear();
}
}
});
};
// Add buttons
$.each(settings.buttons, function(i, button) {
if(button) {
// Create button
var $_button = $('<button id="apprise-btn-' + button.id + '">').append(button.text);
// Add custom class names
if(button.className) {
$_button.addClass(button.className);
}
// Add to buttons
$_buttons.append($_button);
// Callback (or close) function
$_button.on("click", function() {
// Build response object
var response = {
clicked: button, // Pass back the object of the button that was clicked
input: ($_input.val() ? $_input.val() : null) // User inputted text
};
button.action( response );
//$me.dissapear();
});
}
});
// Disabled browser actions while open
if(settings.override) {
$window.bind('beforeunload', function(e){
return "An alert requires attention";
});
}
// Adjust dimensions based on window
$me.adjustWidth();
$window.resize( function() { $me.adjustWidth() } );
// Append elements, show Apprise
$Apprise.html('').append( $_inner.append('<div class="apprise-content">' + text + '</div>') ).append($_buttons);
$cA = this;
if(settings.input) {
$_inner.find('.apprise-content').append( $('<div class="apprise-input">').append( $_input ) );
}
$overlay.fadeIn(300);
$Apprise.show().animate({
top: '20%'
},
settings.animation,
function() {
$me.keyPress();
}
);
// Focus on input
if(settings.input) {
$_input.focus();
}
} // end Apprise();
Make call after page loaded.
$(function() {
Apprise('hi there');
});
I think using Apprise V3 is a better idea.
https://github.com/exis9/Apprise_V3

Ad Block Plus Blocking jQuery Script?

I have a script that pulls data from my CMS and then allows a person to vote on a poll. The script works fine. However, I have Ad Block Plus Plugin installed in Firefox. When that is enabled to blocks the script from submitting the form correctly. It appears to submit correctly in the front end but is never registered in the back end.
Why does Ad Block Plus block my script that has nothing to do with ads?
The script is below:
$(document).ready(function () {
var Engine = {
ui: {
buildChart: function() {
if ($("#pieChart").size() === 0) {
return;
}
var pieChartData = [],
totalVotes = 0,
$dataItems = $("ul.key li");
// grab total votes
$dataItems.each(function (index, item) {
totalVotes += parseInt($(item).data('votes'));
});
// iterate through items to draw pie chart
// and populate % in dom
$dataItems.each(function (index, item) {
var votes = parseInt($(item).data('votes')),
votePercentage = votes / totalVotes * 100,
roundedPrecentage = Math.round(votePercentage * 10) / 10;
$(this).find(".vote-percentage").text(roundedPrecentage);
pieChartData.push({
value: roundedPrecentage,
color: $(item).data('color')
});
});
var ctx = $("#pieChart").get(0).getContext("2d");
var myNewChart = new Chart(ctx).Pie(pieChartData, {});
}, // buildChart
pollSubmit: function() {
if ($("#pollAnswers").size() === 0) {
return;
}
var $form = $("#pollAnswers"),
$radioOptions = $form.find("input[type='radio']"),
$existingDataWrapper = $(".web-app-item-data"),
$webAppItemName = $existingDataWrapper.data("item-name"),
$formButton = $form.find("button"),
bcField_1 = "CAT_Custom_1",
bcField_2 = "CAT_Custom_2",
bcField_3 = "CAT_Custom_3",
$formSubmitData = "";
$radioOptions.on("change", function() {
$formButton.removeAttr("disabled"); // enable button
var chosenField = $(this).data("field"), // gather value
answer_1 = parseInt($existingDataWrapper.data("answer-1")),
answer_2 = parseInt($existingDataWrapper.data("answer-2")),
answer_3 = parseInt($existingDataWrapper.data("answer-3"));
if (chosenField == bcField_1) {
answer_1 = answer_1 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
if (chosenField == bcField_2) {
answer_2 = answer_2 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
if (chosenField == bcField_3) {
answer_3 = answer_3 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
prepForm($formSubmitData);
});
function prepForm(formSubmitData) {
$formButton.click(function(e) {
e.preventDefault();
logAnonUserIn("anon", "anon", formSubmitData); // log user in
}); // submit
} // prepForm
function logAnonUserIn(username, password, formSubmitData) {
$.ajax({
type: 'POST',
url: '/ZoneProcess.aspx?ZoneID=-1&Username=' + username + '&Password=' + password,
async: true,
beforeSend: function () {},
success: function () {},
complete: function () {
fireForm(formSubmitData);
}
});
} // logAnonUserIn
function fireForm(formSubmitData) {
// submit the form
var url = "/CustomContentProcess.aspx?A=EditSave&CCID=13998&OID=3931634&OTYPE=35";
$.ajax({
type: 'POST',
url: url,
data: formSubmitData,
async: true,
success: function () {},
error: function () {},
complete: function () {
window.location = "/";
}
});
}
} // pollSubmit
} // end ui
};
Engine.ui.buildChart();
Engine.ui.pollSubmit();
});
As it turns out easylist contains this filter:
.aspx?zoneid=
This is why my script is being blocked.
I was told I can try this exception filter:
##||example.com/ZoneProcess.aspx?*$xmlhttprequest
I could also ask easylist to add an exception.
Answer comes from Ad Block Plus Forums.

scroll display pagination with knockout js

I would like to use knockout js to enable scroll pagination
Problem
I would like to pass in url and id into my `GetPage(controller, id#, page#))
Currently it is hard coded but i would like to change that.
Knockout js
$.views.Roster.GetPage = function (url, id, pageNumber) {
$.grain.Ajax.Get({
Url: url,
SectionID: {id:id},
DataToSubmit: { pageNumber: pageNumber, id: id },
DataType: "json",
OnSuccess: function (data, status, jqXHR) {
$.views.Roster.RosterViewModel.AddUsers(data);
}
});
};
Next = function () {
var _page = $.views.Roster.ViewModel.CurrentPage() + 1;
$.views.Roster.ViewModel.CurrentPage(_page);
$.views.Roster.GetPage("/api/Roster", 9, _page);
}
Scroll pagination
$(document).ready(function(){
$('#main').scroll(function () {
if ($('#main').scrollTop() >= $(document).height() - $('#main').height()) {
$('#status').text('Loading more items...' + $.views.Roster.ViewModel.TotalRoster());
if ($.views.Roster.ViewModel.RosterUsers() == null ) {
$('#status').hide();
$('#done').text('No more items...'),
$('#main').unbind('scroll');
}
setTimeout(updateStatus, 2500);
}
//updateStatus();
});
});
Change the data in getRoster function to what your server function is expecting for you to return the data. Also, remove the code $.views.Roster.GetRoster, it is not required anymore. Now when you do ko.applyBindings(new $.views.Roster.RosterViewModel()); you should get the first page of data, subsequently, when you scroll, the next() call on the view model will continue paging. That logic is all you.
$.views.Roster.RosterViewModel = function (data) {
var self = this;
self.RosterUsers = ko.observableArray([]);
_rosterUsers = self.RosterUsers;
self.currentPage = ko.observable(1);
self.toDisplay = ko.observable(10);
var filteredRoster = ko.computed(function(){
var init = (self.currentPage()-1)* self.toDisplay(),
filteredList = [],
rosterLength = self.RosterUsers().length,
displayLimit = self.toDisplay();
if(rosterLength == 0)
return[];
for(var i = init; i<(displayLimit + init) && i<rosterLength; i++)
{
filteredList.push(self.RosterUsers()[i]);
}
return filteredList;
}),
totalRoster = ko.computed(function () {
return self.RosterUsers().length;
}),
changePage = function (data) {
self.currentPage(data);
},
next = function () {
if ((self.currentPage() * self.toDisplay()) > self.RosterUsers().length)
return;
self.currentPage(self.currentPage() + 1);
},
prev = function () {
if (self.currentPage() === 1)
return;
self.currentPage(self.currentPage() - 1);
},
getRoster = ko.computed(function () {
var data = {
currentPage: self.currentPage(),
pageSize: self.toDisplay()
},
$promise = _makeRequest(data);
$promise.done(function (data) {
var localArray = [];
ko.utils.arrayForEach(data, function(d){
localArray.push(new $.views.Roster.UserViewModel(d));
});
self.RosterUsers.push.apply(self.RosterUsers,localArray);
});
}),
_makeRequest = function(data){
return $.getJSON('your url here', data);
};
};

Categories