AngularJS http post not working - javascript

I have created a service and I using that for my login:
EDIT: Added the 'success' and 'error' code.
EDIT 2: I am developing an iOS mobile application which includes Javascript/AngularJS. So is there a way to view errors as alerts..
.service('Login', function($http, $q, $httpParamSerializerJQLike) {
return {
loginUser: function(ipAdd, name, pw) {
var sendurl = 'http://' + ipAdd + ':8080/loginuser/user.cgi';
var postData = {
'ACTION' : 'login',
'LOGIN' : name,
'PASSWORD' : pw
};
//what is the mistake here?
return $http({
method : 'POST',
url : sendurl,
data : $httpParamSerializerJQLike(postData),
headers : { 'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response) {
var x2js = new X2JS();
var jsonObj = x2js.xml_str2json(response.data);
if (typeof jsonObj === 'object') {
alert("here:1");
return jsonObj;
} else {
alert("here:2");
// invalid response
return $q.reject(jsonObj);
}
}).error(function(response) {
//do error
//comes here when no internet connection is found..
alert("here:3");
return $q.reject(response.data);
});
}
}
})
I have also included this in app.js:
var app = angular.module("myApp", ['starter.services'],function($httpProvider){
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
});
My actual url looks like this:
'http://' + ipAdd + ':8080/loginuser/user.cgi?ACTION=login&LOGIN=' + name + '&PASSWORD=' + pw;
I have tried this approach too: https://stackoverflow.com/a/25570077/5876598
My service is not returning anything..
I want to know if I'm doing mistake in my url formation, or while sending data.
Thanks.

The best way to know where the mistake comes from is to check the 'network' tab on your navigator developer console.
Assuming you are runing on linux or mac, you can also try to use CURL to have an idea of what return the url you are trying to reach.
We can't help you with the code only.

I added a deferred promise in my service.
I also changed "success().error()" to ".then(function(data, status, headers, config){}) . Don't know why it didn't work when I used success and error.

Actually previously I noticed some issue while rendering promise itself in service. Follow the below structure
.service('Login', function($http, $q, $httpParamSerializerJQLike) {
return {
loginUser: function(ipAdd, name, pw) {
var sendurl = 'http://' + ipAdd + ':8080/loginuser/user.cgi';
var postData = {
'ACTION' : 'login',
'LOGIN' : name,
'PASSWORD' : pw
};
//what is the mistake here?
return $http({
method : 'POST',
url : sendurl,
data : $httpParamSerializerJQLike(postData),
headers : { 'Content-Type': 'application/x-www-form-urlencoded'}
});
}
}
})
.controller('SomeCtrlName',function(Login){
//pass your parameter to below service.
Login.loginUser().then(function success(){
//write success code here
},function error(){
//write error code here
)};
})

Related

Internal Server Error 500 when creating in laravel using ajax jQuery, wrong variables format from ajax to controller

I'm trying to create a new service option while creating a bill (a bill can have many services), it's like creating a new tag, or category while writing post without reloading, but i have this internal server error 500, i think the problem is in the Controller because it works fine when i comment the create in controller, route and csrf and stuff are checked, thanks for helping me !
In my javascript :
var max_service_id = {{$max_service_id}};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#add_service_button").on("click",function(e){
e.preventDefault();
var service_name = $("input[name=service_name]").val();
var service_category = document.getElementById('service_category').value;
var service_description = $("input[name=service_description]").val();
$.ajax({
type:'POST',
url:'/service/add-in-bill',
dataType: 'json',
data:{
name : service_name,
category_id : service_category,
description : service_description
},
success:function(data){
if (data.message) {
//This is error message
alert(data.message);
}
if (data.success) {
alert(data.success);
var newService = new Option(service_name, max_service_id, false, true);
$('.multipleSelect').append(newService).trigger('change');
max_service_id++;
$("#add_service_div").hide("fast");
}
}
});
})
});
In my controller :
$validator = Validator::make($request->all(), [
'name' => 'required|unique:services',
'category_id' => 'required',
]);
if ($validator->fails()) {
return response()->json(['message'=>$validator->errors()->all()]);
} else {
// It works fine when i comment this, so i think the problem is something about variables from javascript to php stuff
Service::create($request->all());
return response()->json(['success'=>'Create service success !']);
}
//
// I think the problem is in the Controller because it works fine when i comment the "Service::create($request->all());"

How to change location and refresh page in angular js

I have a function :
$scope.insert = function(){
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
$http({
method: 'POST',
url: './sys/mac.php',
data : data
}).then(function(response){
return response.data;
});
}
and the function work perfectly, but i want my page change to datalist and refresh datalist after insert() true. my function insert() run in the route "localhost/learn/#!/administrator" so i want it change to route "localhost/learn/#!/" after insert() true. i used location.href='#!/' but it not work for refresh datalist automaticaly, just change location.
If you want to update an object from a service call, you can do the following. I have added an onError function too, to help with debugging.
Tip: Research adding service calls into a Service that AngularJS framework provides. It helps for writing maintainable and structured code.
$scope.objectToUpdate;
$scope.insert = function(){
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
$http({
method: 'POST',
url: './sys/mac.php',
data : data
}).then(function(response){
$scope.objectToUpdate = response.data.d;
}, function(e){
alert(e); //catch error
});
}
Optional Service
Below is an example of how to make use of Angular Services to make server calls
app.service('dataService', function ($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function (url, data) {
// $http() returns a $promise that we can add handlers with .then() in controller
return $http({
method: 'POST',
url: './sys/' + url + '.php',
dataType: 'json',
data: data,
headers: { 'Content-Type': 'application/json; charset=utf-8' }
});
};
});
Then call this service from your controller, or any controller that injects DataService
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
dataService.getData('mac', data).then(function (e) {
$scope.objectToUpdate = e.data.d;
}, function (error) {
alert(error);
});

Return Object in $rootScope Function (AngularJS)

I am trying to return an object from a $rootScope function called retrieveUser() in AngularJS. The object is returned. I have run console.log() on the response of the function ran when $http is successful. Here is my $rootScope function:
$rootScope.retrieveUser = function() {
var apiUrl = "http://104.251.218.29:8080";
if($cookies.get('tundraSessionString')) {
var cookie = $cookies.get('tundraSessionString');
$http({
method: "POST",
url: apiUrl + "/api/master/v1/auth/checkauth",
data: "sessionString=" + cookie,
headers: {
'Content-Type' : 'application/x-www-form-urlencoded;',
'Cache-Control': 'no-cache'
}
}).then(function mySuccess(response) {
if(response.data.event == "error") {
window.location = "/auth/logout";
} else {
return response.data;
}
})
} else {
window.location = "/auth/login";
}
};
With this method, I access it in my controller such as this (and console.log() just to test my work):
vm.user = $rootScope.retrieveUser();
console.log($rootScope.retrieveUser());
But, I have yet to get this to work. I have tried specifying specific objects in an array in my $rootScope function. I know it runs, because I have the $rootScope consoling something when it is run, and it shows a console.log() of the response of the $http request. It looks like this:
Object {event: "success", table: Object}
event:"success"
table:Object
__proto__:Object
Yet, when I console.log() the vm.user with the function $rootScope.retrieveUser(), even though the function is supposed to be returning the object, I simply receive "undefined".
I have been banging my head on this for days, read some articles on functions/objects and I still cannot figure this out. We're two days in.
try this:
if($cookies.get('tundraSessionString')) {
var cookie = $cookies.get('tundraSessionString');
//return a promise
return $http({
method: "POST",
url: apiUrl + "/api/master/v1/auth/checkauth",
data: "sessionString=" + cookie,
headers: {
'Content-Type' : 'application/x-www-form-urlencoded;',
'Cache-Control': 'no-cache'
}
}).then(function mySuccess(response) {
if(response.data.event == "error") {
window.location = "/auth/logout";
}
else {
return response.data;
}
})
}
else {
window.location = "/auth/login";
}
and
$rootScope.retrieveUser().then(function(user){vm.user = user;})
What you are returning from retrieveUser when your cookie is set is what $http returns, which is a promise. Try this:
$rootScope.retrieveUser().then(function(user){vm.user = user;})
retrieveUser fn doesn't return your data :)
$http is asynchronous function and you should read about promises
function handleUser(user){
//do something
}
function retrieveUser(callback){
$http({...}).then(function(response){
callback(response.data.user);
});
}
//how to use it:
retrieveUser(handleUser);
but first of all you may need a service for getting some data instead of using $rootScope
and secondly you can pass a user in your template in script tag
then you don't need another http request and user will be globaly available
<script>var user=<?php echo json_encode($user);?></script>

Consuming a restful service with 'slash' char in uri parameter in angular JS

I have a situation where I need to consume a restful web service in AngularJS using GET method by allowing it to accept slash "/" character in uri parameter.
Normally "/" slash, creates a different end point and service doesn't give the required response and I need to consume the RESTful web service where the parameter should be passed as string.
Scenario to be considered:
Sample URL: http://hostname/servicename/{parameter}
where parameter should be a string and Should be valid for below sample inputs
a
12
12/15
126/567
I am using below code
service.js
angular.module('starter.services', [])
.factory('dataService', ['$http', function($http) {
var obj = {};
obj.getData = function(url){
return $http({
method: 'GET',
url: url,
headers: {'Content-Type': 'application/json;charset=utf-8'},
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
return "ERROR";
});
}
return obj;
}])
controller.js
var url = "http://hostname/servicename/" + paramId + "";
dataService.getData(url).then(
function(response) {
// Response stuff here
}
)
NOTE: I have to manage all things at client side and don't have access to server side code of web service.
Encode the parameter like this.
encodeURIComponent(paramId)
Otherwise replace / with '%2f'
Have u tried params object instead passing the parameter directly in the url?
If no.. just pass the parameter as shown below.
service.js
angular.module('starter.services', [])
.factory('dataService', ['$http', function($http) {
var obj = {};
obj.getData = function(url, paramId){
return $http({
method: 'GET',
url: url,
params:{
"paramId" : paramId
},
headers: {'Content-Type': 'application/json;charset=utf-8'},
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
return "ERROR";
});
}
return obj;
}]);
controller.js
var url = "http://hostname/servicename";
dataService.getData(url, paramId).then(
function(response) {
// Response stuff here
}
);
Let me know if this helps!

AngularJS 1.2.0 $resource PUT/POST/DELETE do not send whole object

I'm using angularjs 1.2.0 with $resource. I would like to have some PUT/POST instance actions that doesn't send the whole object to the server but only some fields and in some cases totally no data.
Is it possible? I searched everywhere but couldn't find anything
UPDATE:
It also happens with DELETE requests:
Given this code:
group.$deleteChatMessage({messageId: message.id}, function(){
var i = _.indexOf(group.chat, message);
if(i !== -1) group.chat.splice(i, 1);
});
The request is this:
See how the whole model is sent (under "Request Payload").
This is the resource:
var Group = $resource(API_URL + '/api/v1/groups/:gid',
{gid:'#_id', messageId: '#_messageId'},
{
deleteChatMessage: {method: "DELETE", url: API_URL + '/api/v1/groups/:gid/chat/:messageId'},
});
This works for me:
$resource(SERVER_URL + 'profile.json',
{},
{
changePassword :
{
method : 'POST',
url : SERVER_URL + 'profile/changePassword.json',
// Don't sent request body
transformRequest : function(data, headersGetter)
{
return '';
}
}
});
You could customise exaclty what is sent to the server by implementing your own code in the transformRequest function. In my example I was adding a new function to the REST client, but you can also overwrite existing functions. Note that 'transformRequest' is only available in version 1.1+
You can use $http for that specifically. However, I have one case I use for a project that might help. Also my example is returning an array from the server but you can change that.
In my service:
app.factory('mySearch', ['$resource', function($resource) {
return $resource('/api/items/:action', {}, {
search: { method: 'POST', isArray: true,
params: { action: 'search' }
}
});
}
]);
In my Controller:
I can build up custom params to post to server or if its only two fields I need from a table row the user selects.
var one = "field_one";
var two = "field_two";
$scope.search({one: one, two: two});
Then I can post those through an event and pass the custom params
$scope.search = function(customParams) {
mySearch.search({query: customParams}, function(data) {
$scope.items = data;
}, function(response) {
console.log("Error: " + response.status);
})
};
Hopefully this was some help. Let me know if this is close to what your looking for and I can help more.
POST
DELETE

Categories

Resources