Jquery-Ajax call not working as expected - google-app-engine

i'm working on a project like this:
(HTML Forms(AJAX)+ twitter bootstrap)(solo HTML, no JSP,etc..)->Servlets(on Google App Engine-JAVA)->Persistence(Google Cloud SQL).
I'm quite new to jQuery ajax calls, but i understand the process, as i'm used to write the old XHR code.
Below is the function in JS, that does not write to console the expected result..so far most of the times form data is persisted.
My Servlet if fine, and outputs a valid JSON.(calling the URL on a browser always works as expected.)
My answer is why jQuery ajax callbacks(done,fail,always) aren't working properly? They do write to console/display alert().
THANKS, for your time!
$(document).ready(function() {
var myEmail = "";
var myGender = "";
$('#saveButton').click(function() {
$('#myform').submit();
//alert('Handler for .submit() called.');
myEmail = document.getElementById("inputEmail").value;
window.console.log('EMAIL---->' + myEmail);/*ok log!*/
//alert('EMAIL->' + myEmail);
var radioObj = document.forms['myForm'].elements['gender'];
myGender = getCheckedValue(radioObj);
window.console.log('GENDER---->' + myGender);/*ok log!*/
//alert('GENDER->' + myGender);
var jqXHR = $.ajax({
statusCode : {
404 : function() {
alert("404 ERROR - page not found");
}
},
url : "/newuser",
type : "GET",
timeout : 10000,
data : {
email : myEmail,
gender : myGender,
operation : '0'
},
done : function(data, textStatus, jqXHR) {
window.console.log('done -> RESPONSE---->' + data);/*this does not log!*/
alert(data);
},
fail : function(jqXHR, textStatus, errorThrown) {
window.console.log('always -> RESPONSE---->' + data); /*this does not log!*/
alert(data);
},
always : function(data, textStatus, jqXHR) {
window.console.log('always -> RESPONSE---->' + data); /*this does not log!*/
alert(data);
}
});
});
});

done, fail and always are not properties of the settings object passed to $.ajax, they are callbacks on the jqxhr object returned by the call to $.ajax. They should be configured like this instead:
var jqxhr = $.ajax( "example.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });
Check out the API documentation for further usage guidance.

Related

$http:GET Invalid basic header. No credentials provided

When i tried to access star wars API using $http method . am getting 403 response with message "Invalid basic header. No credentials provided" what am missing here?
$http({
method : 'GET',
url : 'https://swapi.co/api/people/'
}).then(function(success) {
var data = JSON.parse(body);
var result = data.result.filter(function each(r) {
return username == r.name && password == r.birth_year;
});
}, function(error) {
alert('not logged::' + eror)
});
Could you please someone help me to find the issue?
You are using wrongly the data returned by the get call.
You don't need to parse it to JSON, it's already a JSON.
Here's a plunker with a call to the API working. Hope it helps you
https://plnkr.co/edit/WKQfqc7wxmBJIjYUyZKe
angular.module('myApp', []).controller('myAppController', function($http, $scope) {
$scope.callApi = function() {
$http.get('https://swapi.co/api/people/').then(function(result) {
$scope.characters = result.data.results;
}, function(error) {
alert('not logged::' + error)
});
}
});

query a specific url with AngularJS and Express

Inside my controller I have a call to fetch a document from my back end that looks like this:
orderFactory.query({_id: $stateParams.obj}).$promise.then(
function (response) {
console.log(response);
$scope.invoice = response[0].invoice;
$scope.client = response[0].client;
$scope.orderdetails = response[0].orderdetails;
},
function (response) {
console.log(response);
$scope.message = "Error: " + response.status + " " + response.statusText;
});
But the problem is that this code sends a GET request to /orders&_id=5926bef0f5344c1ff8a9b295 but the REST end point it should access is /orders/5926bef0f5344c1ff8a9b295
The URL in the browser is /trackdetails and I cant use $stateParams to access the end point desired
So my question is there any way to access that end point from the controller? Or perhaps I have to rework my architecture?
In resource:
$resource('your_url/:_id',
{
_id: '#_id'
}
)
In component:
orderFactory.get({_id: $stateParams.obj}, function(response) {
// success
}, function(reject) {
// error
})

data is undefined in transformRequest using $resource

I'm working on a small project with MEAN in order to get started with it. I've been following the tutorial on thinkster.io (with some minor modifications made by me) and so far I've obtained good results. I've tested the API routes with Postman and everything is working. Problem is, for some reason (keep in mind that I'm new to NodeJS), it only accepts requests with Content-type: x-www-form-urlencoded.
The solution I've come across several times is to change the headers in the options parameter of the $resource. This is the code I have
register: function(user){
var deferred = $q.defer();
var UserResource = $resource('/api/users/register', {}, {
save: {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: function (data, headersGetter) {
console.log(data); // data is undefined ??
var str = [];
for (var d in data)
str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return str.join("&");
}
}
});
UserResource.save(function(user){
this.saveToken(user.token);
deferred.resolve(user);
}, function(user){
deferred.reject(user);
});
return deferred.promise;
}
The register function is declared on an angular service. Problem is that the backend is sending me an error because the req.body object is empty. This is due to the fact that the transformRequest method is not executing correctly. Doing a little debugging I found that the 'data' parameter is undefined.
This is the code in the backend
router.post('/register', function(req, res, next){
if(!req.body.username || !req.body.password){
console.log(req.body.username);
return res.status(400).json({message: 'Por favor llene todos los campos'});
}
var user = new User();
user.username = req.body.username;
user.fullname = req.body.fullname;
user.setPassword(req.body.password);
user.save(function (err){
if(err){ return next(err); }
return res.json({token: user.generateJWT()})
});
});
Any ideas would be appreciated. Thanks in advance
You should pass user data in 1st parameter of save method(that will pass through the request body), there after you can place successCallback & errorCallback
UserResource.save(user, function(user){
this.saveToken(user.token);
deferred.resolve(user);
}, function(user){
deferred.reject(user);
});
Checkout this article

Turn request success into error based on response data

I am relatively new to Angular js and trying to use promises along with services and got reference http://plnkr.co/edit/b4HPbX2olM745EfHVcc6?p=preview. But in my application I am getting response as {"Response":"exception while loading Reports List","error":"Exception getting all records.","status":"failure"}. When I get response like this, I need to show an alert message with the message in "error" (i.e., Exception getting all records) and set $scope.data to [] in my controller.What are the changes I need to make to services and controller to handle this. Any help is much appreciated.
In services :
return $q.when(originalRequest)
.then(function(res) {
data = res.ResultSet.Response;
return data;
});
In Controller,
DashboardsDataService.getNetSpendOverTimeData()
.then(function(data) {
$scope.data = data;
});
The following is my original request to Java action class:
var originalRequest = $.ajax({
async : false,
url : "/dash2/dashd2ajax.do",
type : "POST",
data : {
action : 'getNetSpendOverTime',
customerId : selectedAccTd,
carriersId : selectedCarriers,
fromDate : fromDate,
toDate : toDate,
modes : selectedModes,
services : selectedServices,
dateType : selectedDateType,
lanesList : selectedLaneList
},
dataType : "json"
});
return $q.when(originalRequest)
.then(function(res) {
data = res.ResultSet.Response;
return data;
});
If what you're asking is "how do I turn request success into a failure based on result data", then take a look at the following example:
return $q.when(originalRequest).then(function (res) {
if (res.ResultSet.error) {
return $q.reject(res.ResultSet.error);
} else {
return res.ResultSet.Response;
}
});
Using $q.reject() turned your data into a real "promise failure", so in your controller, you can use the normal promise API:
doSomethingAsynchronous().then(function (data) {
$scope.data = data;
}, function (error) {
$scope.data = [];
alert(error);
});

AngularJS reload data after PUT request

Should be a fairly easy one here for anyone who knows Angular. I am trying to update the data that is displayed after I make a PUT request to update the object. Here is some code:
Post service (services/post.js)
'use strict';
angular.module('hackaboxApp')
.factory('Post', function($resource) {
return $resource('/api/posts/:id', {id : '#id'}, {
'update': { method: 'PUT' }
})
});
Server side controller function that gets executed when trying to update data (lib/controllers/api.js)
exports.editsave = function(req, res, next) {
var posty = req.body;
console.log(posty._id.toString() + " this is posty");
function callback (err, numAffected) {
console.log(err + " " + numAffected);
if(!err) {
res.send(200);
//res.redirect('/forum');
}
}
Post.update(posty, { id: posty._id.toString() }, callback);
};
This is the console output for the above code:
53c54a0d4960ddc11495d7d7 this is posty
null 0
So as you can see, it isn't affecting any of the MongoDB documents, but it also isn't producing errors.
This is what happens on the client (Angular) side when a post is updated:
$scope.saveedit = function() {
console.log($scope.post._id + " post id");
// Now call update passing in the ID first then the object you are updating
Post.update({ id:$scope.post._id }, $scope.post, function() {$location.path('/forum')});
};
After the redirect, $location.path('/forum'), none of the data is displayed as being updated...when I look in the database...nothing has changed either...it is like I am missing the step to save the changes...but I thought that update (a PUT request) would do that for me.
I use ng-init="loadposts()" when the /forum route is loaded:
$scope.loadposts = function() {
$http.get('/api/posts').success(function (data) {$scope.posts = data});
};
Shouldn't all the new data be loaded after this? Any help would be appreciated. Thanks!
Your server side output indicate that the update query doesn't match any document in the database.
I'm guessing that you are using Mongoose in NodeJS server side code to connect to mongodb.
If that the case, your update statement seems incorrect.
Instead of { id: .. } it should be { _id: .. }
Also the conditions object and updated object are swapped.
The statement should be like this:
Post.update({ _id: posty._id.toString() }, posty, callback);
If you are not using Mongoose, please eloborate more on which library you are using or better than that, show the code where the Post variable is defined in your server side code.
Ok I got it.
the problem is that you are not using the Angular resource api correct.
This code need to be changed:
$scope.saveedit = function() {
console.log($scope.post._id + " post id");
Post.update({ id:$scope.post._id }, $scope.post, function() {$location.path('/forum')});
};
Into:
// Update existing Post
$scope.saveedit = function() {
var editedpost = new Post($scope.post); //New post object
editedpost.$update(function() {
$location.path('/forum');
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
And as for the server code (taken from my own working module):
exports.update = function (req, res) {
var post == req.post;
post = _.extend(post, req.body);
post.save(function (err) {
if (err) {
return res.send(400, {
message: getErrorMessage(err)
});
} else {
res.jsonp(post);
}
});
};

Resources