Angular get request within rails app not working - ajax

I'm trying to make (my first) angular get request within a rails app to one of my routes. I'm not sure why this is returning nothing, not even an error.
function accomplishmentController($scope, $http) {
$scope.$apply(function() {
$http({method: 'GET', url: '/api/users'}).
success(function(data, status, headers, config) {
console.log("hell0");
}).
error(function(data, status, headers, config) {
console.log("error");
});
});
$scope.accomplishments = [];
$scope.submit = function() {
$scope.accomplishments.unshift({ name: $scope.newAccomp, count: 0 });
$scope.newAccomp = '';
}
$scope.addToCount = function() {
var currentcount = this.accomp.count;
this.accomp.count = currentcount + 1;
}
$scope.delete = function() {
index = this.$index;
$scope.accomplishments.splice(index, 1)
}
}

Related

How can I handle a ajax request response in the Flux Architecture?

Looking at the Flux Documentation I can't figure out how the code to a ajax update, and a ajax fetch would fit into the dispatcher, store, component architecture.
Can anyone provide a simple, dummy example, of how an entity of data would be fetched from the server AFTER page load, and how this entity would be pushed to the server at a later date. How would the "complete" or "error" status of request be translated and treated by the views/components? How would a store wait for the ajax request to wait? :-?
Is this what you are looking for?
http://facebook.github.io/react/tips/initial-ajax.html
you can also implement a fetch in the store in order to manage the information.
Here is an example (it is a concept, not actually working code):
'use strict';
var React = require('react');
var Constants = require('constants');
var merge = require('react/lib/merge'); //This must be replaced for assign
var EventEmitter = require('events').EventEmitter;
var Dispatcher = require('dispatcher');
var CHANGE_EVENT = "change";
var data = {};
var message = "";
function _fetch () {
message = "Fetching data";
$.ajax({
type: 'GET',
url: 'Url',
contentType: 'application/json',
success: function(data){
message = "";
MyStore.emitChange();
},
error: function(error){
message = error;
MyStore.emitChange();
}
});
};
function _post (myData) {
//Make post
$.ajax({
type: 'POST',
url: 'Url',
// post payload:
data: JSON.stringify(myData),
contentType: 'application/json',
success: function(data){
message = "";
MyStore.emitChange();
},
error: function(error){
message = "update failed";
MyStore.emitChange();
}
});
};
var MyStore = merge(EventEmitter.prototype, {
emitChange: function () {
this.emit(CHANGE_EVENT);
},
addChangeListener: function (callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function (callback) {
this.removeListener(CHANGE_EVENT, callback);
},
getData: function (){
if(!data){
_fetch();
}
return data;
},
getMessage: function (){
return message;
},
dispatcherIndex: Dispatcher.register( function(payload) {
var action = payload.action; // this is our action from handleViewAction
switch(action.actionType){
case Constants.UPDATE:
message = "updating...";
_post(payload.action.data);
break;
}
MyStore.emitChange();
return true;
})
});
module.exports = MyStore;
Then you need to subscribe your component to the store change events
var React = require('react');
var MyStore = require('my-store');
function getComments (){
return {
message: null,
data: MyStore.getData()
}
};
var AlbumComments = module.exports = React.createClass({
getInitialState: function() {
return getData();
},
componentWillMount: function(){
MyStore.addChangeListener(this._onChange);
},
componentWillUnmount: function(){
MyStore.removeChangeListener(this._onChange);
},
_onChange: function(){
var msg = MyStore.getMessage();
if (!message){
this.setState(getData());
} else {
this.setState({
message: msg,
data: null
});
}
},
render: function() {
console.log('render');
return (
<div>
{ this.state.message }
{this.state.data.map(function(item){
return <div>{ item }</div>
})}
</div>
);
}
});
I hope it is clear enough.

I cannot send data from Angular to Django using $http

I'm trying to set up a form which add a new object to db but first I want to check something and set up the server side for new record, but I'm frozen :(
Here is my code, please give it a try:
ctrl
subtitlesApp.controller('AddSubtitleController',
function($scope, addSubtitle) {
$scope.saveSubtitle = function(subtitle, addSubtitleForm) {
if (addSubtitleForm.$valid) {
var x = addSubtitle.getTitle(subtitle.imdb_id);
}
};
});
service
subtitlesApp.factory('addSubtitle', ['$http', function ($http) {
return {
getTitle: function(imdb_id) {
$http({
method: 'POST',
url:'add_subtitle/',
data: imdb_id,
})
.success(function(data, status, headers, config) {
console.log(data);
}).error(function(data, status, headers, config) {
console.log(imdb_id+'eror')
});
}
}
}]);
And here's what I'm getting when I print request.POST:
<QueryDict: {}>
You should let the service return a promise
subtitlesApp.factory('addSubtitle', ['$http', function ($http) {
return {
getTitle: function(imdb_id) {
var promise = $http({
method: 'POST',
url:'add_subtitle/',
data: imdb_id,
})
.success(function(data, status, headers, config) {
console.log(data);
}).error(function(data, status, headers, config) {
console.log(imdb_id+'eror')
});
return promise;
}
}
}]);
When consume the service
var x;
if (addSubtitleForm.$valid) {
addSubtitle.getTitle(subtitle.imdb_id).then(function(data){
x = data;
});
}

AngularJS - Strange behaviour of promises in connection with notify()

As I want to implement a chat in AngularJS, I want to use the promise/deferred principle. My ChatService looks like the following:
factory('ChatService', ['$q', '$resource', function($q, $resource) {
var Service = {};
var connected = false;
var connection;
var chatResource = $resource('/guitars/chat/:action', {action: '#action'}, {
requestChatroomId: {
params: {
action: 'requestChatroomId'
},
method: 'GET'
},
sendMessage: {
params: {
action: 'sendMessage'
},
method: 'POST'
}
});
Service.connect = function(cb) {
var deferred = $q.defer();
chatResource.requestChatroomId(function(data) {
connection = new WebSocket('ws://127.0.0.1:8888/realtime/' + data.chatroomId);
connection.onerror = function (error) {
deferred.reject('Error: ' + error);
};
connection.onmessage = function (e) {
cb.call(this, e.data);
deferred.notify(e.data);
};
connected = true;
});
return deferred.promise;
};
Service.sendMessage = function(msg) {
if(!connected) {
return;
}
chatResource.sendMessage({message: msg});
}
return Service;
}])
My controller using the ChatService is:
app.controller('ChatCtrl', ['$scope', 'ChatService', function($scope, ChatService) {
$scope.chat = {};
$scope.chat.conversation = [];
var $messages = ChatService.connect(function(message) {
$scope.$apply(function() {
// #1 THIS FIRES EVERY TIME
$scope.chat.conversation.push(message);
});
});
$messages.then(function(message) {
console.log('Finishes - should never occur!')
}, function(error) {
console.log('An error occurred!')
}, function(message) {
// #2 THIS FIRES ONLY IF THERE IS AN INTERACTION WITH THE ANGULAR MODEL
console.log(message);
});
$scope.sendMessage = function(event) {
ChatService.sendMessage($scope.chat.message);
$scope.chat.message = '';
};
}]);
If something is pushed from the server, callback #1 is called, but callback #2 wont be called until there is some interaction with the angular-model, i.e. start writing something in the input-Box. What is the reason for that behaviour?
Okay the reason was, that AngularJS was not aware of a change. So I injected the $rootScope to my ChatService:
factory('ChatService', ['$q', '$resource', '$rootScope', function($q, $resource, $rootScope) {
and in connection.onmessage I called $apply() on $rootScope:
connection.onmessage = function (e) {
deferred.notify(e.data);
$rootScope.$apply();
};

IE not reading GET success after POST

I cannot seem to find out why IE does not read my success on get after the post. I have tried cache: false, with no luck. This works in all other browsers, just not IE.
$.ajaxSetup({ cache: false });
num = $('#num').val();
phone = $('#phone').val();
$.post("post.php?"+$("#MYFORM").serialize(), {
}, function(response){
if(response==1 && codeVal == 1 && telVal == 1)
{
$("#after_submit").html('');
$("#Send").after('<label class="success" id="after_submit">Η αποστολή πραγματοποιήθηκε</label>');
change_captcha();
clear_form();
$.ajax({
type:'get',
cache: false,
url: "http://web.somesite/submit_code.php",
dataType: 'html',
data:{ user: "one", pass: "mtwo", source: "WEB", receipt: num, msisdn: phone},
success: function(data) {
var qsFull = "http://web.somesite.gr/submit_code.php?" + data;
var qs = URI(qsFull).query(true);
TINY.box.show({html:qs.message,animate:false,boxid:'error',top:5});
}
});
}
else
{
$("#after_submit").html('');
$("#Send").after('<label class="error" id="after_submit">Error! in CAPTCHA .</label>');
}
});
OK, I tried adding an error after the success and I see that I get my pop up as I should be, but the value of qs.message is 0. Why would I get error and not success, when it is successful in other browsers.
I found the answer, It has to do with IE not being flexible with cross domains and such, so I added a XDomainRequest like so
if (jQuery.browser.msie && window.XDomainRequest) {
var xdr = new XDomainRequest();
var my_request_data = { user: "M1web", pass: "m!", source: "WEB", receipt: num, msisdn: phone};
my_request_data = $.param(my_request_data);
if (xdr) {
xdr.onerror = function () {
alert('xdr onerror');
};
xdr.ontimeout = function () {
alert('xdr ontimeout');
};
xdr.onprogress = function () {
alert("XDR onprogress");
alert("Got: " + xdr.responseText);
};
xdr.onload = function() {
//alert('onload ' + xdr.responseText);
var qsFull = "http://web.web.gr/submit_code.php?" + xdr.responseText;
var qs = URI(qsFull).query(true);
TINY.box.show({html:qs.message,animate:false,boxid:'error',top:5});
callback(xdr.responseText);
};
xdr.timeout = 5000;
xdr.open("get", "http://web.web.gr/submit_code.php?" + my_request_data);
xdr.send();
} else {
}
}
I unfortunately had to do a crash course in legacy IE behavior, and this post was very helpful. Here are some other links to help those having to deal with these issues:
Microsoft's Documentation of their XDomainRequest object
An internal blog post covering some of XDomainRequest's idiosyncrasies
Here's a function I use as a fallback where necessary:
// This is necessary due to IE<10 having no support for CORS.
function fallbackXDR(callObj) {
if (window.XDomainRequest) {
var xdrObj = new XDomainRequest();
xdrObj.timeout = callObj.timeout;
xdrObj.onload = function() {
handleSuccess(xdrObj.responseText);
};
xdrObj.onerror = function() {
handleError(xdrObj);
};
xdrObj.ontimeout = function() {
callObj.xdrAttempts = callObj.xdrAttempts++ || 1;
if (callObj.xdrAttempts < callObj.maxAttempts) {
fallbackXDR(callObj);
}
};
xdrObj.onprogress = function() {
// Unfortunately this has to be included or it will not work in some cases.
};
// Use something other than $.param() to format the url if not using jQuery.
var callStr = callObj ? '?'+$.param(callObj.urlVars) : '';
xdrObj.open("get", callObj.url+callStr);
xdrObj.send();
} else {
handleError("No XDomainRequest available.", callObj);
}
}//fallbackXDR()

Backbone collection fetch error with no information

I have a strange problem with the fetch of a backbone collection I am working with. In one particular instance of my code I perform a fetch (exactly how I do it in other areas of the code which all work fine), the fetch never seems to make it to the server and the developer tools shows the request as red with the word (canceled) in the status/text field.
I've walked this through into the backbone sync method and I see the $.ajax being built and everything looks fine. Has anyone run into this problem?
here is my code if it helps, this is a function that calls two .ashx services to first check for a file's existence then to open it. The part that isn't working for me is the "me.collection.fetch().
openDocument: function () {
var me = this,
fileId = me.model.get('id'),
userId = Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
fileRequest = '/genericHandlers/DownloadFile.ashx?id=' + fileId + '&userId=' + userId,
fileCheck = '/genericHandlers/CheckFileExistance.ashx?id=' + fileId + '&userId=' + userId;
//hide tooltip
me.hideButtonTooltips();
// Check for file existance
$.ajax({
url: fileCheck
})
.done(function (data) {
if (data && data === "true") {
document.location.href = fileRequest;
me.collection.fetch();
} else if (!!data && data === "false") {
"This file is no longer available.".notify('error');
}
})
.fail(function (data) {
"Something went wrong during the File Existance check".notify('error');
"Something went wrong during the File Existance check".log(userId, 'error', 'Docs');
});
},
my collection:
// docsCollection.js - The collection of ALL the documents available to a given user
// Document Collection
Dashboard.Collections.DocsCollection = Backbone.Collection.extend({
model: Dashboard.Models.DocumentUploadModel,
url: function () {
return 'apps/docs/Docs/' + this.userId;
},
initialize: function (options) {
this.userId = options.userId;
this.deferredFetch = this.fetch();
},
comparator: function (model) {
return -(new Date(model.get('expirationDate')));
},
getDaysSinceViewedDocuments: function () {
return this.filter(function (model) {
return model.get('daysSinceViewed') !== null;
});
},
getNewDocuments: function () {
return this.filter(function (model) {
return model.get('isNew');
});
},
getExpiredDocuments: function () {
return this.filter(function (model) {
return model.get('isExpired');
});
}
});
and my model:
Dashboard.Models.DocumentUploadModel = Backbone.Model.extend({
defaults: {
fileArray: [],
name: '',
description: '',
accesses: [],
tags: [],
expirationDate: ''
},
initialize: function () {
this.set({
userId: Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
expirationDate: (this.isNew()) ? buildExpirationDate() : this.get('expirationDate')
}, { silent: true });
function buildExpirationDate() {
var date = new Date((new Date()).getTime() + 24 * 60 * 60 * 1000 * 7),
dateString = "{0}/{1}/{2}".format(date.getMonth() + 1, date.getDate(), date.getFullYear());
return dateString;
}
},
firstFile: function () {
return this.get('fileArray')[0];
},
validate: function (attributes) {
var errors = [];
if (attributes.name === '' || attributes.name.length === 0)
errors.push({
input: 'input.txtName',
message: "You must enter a name."
});
if (attributes.description === '' || attributes.description.length === 0)
errors.push({
input: 'textarea.taDescription',
message: "You must enter a description."
});
if (errors.length > 0)
return errors;
return;
},
sync: function (method, model, options) {
var formData = new FormData(),
files = model.get("fileArray"),
$progress = $('progress'),
success = options.success,
error = options.error;
// Nothing other than create or update right now
if (method !== "create" && method !== "update")
return;
// Build formData object
formData.append("name", model.get("name"));
formData.append("description", model.get("description"));
formData.append("accesses", model.get("accesses"));
formData.append("tags", model.get("tags"));
formData.append("expirationDate", model.get("expirationDate"));
formData.append("userId", model.get("userId"));
formData.append("isNew", model.isNew());
// if not new then capture id
if (!model.isNew())
formData.append('id', model.id);
for (var i = 0; i < files.length; i++) {
formData.append('file', files[i]);
}
xhr = new XMLHttpRequest();
xhr.open('POST', '/genericHandlers/UploadDocsFile.ashx');
xhr.onload = function () {
if (xhr.status === 200) {
if (success)
success();
} else {
if (error)
error();
}
}
if ($progress.length > 0) {
xhr.upload.onprogress = function (evt) {
var complete;
if (evt.lengthComputable) {
// Do the division but if you cant put 0
complete = (evt.loaded / evt.total * 100 | 0);
$progress[0].value = $progress[0].innerHTML = complete;
}
}
}
xhr.send(formData);
},
upload: function (changedAttrs, options) {
this.save("create", changedAttrs, options);
}
});
You're assigning a value to document.location.href before you try to fetch your collection:
document.location.href = fileRequest;
me.collection.fetch();
Changing document.location.href will change the whole page and in the process, any currently running JavaScript will get shutdown so I wouldn't expect your me.collection.fetch() to ever get executed.

Resources