Override Jquery Ajax with Formdata - javascript

I'm trying to override jeury ajax with form data (having file as well), but it always return following error:
Uncaught TypeError: Illegal invocation
But it is working fine when I pass array data instead of formdata.
I have tried both ajax and post but none of the code is working. Please do help guys.
Here is the post override:
// Store a reference to the original remove method.
var originalPostMethod = jQuery.post;
// Define overriding method.
jQuery.post = function () {
// Execute the original method.
if (window.user && window.user.user && window.user.user.csrf) {
console.log('form data', arguments[1]);
if (arguments[1] instanceof FormData) {
arguments[1].set('csrf', window.user.user.csrf);
}
else {
arguments[1].csrf = window.user.user.csrf;
}
}
var callback = arguments[2];
arguments[2] = function (data) {
console.log('post data', data);
if (data.new_csrf) {
window.user.user.csrf = data.new_csrf;
}
callback(data);
}
console.log('this post', this);
console.log('arguments post', arguments);
var callMethod = originalPostMethod.apply(this, arguments);
callMethod.error = callMethod.fail
return callMethod
}
Here is the ajax override:
var originalAjaxMethod = jQuery.ajax;
jQuery.ajax = function () {
if (arguments[0] && arguments[0].success) {
var callback = arguments[0].success;
arguments[0].success = function (data) {
console.log('ajax data', data);
if (data.new_csrf) {
window.user.user.csrf = data.new_csrf;
}
callback(data);
}
if ($.inArray(arguments[0].type, ['post', 'POST']) !== -1 && window.user && window.user.user && window.user.user.csrf) {
console.log('form data', arguments[0]);
var reqData = arguments[0].data ? arguments[0].data : {};
if (reqData instanceof FormData) {
reqData.set('csrf', window.user.user.csrf);
}
else {
reqData.csrf = window.user.user.csrf;
}
arguments[0].data = reqData;
}
}
console.log('this ajax', this);
console.log('arguments ajax', arguments);
var callMethod = originalAjaxMethod.apply(this, arguments);
callMethod.error = callMethod.fail;
return callMethod;
}
This is not working:
$.post('url', formData, function (data) {
});
This is working:
$.post('url', {data: data}, function (data) {
});
Anyone has any idea about it?

Related

"Uncaught TypeError: Cannot read property 'defer' of undefined at Websocket Angular JS"

I am pretty new to web technologies, I got bits & pieces of code from internet and somehow managed to form this code.
I have to get data to a web app developed in angularjs from websocket through APIs.
here is the code,
angular.module("MyApp")
.service("myService", function ($rootScope, $q) {
return {
_prevTransmittingStatus: null,
transmitting: false,
_transmissionStatus: function () {},
socket: null,
socket_msg_id: 0,
socket_history: {},
url: "ws://localhost:4848/app/",
setOnTransmissionStatus: function (callback) {
var self = this;
this._transmissionStatus = function () {
if (self.transmitting != self._prevTransmittingStatus) {
self._prevTransmittingStatus = self.transmitting
callback(self.transmitting)
} else {}
}
},
connect: function (callback) {
var deferred = $q.defer();
var promise = deferred.promise;
var self = this
this.transmitting = true;
this._transmissionStatus();
this.socket = new WebSocket(this.url);
this.socket.addEventListener('open', function (e) {
self.transmitting = false;
self._transmissionStatus();
deferred.resolve("connected")
});
this.socket.addEventListener('message', function (e) {
var asJson = angular.fromJson(e.data)
var replyId = asJson.id;
var histItem = self.socket_history[replyId]
self.transmitting = false;
self._transmissionStatus();
if (angular.isUndefined(asJson.error)) {
$rootScope.$apply(histItem.defer.resolve(asJson.result))
} else {
**GetActiveDoc();/*how to call this */**
console.log("---rejected-----");
$rootScope.$apply(histItem.defer.reject(asJson.error))
}
});
return promise;
},
disconnect: function () {
this.socket.close();
this.transmitting = false;
this._transmissionStatus();
return this;
},
send: function (msg, scope, callback, onerror) {
console.info("SEND:", msg)
var _this = this;
this.transmitting = true;
this._transmissionStatus();
if (!this.socket) {
return this.connect().then(
function (histItem) {
console.log("CONNECT SUCCESS", histItem)
},
function (histItem) {
console.log("CONNECT ERROR", histItem)
}
).then(function () {
return _this.send(msg, scope);
})
} else if (this.socket) {
console.log("socket is open")
var deferred = $q.defer();
var promise = deferred.promise;
msg.id = this.socket_msg_id;
this.socket_history[msg.id] = {
id: msg.id,
defer: deferred,
scope: scope,
msg: msg
};
this.socket_msg_id++
this.socket.send(angular.toJson(msg))
return promise
}
},
isConnected: function () {
return this.socket ? true : false;
}
}
});
I am getting an error "Uncaught TypeError: Cannot read property 'defer' of undefined at Websocket" only for the first time when I open my web app.
Can some one explain how to resolve this.
solved it myself, just added/modified the code as follows,
if(replyId >= 0){
$rootScope.$apply(histItem.defer.resolve(asJson.result))
}

angular factory store promise result

I have a factory object that contain private object, which is used to cache result retrieved from the api using the factory available functions.
global.mainApp.factory('SessionFactory', function (UserEndpointsResource, SiteEndpointsResource) {
var data = {
/**
* #type {boolean|null}
*/
isLoggedIn: null
};
return {
isUserLoggedIn: function (callback) {
if (data.isLoggedIn != null) {
callback(data.isLoggedIn);
}
else {
UserEndpointsResource.isLoggedIn().$promise.then(function (res) {
var isUserLoggedIn = res.status == 1;
// Trying to set the result to the outer scope data variable
data.isLoggedIn = isUserLoggedIn;
callback(isUserLoggedIn);
}, function (failureData) {
data.isLoggedIn = false;
callback(false);
});
}
},
...
};
});
The problem that every time I call the isUserLoggedIn function, data.isLoggedIn is always null.
How can I alter the factory data object inside the promise then function?
Thanks.
Using the suggestion supplied in the comments, aka do not store promise results, store promises themselves, this is the modified working code!
global.mainApp.factory('SessionFactory', function (UserEndpointsResource, SiteEndpointsResource) {
var data = {
/**
* #type {boolean|null}
*/
isLoggedIn: null
};
return {
isUserLoggedIn: function (callback) {
if (data.isLoggedIn != null) {
data.isLoggedIn.then(function (isLoggedIn) {
callback(isLoggedIn.status == 1);
});
}
else {
data.isLoggedIn = UserEndpointsResource.isLoggedIn().$promise.then(function (res) {
var isUserLoggedIn = res.status == 1;
callback(isUserLoggedIn);
return isUserLoggedIn;
}, function (failureData) {
data.isLoggedIn = false;
callback(false);
return null;
});
}
}
};
});

Reformatting for Angular style guide 1.5

I am using the Angular spyboost utility wrapper. I am trying to reformat it for this angular 1 style guide. I'm having a hard time with parts of it. I think I have most of it correct but the angular.forEach function is throwing me off. I am and am getting an error `Expected '{' and instead saw 'result'. Could someone help me please ?
angular
.module('myMod')
.factory('MyService');
MyService.$inject = ['$rootScope', 'atmosphereService', 'atmosphere'];
function MyService ($rootScope, atmosphere) {
return {
subscribe: subscribe,
getMessage: getMessage
};
function subscribe (r) {
var responseParameterDelegateFunctions = ['onOpen', 'onClientTimeout', 'onReopen', 'onMessage', 'onClose', 'onError'];
var delegateFunctions = responseParameterDelegateFunctions;
var result = {};
delegateFunctions.push('onTransportFailure');
delegateFunctions.push('onReconnect');
angular.forEach(r, function (value, property) {
if (typeof value === 'function' && delegateFunctions.indexOf(property) >= 0) {
if (responseParameterDelegateFunctions.indexOf(property) >= 0)
**result[property] = function (response) {**
$rootScope.$apply(function () {
r[property](response);
});
};
else if (property === 'onTransportFailure')
result.onTransportFailure = function (errorMsg, request) {
$rootScope.$apply(function () {
r.onTransportFailure(errorMsg, request);
});
};
else if (property === 'onReconnect')
result.onReconnect = function (request, response) {
$rootScope.$apply(function () {
r.onReconnect(request, response);
});
};
} else
result[property] = r[property];
});
function getMessage () {
var vm = this;
var request = {
url: '/chat',
contentType: 'application/json',
transport: 'websocket',
reconnectInterval: 5000,
enableXDR: true,
timeout: 60000
};
request.onMessage(response); {
vm.$apply (function () {
vm.model.message = atmosphere.util.parseJSON(response.responseBody);
});
}
}
return atmosphere.subscribe(result);
}
}
})(window.angular);
if (responseParameterDelegateFunctions.indexOf(property) >= 0)
is missing its curly braces?
if (responseParameterDelegateFunctions.indexOf(property) >= 0) {
result[property] = function (response) {
$rootScope.$apply(function () {
r[property](response);
});
};
}
else if (property === 'onTransportFailure') {
result.onTransportFailure = function (errorMsg, request) {
$rootScope.$apply(function () {
r.onTransportFailure(errorMsg, request);
});
};
}
else if (property === 'onReconnect') {
result.onReconnect = function (request, response) {
$rootScope.$apply(function () {
r.onReconnect(request, response);
});
};
}

How to call function?

I have this function:
$scope.PinTicketSearch = function(pinTicket) {
if (pinTicket != null) {
ticketService.searchTicket(pinTicket)
.then(function(response) {
$location.search({
"ticketPin": pinTicket
});
$scope.TicketDetail = response;
$scope.ShowDetailsAboutTicket = true;
});
}
}
and i have this part of code:
if ($location.search().ticketPin)
{
}
How can i call this function $scope.PinTicketSearch and pass parameters from $location.search().ticketPin. I tried with $scope.PinTicketSearch($location.search().ticketPin) but i get an error
PinTicketSearch is not a function
You should to use a callback, instead of your if:
$scope.PinTicketSearch = function(pinTicket, success) {
if(pinTicket != null) {
ticketService.searchTicket(pinTicket)
.then(function(response) {
$location.search({
"ticketPin": pinTicket
});
$scope.TicketDetail = response;
$scope.ShowDetailsAboutTicket = true;
success();
});
}
}
and your "if", will be:
$scope.PinTicketSearch(pinTicket, function() {
// your original "if" body
});

Angular Directive Follow/Unfollow button

I'm trying to make angular directive button to follow and unfollow leagues ID
every request $http.put going fine but there is a problem with .then method console show me error and the method rejected
here the code
app.factory('FollowedLeagues', ['appConfig', '$http', '$q', function(appConfig, $http, $q){
var FollowedLeagues = {};
FollowedLeagues.follow = function (token, leagueID) {
$http.put(appConfig.apiUrl + 'user/follow-league?token=' + token +'&league_id='+ leagueID +'&status=true' )
.then(function(response){
if (typeof response.data === 'object') {
return response.data;
} else {
// invalid response
return $q.reject(response.data);
}
},
function(response) {
// something went wrong
return $q.reject(response.data);
});
};
FollowedLeagues.unfollow = function (token, leagueID) {
$http.put(appConfig.apiUrl + 'user/follow-league?token=' + token +'&league_id='+ leagueID +'&status=false' )
.then(function(response){
if (typeof response.data === 'object') {
return response.data;
} else {
// invalid response
return $q.reject(response.data);
}
},
function(response) {
// something went wrong
return $q.reject(response.data);
});
};
return FollowedLeagues;
}]);
app.directive('fbFollowBtn', ['$rootScope', '$compile', 'FollowedLeagues', function ($rootScope, $compile, FollowedLeagues) {
var getLeagueID = function(leagueID, followed){
for(var i=0; i< followed.length; i++) {
var fLeagues = followed[i]._id;
if (fLeagues == leagueID) {
return fLeagues;
}
}
};//End-function.
return {
restrict: 'A',
link:function(scope, element, attrs){
scope.followed = $rootScope.meData.followedLeagues;
scope.leagueid = attrs.leagueid;
var follow_btn = null;
var unfollow_btn = null;
var createFollowBtn = function () {
follow_btn = angular.element('Follow');
$compile(follow_btn)(scope);
element.append(follow_btn);
follow_btn.bind('click', function(e){
scope.submitting = true;
FollowedLeagues.follow($rootScope.userToKen, scope.leagueid)
.then(function(data){
scope.submitting = false;
follow_btn.remove();
createUnfollowBtn();
console.log('followed Leagues Done :-) ', data);
});
// scope.$apply();
});
};
var createUnfollowBtn = function () {
unfollow_btn = angular.element('Unfollow');
$compile(unfollow_btn)(scope);
element.append(unfollow_btn);
unfollow_btn.bind('click', function (e) {
scope.submitting = true;
FollowedLeagues.unfollow($rootScope.userToKen, scope.leagueid)
.then(function(data){
scope.submitting = false;
unfollow_btn.remove();
createFollowBtn();
console.log('followed Leagues Done :-) ', data);
});
// scope.$apply();
});
};
scope.$watch('leagueid', function (val) {
var leag = getLeagueID(scope.leagueid, scope.followed);
if(typeof(leag) == 'undefined'){
createFollowBtn();
} else if(typeof(leag) !== 'undefined'){
createUnfollowBtn();
}//end if
}, true);
}
};
}]);
You have to return your $http.put function inside your service functions. For example the Followedleagues.follow function:
FollowedLeagues.follow = function (token, leagueID) {
return $http.put(appConfig.apiUrl + 'user/follow-league?token=' + token +'&league_id='+ leagueID +'&status=true' )
.then(function(response){
if (typeof response.data === 'object') {
return response.data;
} else {
// invalid response
return $q.reject(response.data);
}
},
function(response) {
// something went wrong
return $q.reject(response.data);
});
};

Categories

Resources