I'm playing around with this demo app https://github.com/kagemusha/ember-rails-devise-demo that uses Ember to create a JavaScript implemenation of Devise registration for Rails. The app uses CoffeeScript. I converted it to JavaScript using the compiler on the coffeescript.org website, but now I'm getting these unexpected token and string errors.I'm very inexperienced with Ember and don't know how to make heads or tails of this error messages.
For example, at the top of the settings file, the code does this memoization check (syntax same for both the coffeescript and JavaScript version)
App.urls ||= {}
Which triggers this error when I load the app.
Uncaught SyntaxError: Unexpected token = :3000/assets/settings.js?body=1:1
Same thing happens with the same type of code in the authentications_helper file
App.Authentication ||= {}
Which triggers this error
Uncaught SyntaxError: Unexpected token = authentication_helper.js:1
However, it also obviously affects the rest of the code in the authentication_helper file. When I try to register, I click a link in a template
{{view App.MenuItem href="#/registration" label="Register"}}
which calls the register function in the App.RegistrationRoute
App.RegistrationRoute = Ember.Route.extend({
model: function() {
Ember.Object.create();
},
actions: {
register: function() {
log.info("Registering...");
App.Authentication.register(this);
},
which tries to trigger this register function in the authentication_helper file (the file with the App.Authentication ||= {} at the top), but I'm getting an
Uncaught TypeError: Cannot call method 'register' of undefined
I'm guessing this App.Authentication isn't defined because of the error relating to the unexpecting = in the caching function.
Have I given you enough code to help me make some progress on these errors?
App.Authentication.register = function(route) {
$.ajax({
url: App.urls.register,
type: "POST",
data: {
"user[name]": route.currentModel.name,
"user[email]": route.currentModel.email,
"user[password]": route.currentModel.password,
"user[password_confirmation]": route.currentModel.password_confirmation
},
success: function(data) {
App.currentUser = data.user;
App.LoginStateManager.transitionTo("authenticated");
route.transitionTo('home');
},
error: function(jqXHR, textStatus, errorThrown) {
route.controllerFor('registration').set("errorMsg", "That email/password combo didn't work. Please try again");
}
});
};
App.urls ||= {} is not valid JS, so I suspect that your coffee script has not been translated to JS correctly. You're right that App.Authentication is not defined and is causing your other problems. The JS translation of App.urls ||= {} would be App.urls = App.urls || {}.
Related
I have all the objects from my db rendered on my template by an ajax function.
Near every object there's a button that should delete it from the db but since I'm working on Django it raise a csrf_token missing or incorrect error.
I'm not using a form so I don't know how to include the csrf_token.
var $orders = $('#orders')
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:8000/MyApp/list-api/?format=json',
success: function(orders) {
$.each(orders, function(i, order){
$orders.append('<li>name: '+order.name+', drink:
'+order.drink+'</li>')
$orders.append("<button data-id=" +(order.pk)+"
class='remove'>X</button>")
});
},
error: function() {
alert('errore caricamento ordini');
}
});
$orders.delegate('.remove', 'click', function(){
$.ajax({
type: 'DELETE',
url: 'http://127.0.0.1:8000/MyApp/list-api/' +
$(this).attr('data-id')
});
});
When I press a remove button a new request appears in the network panel of the browser, the response states :detail: "CSRF Failed: CSRF token missing or incorrect." The console gives a 403 forbidden error.
Any help or hints are really appreciated.
I would like to display an error message when the server responses with record not found.
The model in the route handler:
model: function(userLoginToken) {
var userLoginToken= this.store.createRecord('userLoginToken');
return userLoginToken;
},
The action:
actions: {
sendOTP: function(userLoginToken) {
var thisObject = this;
var model=this.currentModel;
this.store.findRecord('user-login-token', userLoginToken.get('mobileNumber')).then(function(response) {
//thisObject.get('controller').set('model', response);
},
function(error) {
//thisObject.get('controller').set('model', error);
//alert("model======== "+model.get('errors'));
});
},
The template is not displaying any error message.
The template:
{{#each model.errors.messages as |message|}}
<div class="errors">
{{message}}
</div>
{{/each}}
Unfortunately, the error message doesn't appear.
Ember depends on an DS.error object, in order to get errors from your models the response has to fulfill the requirements. In order to get Ember to recognize an valid error, in Ember 2.x the error code MUST be 422 and has to follow jsonapi http://jsonapi.org/format/#errors-processing
If you want to catch the errors from the backend response you have to use the catch method:
this.store.findRecord('user-login-token', userLoginToken.get('mobileNumber'))
.then(success => {
// Do whatever you need when the response success
})
.catch(failure => {
// Do whatever you need when the response fails
})
},
For catching the errors automatically as you are doing in your template, your backend needs to response in the right way. I would suggest you to read the answer for this SO question.
When loading my webpage, I get the following errors:
Error: [ng:areq] Argument 'LFSTD' is not a function, got undefined
Uncaught ReferenceError: controller is not defined
The webpage i'm loading has the ng-app attribute in the body tag, and a Ionic tag has the ng-controller:
<body ng-app="ia">
[...]
<ion-side-menu-content ng-controller="LFSTD">
"ia" and "LFSTD" are both defined in app.js. The webpage does load the following static files correctly
This is app.js:
angular.module('ia', ['ionic'])
.run(function ($ionicPlatform) {
$ionicPlatform.ready(function () {
controller('LFSTD', function($scope, $ionicSideMenuDelegate) {
$scope.toggleLeft = function() {
$ionicSideMenuDelegate.toggleLeft();
};
});
});
})
I've been struggling with this, lurking stackoverflow and ionic/angular docs for quite a while. It might be worth saying that my project uses Django. Any idea what might be causing these errors?
Solution
angular
.module('ia', ['ionic'])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'create.html',
controller: 'LFSTD'
})
}
.run(function ($ionicPlatform) {
$ionicPlatform.ready(function () {
controller('LFSTD', function($scope, $ionicSideMenuDelegate) {
$scope.toggleLeft = function() {
$ionicSideMenuDelegate.toggleLeft();
};
});
});
})
I was missing the .controller part in app.js. I thought I could include controllers in a function, but no. It needs to be directly after the angular.module. See updated question.
I'm using django 1.5 + Mezzanine + django-ajax-upload-widget. I have the problem with the django-ajax-upload-widget.
So, when I trying to choose file in form I have an upload error. As I undestand (by using js debugger) - the problem is that jQuery use error handler to handle successful response.
So here is the view, which process ajax uploading:
#csrf_exempt
#require_POST
def upload(request):
form = UploadedFileForm(data=request.POST, files=request.FILES)
if form.is_valid():
uploaded_file = form.save()
data = {'path': uploaded_file.file.url,}
return HttpResponse(simplejson.dumps(data))
else:
return HttpResponseBadRequest(simplejson.dumps({'errors': form.errors}))
I also tried python debugger, so file uploading cause running of this line:
return HttpResponse(simplejson.dumps(data))
So, it means that file uploaded successfuly (I also checked destination folder - it contains this file). Using HttpResponse means that status of request is 200, as I understand. So, jQuery run error handler instead of success. So. it means that the problem may appear when jQuery try to process data, but here is js code:
$.ajax(this.$element.data('upload-url'), {
iframe: true,
files: this.$element,
processData: false,
type: 'POST',
dataType: 'json',
success: function(data) { self.uploadDone(data); },
error: function(data) { self.uploadFail(data); }
});
So, processData: false and here is no proccessing.
How do you think - what may cause the problem? And how to fix it?
ADDITION:
I changed error handler to
AjaxUploadWidget.prototype.uploadFail = function(jqXHR, textStatus, errorThrown){
if(this.options.onError) {
this.options.onError.call(this);
} else {
console.log('Upload failed:');
console.log(jqXHR, textStatus, errorThrown);
}
};
So, js console shows that it is "parsererror".
Problem SOLVED
I try to console.log(jqXHR.responseText); in error handler and see the following:
if (window.top.ripple) { window.top.ripple("bootstrap").inject(window, document); }{"path": "/static/media/ajax_uploads/c351360b8aa7417b89f51cdd9e9057ae-Koala.jpg"}
But I MUST see just this:
{"path": "/static/media/ajax_uploads/c351360b8aa7417b89f51cdd9e9057ae-Koala.jpg"}
So, I turn off Ripple plugin in my Chrome and all works fine o_O :-)
But it's very strange that some plugin can break the work of frontend js. Do you have any thoughts on this?
I started playing a bit with Sencha Touch.
So I've built a really simple application based on one of the examples just to see how it goes.
Basically it creates a JSON Request which executes a Last.FM web service to get music events near the user's location.
Here's the JSON code:
var makeJSONPRequest = function() {
Ext.util.JSONP.request({
url: 'http://ws.audioscrobbler.com/2.0/',
params: {
method: 'geo.getEvents',
location: 'São+Paulo+-+SP',
format: 'json',
callback: 'callback',
api_key: 'b25b959554ed76058ac220b7b2e0a026'
},
callback: function(result) {
var events = result.data.events;
if (events) {
var html = tpl.applyTemplate(events);
Ext.getCmp('content').update(html);
}
else {
alert('There was an error retrieving the events.');
}
Ext.getCmp('status').setTitle('Events in Sao Paulo, SP');
}
})
};
But every time I try to run it, I get the following exception:
Uncaught SyntaxError: Unexpected token :
Anyone has a clue?
A couple of things. First of all the "Uncaught SyntaxError: Unexpected token :" means the browser javascript engine is complaining about a colon ":" that has been put in the wrong place.
The problem will most likely be in the returned JSON. Since whatever the server returns will be run though the eval("{JSON HTTP RESULT}") function in javascript, the most likely thing is that your problem is in there somewhere.
I've put your code on a little sencha test harness and found a couple of problems with it.
First: My browser was not too happy with the "squiggly ã" in location: 'São+Paulo+-+SP', so I had to change this to location: 'Sao+Paulo,+Brazil', which worked and returned the correct results from the audioscribbler API.
Second: I notice you added a callback: 'callback', line to your request parameters, which changes the nature of the HTTP result and returns the JSON as follows:
callback({ // a function call "callback(" gets added here
"events":{
"event":[
{
"id":"1713341",
"title":"Skank",
"artists":{
"artist":"Skank",
"headliner":"Skank"
},
// blah blah more stuff
"#attr":{
"location":"Sao Paulo, Brazil",
"page":"1",
"totalpages":"1",
"total":"2"
}
}
}) // the object gets wrapped with extra parenthesis here
Instead of doing that I think you should be using the callbackKey: 'callback' that comes with the example in http://dev.sencha.com/deploy/touch/examples/ajax/index.js.
Something like this for example:
Ext.util.JSONP.request({
url: 'http://ws.audioscrobbler.com/2.0/',
params: {
method: 'geo.getEvents',
location: 'Sao+Paulo,+Brazil',
format: 'json',
api_key: 'b25b959554ed76058ac220b7b2e0a026'
},
callbackKey: 'callback',
callback: function(result) {
// Output result to console (Firebug/Chrome/Safari)
console.log(result);
// Handle error logic
if (result.error) {
alert(result.error)
return;
}
// Continue your code
var events = result.data.events;
// ...
}
});
That worked for me so hopefully it'll work for you too. Cherio.