I'm getting ExecJS::RuntimeError when i try to start Rails server and the server log gives me the following:
ActionView::Template::Error (delete operand may not be argument or var
(in /home/sergey/Perfecto/arena/app/assets/javascripts/items.js.coffee)):
47: <%= raw flash_messages %>
48: </div>
49:
50: <%= javascript_include_tag "application" %>
51: <%= yield :javascripts %>
52: <%= yield :scripts %>
53: </body>
I found that this error happens because Ubuntu don't have a javascript runtime installed.
Okay. I've installed nodejs v0.6.3 from sources and tried to add gem 'therubyracer' to my Gemfile as it was suggested but the error still apperars.
What have i missed? Thanks in advance.
My items.js.coffee looks like this:
jQuery ->
if $('#main.items_controller.new').length > 0
overlay = null
iconOffsetX = 26
iconOffsetY = 52
disableDraggingFor = (el) ->
el.draggable = false
el.onmousedown = (event) ->
event.preventDefault()
return false
$(".draggable_item, #new_items_queue").disableSelection()
$.each $(".draggable_item"), (i, el) ->
disableDraggingFor(el)
showInfobox = (marker,data) ->
boxText = document.createElement("div")
boxText.style.cssText = "height: 100%; background: url('/images/form.png') no-repeat;"
boxText.innerHTML = '<div id="infoboxContent">' + data + '</div>'
myOptions =
content: boxText
disableAutoPan: false
maxWidth: 0
pixelOffset: new google.maps.Size(-79, -386)
zIndex: 0
boxStyle:
width: "650px"
height: "350px"
closeBoxMargin: "10px"
infoBoxClearance: new google.maps.Size(1, 1)
isHidden: false
pane: "floatPane"
enableEventPropagation: false
ib = new InfoBox(myOptions)
oldDraw = ib.draw
ib.draw = ->
oldDraw.apply(#)
jQuery(ib.div_).hide()
jQuery(ib.div_).fadeIn(900)
$("#item_name").focus()
priceResult = $("#converted_price")
$("#item_price").live "keydown keyup keypress focus blur paste change", ->
fx.base = "USD"
fx.rates =
"KGS": 46.4
input = accounting.unformat $("#item_price").val()
result = accounting.formatMoney fx.convert(input, from: "USD", to: "KGS"),
symbol: "сом"
precision: 0
thousand: " "
format:
pos : "%v %s"
neg : "(%v) %s"
zero: "0 %s"
priceResult.html result
ib.open(Gmaps.map.map, marker)
google.maps.event.addListener marker, 'dragstart', ->
ib.hide()
google.maps.event.addListener marker, 'dragend', ->
newPosition = #getPosition()
$.ajax "/items/reverse_geocode",
type: 'GET'
dataType: 'text'
data:
lat: newPosition.lat()
lng: newPosition.lng()
error: (jqXHR, textStatus, errorThrown) ->
console.log "AJAX Error: #{textStatus}"
success: (data, textStatus, jqXHR) ->
$("#item_location").val data
ib.show()
$('#item_latitude').val newPosition.lat()
$('#item_longitude').val newPosition.lng()
google.maps.event.addListener ib, 'domready', ->
$('#change_position').bind 'click', ->
ib.close()
marker.setAnimation google.maps.Animation.BOUNCE
google.maps.event.addListener marker, 'position_changed', ->
setTimeout (->
ib.open(Gmaps.map.map, marker)
), 300
google.maps.event.addListener ib, 'closeclick', ->
marker.setMap(null)
delete marker
$(".draggable_item").draggable("enable")
placeMarker = (location,icon,shadow,kind) ->
$.ajax "/items/reverse_geocode",
type: 'GET'
dataType: 'text'
data:
lat: location.lat()
lng: location.lng()
onlyCountry: true
error: (jqXHR, textStatus, errorThrown) ->
console.log "AJAX Error: #{textStatus}"
success: (data, textStatus, jqXHR) ->
if data != "Киргизия"
humane "Вы можете добавлять объявления только в Кыргызстане"
else
$(".draggable_item").draggable("disable")
marker = new google.maps.Marker
position: location
map: Gmaps.map.map
icon: icon
shadow: shadow
draggable: true
zIndex: 99
$.ajax "/items/new.js",
type: 'GET'
dataType: 'text'
data:
content: kind
lat: location.lat()
lng: location.lng()
error: (jqXHR, textStatus, errorThrown) ->
console.log "AJAX Error: #{textStatus}"
success: (data, textStatus, jqXHR) ->
showInfobox marker, data
Gmaps.map.callback = ->
#.map.mapTypes.set "OSM", new google.maps.ImageMapType(
getTileUrl: (coord, zoom) ->
"http://192.168.0.112/osm_tiles2/" + zoom + "/" + coord.x + "/" + coord.y + ".png"
tileSize: new google.maps.Size(256, 256)
name: "OpenStreetMap"
maxZoom: 18
)
#.map.setMapTypeId("OSM")
overlay = new google.maps.OverlayView()
overlay.draw = ->
overlay.setMap #.map
$.each $(".draggable_item"), ->
$(#).draggable
cursor: "move",
revert: false,
helper: 'clone',
stop: (event,ui) ->
point = new google.maps.Point ui.offset.left+iconOffsetX,ui.offset.top+iconOffsetY
location = overlay.getProjection().fromContainerPixelToLatLng(point)
placeMarker location, $(#).data('marker'), $(#).data('shadow'), $(#).data('kind')
You have this in your CoffeeScript:
google.maps.event.addListener ib, 'closeclick', ->
marker.setMap(null)
delete marker
$(".draggable_item").draggable("enable")
And the error say this:
delete operand may not be argument or var
If you backtrack through your CoffeeScript from that delete marker, you'll see that marker is an argument and you can't use the JavaScript delete operator on an argument.
You should be able to get rid of that delete marker without causing problems, just the marker.setMap(null) should be enough to make it go away.
Try to add gem "execjs", "~> 1.3.0" at your Gemfile.
I guess it can fix this...
Older thread but I had the same issue as well but solved it by simply renaming my javascript and deleting the '.coffee' at the end of all the file names.
For example:
From:
'name'.js.coffee
to:
'name'.js
For some reason or another this worked.
Related
$('.searchName').autocomplete({
source: function(req, res){
$.ajax({
url: "{{ route('airportSearch') }}",
dataType: "json",
type: "GET",
data: req,
beforeSend: function() {
$('#iconMaps').hide();
$('#loadingMaps').show();
},
success: function (data){
$('#iconMaps').show();
$('#loadingMaps').hide();
res(data);
console.log(data)
},
error: function(err){
$('#iconMaps').show();
$('#loadingMaps').hide();
}
});
}
}).data('ui-autocomplete')._renderItem = function(ul, item) {
return $('<li>')
.data('ui-autocomplete', item)
.append('<span><b>' + item.label + '</b></span><br><span>' + item.value + '</span>')
.appendTo(ul);
}
this my code, i have problem if selected list have error:
Cannot read property 'value' of undefined.
How to resolve this error?
I had a similar issue after updating JQuery version and fixed it applying few changes in data(), like bellow:
.data('uiAutocomplete')._renderItem = function(ul, item) {
return $('<li>')
.data('ui-autocomplete-item', item)
.append('<span><b>' + item.label + '</b></span><br><span>' + item.value + '</span>')
.appendTo(ul);
So I'm using a chart to display the top most common operating systems (e.g. XP, server 2003, etc.) and I'm trying to pull this information from ActiveRecord. I have a Node model that has the operating_system column.
From my show page, this is what I have at the bottom:
var chart = c3.generate({
bindto: '#nodes-os-chart',
title: {
text: 'Top 5 Operating Systems Detected'
},
data: {
columns: [
['Microsoft Windows XP', 10],
['Microsoft Windows Server 2003', 5],
['Microsoft Windows Server 2016', 15]
],
type : 'pie',
onclick: function (d, i) { console.log("onclick", d, i); },
onmouseover: function (d, i) { console.log("onmouseover", d, i); },
onmouseout: function (d, i) { console.log("onmouseout", d, i); }
},
legend: {
position: "right"
}
});
However, I would like to fill in the columns array with some data from ActiveRecord, so I tried turning it into an ajax call, such as this:
var operating_systems = $.ajax({
url: window.location.pathname + "/node_os",
type: 'GET',
dataType: 'json', // added data type
success: function(res) {
console.log(res);
alert(res);
}
});
var chart = c3.generate({
bindto: '#nodes-os-chart',
title: {
text: 'Top 5 Operating Systems'
},
data: {
columns: operating_systems,
type : 'pie',
onclick: function (d, i) { console.log("onclick", d, i); },
onmouseover: function (d, i) { console.log("onmouseover", d, i); },
onmouseout: function (d, i) { console.log("onmouseout", d, i); }
},
legend: {
position: "right"
}
});
I added a route for get 'node_os' to map back to the necessary controller. However, now in the controller, this is the method I have defined for node_os:
# GET /logs/4/node_os
def node_os
return ['Test1','Test2']
end
Test1 and Test2 are just samples, but I'm trying to figure out the best way to do this. I get a pop up that says "Undefined" when I try to run this in the browser.
Solved this using this: https://medium.com/#ryannovas/pass-a-nested-array-from-rails-to-js-41f021eef459.
Basically my show.html.erb just makes the AJAX call and the rest happens in the js.erb file.
I am try to draw simple chart using this code:
:coffee
requestData = () ->
$.ajax
url: "#{ build_chart_data_track_url(#track.id) }"
type: "GET"
dataType: "json"
success: (data, textStatus, jqXHR) ->
chart.addSeries({
type: 'spline',
name: "Price",
data: data.price,
connectEnds: false,
color: 'orange',
});
chart = Highcharts.chart 'chart',
chart:
zoomType: 'x'
events:
load: requestData
title:
text: "some text"
But I see strange lines when data is absent (or something else?). How I can disable it and leave only one line with my data?
Solved. The issue was in Ajax loaded data format.
I'm a hobbyist developer. I'm using basic Select2 ajax in a new/edit Rails form, and I can't figure out how to re-populate it in the edit form. song_creditor_1 is a string, but it's entered as an id of Fan model.
form:
<%= f.input :song_creditor_1, label: 'Song Creditor 1', as: :select, input_html: { id: "song_creditor_1", include_hidden: false } %>
script
function templateDropDownFormat (item) {
return item.text;
}
function templateSelectionFormat (item) {
return item.text;
}
$("#song_creditor_1").select2({
placeholder: "Search",
ajax: {
url: "/songs",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: $.map(data, function(cnut) {
return {
text: cnut.name + ", " + cnut.city + ", " + cnut.country + " (" + cnut.account_type + ")",
id: cnut.id,
};
}),
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: templateDropDownFormat, // omitted for brevity, see the source of this page
templateSelection: templateSelectionFormat// omitted for brevity, see the source of this page
});
Well, I'm just a hobbyist, and this is my first website, so this answer isn't pretty but it's how I resolved it. The issue was having to re-populate the data in the field if there was an error on the form, so I just pulled that particular attribute out during the 'create' and called it #creditor1.
var $select1 = $('#song_creditor_1');
function templateDropDownFormat (item) {
return item.text;
}
function templateSelectionFormat (item) {
return item.text;
}
$select1.select2({
ajax: {
url: "/songs",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: $.map(data, function(cnut) {
return {
text: cnut.name + ", " + cnut.city + ", " + cnut.country + " (" + cnut.account_type + ")",
id: cnut.id,
};
}),
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: templateDropDownFormat, // omitted for brevity, see the source of this page
templateSelection: templateSelectionFormat// omitted for brevity, see the source of this page
});
<% if params[:action] === "edit" && #creditor1_real || params[:action] === "update" && #creditor1_real %>
var $option1 = $('<option selected><%= #creditor1_real.name %>, <%= #creditor1_real.city %>, <%= #creditor1_real.country %></option>').val("<%= #creditor1_real.id %>");
$select1.append($option1).trigger('change');
<% elsif params[:action] === "create" && #creditor1 || params[:action] === "new" && #creditor1 %>
var $option1 = $('<option selected><%= #creditor1.name %>, <%= #creditor1.city %>, <%= #creditor1.country %></option>').val("<%= #creditor1.id %>");
$select1.append($option1).trigger('change');
<% else %>
var $option1 = $('<option selected>Search</option>');
$select1.append($option1).trigger('change');
<% end %>
for me, i found solution to just find and plucking model in select options, while keeping the ajax source on js side
<%= f.select :song_creditor_1, Song.where(song_id: song.id).pluck(:song_name, :id), {}, class: 'your-select-2-class' %>
you can select all from your model, but in my case it slowing page load
I want to delete the image via Ajax.
I'm using Paperclip for the upload.
I learned that for deleting the image all I have to do is to set it to nil.
Example:
#meth.picture = nil # this works
Error msg:
Paperclip::AdapterRegistry::NoHandlerError (No handler found for "nil"):
app/controllers/meths_controller.rb:116:in `block in update'
app/controllers/meths_controller.rb:115:in `update'
code:
$(function() {
$('#delete_image').on("click", function() {
$('#image > img').remove();
//console.log("??");
var url = document.URL.split("/");
var meth_id = url[4];
console.log(meth_id);
$.ajax({
url: '/Methoden/'+meth_id,
type: 'PATCH',
dataType: 'json',
data: {"meth": {"picture": "nil"}},
complete: function (jqXHR, textStatus) {
},
success: function (data, textStatus, jqXHR) {
console.log(" ?? profit");
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
});
});
With the help from Зелёный, I did the following:
data: {"meth": "delete_image"}
Then in my controller update method:
if params[:meth] == "delete_image"
#meth.picture = nil
#meth.save
end
Problem is what you pass string ((No handler found for "nil")) to the method #meth.picture.
Send instead "nil" something like "delete" or "clear" and check in controller if params[:meth] == "delete" do #meth.picture = nil else do something other.