Array empty after posting data from angular controler - javascript

I am using codeigniter and angular for my app. When I post the data from angular controller to CI controller, array seems to be empty (result of print_r is "array()") .Can someone tell me why?
Angular Part:
$scope.posaljiKontroleru = function () {
$scope.prosek = {kalorije: 0.0, proteini: 0.0, uh: 0.0, masti: 0.0};
$http({
method: 'POST',
url: 'http://localhost/psi/Pravljenjejela/dodajBazi',
data: $scope.prosek
}).then(function (res) {
$window.location.href = "http://localhost/psi/Pravljenjejela/dodajBazi";
}, function (err) {
console.log(err);
});
});
}
CI part
public function dodajBazi() {
$info = $this->input->post();
print_r($info);
}

You need to use default content-type header
Try this:
$http({
method: 'POST',
url: 'http://localhost/psi/Pravljenjejela/dodajBazi',
data: $scope.prosek,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (res) {
$window.location.href = "http://localhost/psi/Pravljenjejela/dodajBazi";
}, function (err) {
console.log(err);
});

Related

Cascading Dropdown - How to load Data?

I try to make an cascading dropdown, but I have problems with the sending and fetching of the response data.
Backend:
[HttpPost]
public async Task<JsonResult> CascadeDropDowns(string type, int id)
{ .............
return Json(model);
}
Here I get the correct data.
First I tried:
$("#dropdown").change( function () {
var valueId = $(this).val();
var name = $(this).attr("id");
let data = new URLSearchParams();
data.append("type", name);
data.append("id", valueId);
fetch("#Url.Action("CascadeDropDowns", "Home")", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
body: data
})
.then(response => {
console.log('Success:', response);
return response.json();
})
.then(json => {
console.log('Success:', json );
console.log('data:', json.Projects);
PopulateDropDown("#subdropdown1",json.Projects)
})
.catch(error => {
console.log('Error:', error);
});
});
Here I can send the Request and get a "success" back. However, when I access json.Projects I just get an `undefined. I have tried to change the Content-Type, without success.
Secondly I have used:
$.ajax({
url: "#Url.Action("CascadeDropDowns", "Home")",
data: data,
type: "POST",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function (data) {
console.log(data);
},
error: function (r) {
console.log(r.responseText);
},
failure: function (r) {
console.log(r.responseText);
}
});
With this I get an Illegal Invocation Error.
What do I have to do that get either of those working? What are their problems?
I try to make an cascading dropdown, but I have problems with the
sending and fetching of the response data.What do I have to do that get either of those working? What are their problems?
Well, let consider the first approach, you are trying to retrieve response like json.Projects but its incorrect because data is not there and you are getting undefined as below:
Solution:
Your response would be in json instead of json.Projects
Complete Demo:
HTML:
<div class="form-group">
<label class="col-md-4 control-label">State</label>
<div class="col-md-6">
<select class="form-control" id="ddlState"></select>
<br />
</div>
</div>
Javascript:
var ddlState = $('#ddlState');
ddlState.empty();
ddlState.append($("<option></option>").val('').html('Please wait ...'));
let data = new URLSearchParams();
data.append("type", "INDIA");
data.append("id", 101);
fetch("http://localhost:5094/ReactPost/CascadeDropDowns", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
body: data
})
.then(response => {
return response.json();
})
.then(result => {
console.log(result);
var ddlState = $('#ddlState');
ddlState.empty();
ddlState.append($("<option></option>").val('').html('Select State'));
$.each(result, function (index, states) {
ddlState.append($("<option></option>").val(states.cityId).html(states.cityName));
});
})
Second approach:
In ajax request you are passing object as object fahsion like data: data whereas, your controller expecting as parameter consequently, you are getting following error:
Solution:
You should pass your data within your ajax request like this way data: { type: "YourTypeValue", id:101 }, instead of data: data,
Complete Sample:
$.ajax({
url: 'http://localhost:5094/ReactPost/CascadeDropDowns',
type: 'POST',
data: { type: "YourValue", id:101 },
success: function (response) {
ddlState.empty();
ddlState.append($("<option></option>").val('').html('Select State'));
$.each(response, function (i, states) {
ddlState.append($("<option></option>").val(states.cityId).html(states.cityName));
});
},
error: function (response) {
alert('Error!');
}
});
Note: I have ommited contentType because, by default contentType is "application/x-www-form-urlencoded;charset=UTF-8" if we don't define.
Output:

Javascript AngularJS: Inner function cannot the variable value of outer function

I am developing ionic hybrid application. I am using $http to get value from server. Next, I will make a cordova sqlite query, inside the cordova query I want to insert my result from $http call from server and result of cordova query into my sqlite database. However, I can't get the value of $http return value in my cordova query. The following is my code:
$http({
method: "post",
url: "http://localhost/php2/get_channel.php",
data: {
user_name: usernameID
},
headers: { 'Content-Type': 'application/json' }
}).success(function(response) {
for(i=0; i<response.length; i++){
var channelNameQuery = "SELECT * FROM chat_friend WHERE channel_id=?"
var channelNamePromise = $cordovaSQLite.execute(db, channelNameQuery, [response[i].ChannelName]).then(function (result){
var ChannelQuery = "REPLACE INTO chat_channel (last_text, usernameID, chat_channel, chat_channel_name) VALUES (?,?,?,?)";
$cordovaSQLite.execute(db, ChannelQuery, [response[i].LastText, usernameID, response[i].ChannelName, result.rows.item(0).UserName]);
})
}
}).error(function(response) {
console.log(response);
console.log("failed");
});
I can't get response[i].LastText and response[i].ChannelName value inside $cordovaSQLite.execute() function.
Sorry for my poor language.
The data you recive is mapped on response.data. Try looping thru your data by using angular.forEach(). Remember that response is mostly a object so you cant get response.length here. Please take a look at the $http AngularJS documentation.
$http({
method: "post",
url: "http://localhost/php2/get_channel.php",
data: {
user_name: usernameID
},
headers: { 'Content-Type': 'application/json' }
}).success(function(response) {
angular.forEach(response.data, function (data) {
var channelNameQuery = "SELECT * FROM chat_friend WHERE channel_id=?"
var channelNamePromise = $cordovaSQLite.execute(db, channelNameQuery, [data.ChannelName]).then(function (result){
var ChannelQuery = "REPLACE INTO chat_channel (last_text, usernameID, chat_channel, chat_channel_name) VALUES (?,?,?,?)";
$cordovaSQLite.execute(db, ChannelQuery, [data.LastText, usernameID, data.ChannelName, result.rows.item(0).UserName]);
})
});
}).error(function(response) {
console.log(response);
console.log("failed");
});

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);
});

Laravel 5.3 AJAX login doesn't redirect

I have similar issue like this one.
I'm trying to make AJAX login using Laravel 5.3 Auth.
Here's what I got so far:
var login = function()
{
var data = {};
data["email"] = $('#email').val();
data["password"] = $('#password').val();
if($('#remember').is(':checked'))
data["remember"] = "on";
$.ajax({
type: "POST",
url: '/login',
data: JSON.stringify(data),
// data: data,
headers : { 'Content-Type': 'application/json' },
success: function(data) {
console.log(data);
// window.location.href = "/dashboard";
}
});
};
I'm sending CRSF token as X-CSRF-TOKEN header.
The problem is that when I successfully login, I say on the same page,
but in Network tab I can see that /dashboard page is loaded by I'm not
redirected.
In the same manner, when I pass wrong credentials, I stay on the same page,
but I can see that /login page is loaded in the separate call with an error message that should be actually displayed.
Also, I've tried without headers : { 'Content-Type': 'application/json' },
and sending data as: data = data, but I get the same thing.
Why the browser doesn't redirect to that page since it is loading it in the "background"?
Edit: I'm getting correct page as request response as well, I can see it
in console (console.log(data);).
//Login FORM
$(document).on('submit', 'form#FormID', function(e) {
e.preventDefault();
var forms = document.querySelector('form#FormID');
var request = new XMLHttpRequest();
var formDatas = new FormData(forms);
request.open('post','/login');
request.send(formDatas);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
if (request.responseText == 'success') {
setTimeout(function() {
window.location.href = "/dashboard";
}, 5000);
}else{
};
}
}
}
});
//Controller
public function authUser(Request $request){
$data = $request->except('_token');
$validate = \Validator::make($data, [
'email' => 'email'
]);
if ($validate->fails())
return 'Invalid email format for username.';
if (\Auth::attempt($data)) {
return 'success';
}else{
return 'Invalid username or password';
}
}
//Route
Route::post('/login', 'YourController#authUser');
The problem might be with the response AJAX request is expecting before redirect.
Try the above code.
in the controller method
function login(Request $request){
if(\Auth::attempt($request)){
return response()->json('success');
}else{
return response()->json('wrong username or pass', 401);
}
}
in ajax
$.ajax({
type: "POST",
url: '/login',
data: JSON.stringify(data),
// data: data,
headers : { 'Content-Type': 'application/json' },
success: function(data) {
console.log(data);
window.location.href = "/dashboard";
},
error : function(data){
alert(data);
}
});
Here's an interesting solution.
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendFailedLoginResponse(Request $request)
{
if ($request->ajax()) {
return response()->json([
'error' => Lang::get('auth.failed')
], 401);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors([
$this->username() => Lang::get('auth.failed'),
]);
}
And this:
var loginForm = $("#loginForm");
loginForm.submit(function(e) {
e.preventDefault();
var formData = loginForm.serialize();
$('#form-errors-email').html("");
$('#form-errors-password').html("");
$('#form-login-errors').html("");
$("#email-div").removeClass("has-error");
$("#password-div").removeClass("has-error");
$("#login-errors").removeClass("has-error");
$.ajax({
url: '/login',
type: 'POST',
data: formData,
success: function(data) {
$('#loginModal').modal('hide');
location.reload(true);
},
error: function(data) {
console.log(data.responseText);
var obj = jQuery.parseJSON(data.responseText);
if (obj.email) {
$("#email-div").addClass("has-error");
$('#form-errors-email').html(obj.email);
}
if (obj.password) {
$("#password-div").addClass("has-error");
$('#form-errors-password').html(obj.password);
}
if (obj.error) {
$("#login-errors").addClass("has-error");
$('#form-login-errors').html(obj.error);
}
}
});
});

Angularjs: Singleton service using $http [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
is it possible in angular to create service using $http which will take method, url, success and failure callback as parameters when called from controller.
I want to achieve following kind of functionality using angular.
var ajax = {
URL: "webservice url",
loggedIn: false,
importedId: "",
token: '',
userdetails: new Backbone.Collection.extend({}),
serverCall: function(method, data, successCallBack, failureCallBack) {
var that = this;
//console.log(method);
//console.log(successCallBack);
that.showLoading();
$.ajax({
url: that.URL + method,
method: 'post',
data: data,
// contentType:"application/json; charset=utf-8",
success: function(data) {
that.hideLoading();
if (that.checkForError(data))
{
successCallBack(data);
}
},
fail: function(data) {
that.hideLoading();
failureCallBack(data);
}
});
}
i am using https://github.com/StarterSquad/startersquad.github.com/tree/master/examples/angularjs-requirejs-2 folder structure for app and inside services i have following code
define(['./module'], function(services) {
'use strict';
services.factory('user_resources', ['$resource', '$location', function($resource, $location) {
return $resource("", {},
{
'getAll': {method: "GET", url:'JSON/myList.JSON',isArray:true}
});
}]);
});
and in controller i have following code
define(['./module'], function (controllers) {
'use strict';
controllers.controller('myListCtrl',['Phone','Phone1','loginForm','$scope','$http','user_resources','CreditCard',function(Phone,Phone1,loginForm,$scope,$http,user_resources,CreditCard){
console.log(user_resources.getAll())
}]);
});
which returns [$promise: Object, $resolved: false] how to get data from that?
A service in AngularJS is always a singleton, so you wouldn't have to do anything to achieve that. However, it seems like you do not actually want a singleton as you want to pass in different values. Thus, you might want to add your own service factory function. Something like:
function MyHTTPService($rootScope, url, method) {
this.$rootScope = $rootScope;
this.url = URL;
this.method = method;
}
MyHTTPService.prototype.serverCall = function () {
// do server call, using $http and your URL and Method
};
App.factory('MyHTTPService', function ($injector) {
return function(url, method) {
return $injector.instantiate(MyHTTPService,{ url: url, method: method });
};
});
This can be called using
new MyHTTPService("http://my.url.com", "GET");
you could also use $resource for this type of usage.
angular.module('MyApp.services').
factory('User_Resource',["$resource","$location", function ($resource,$location){
var baseUrl = $location.protocol() + "://" + $location.host() + ($location.port() && ":" + $location.port()) + "/";
return $resource(baseUrl+'rest/users/beforebar/:id',{}, {
query: { method: 'GET', isArray: true },
get: { method: 'GET' },
login: { method: 'POST', url:baseUrl+'rest/users/login'},
loginAnonymous: { method: 'POST', url:baseUrl+'rest/users/loginAnonymous'},
logout: { method: 'POST', url:baseUrl+'rest/users/logout/:id'},
register: { method: 'POST', url:baseUrl+'rest/users/register'}
});
}]);
Example of usage :
userSrv.logout = function(user,successFunction,errorFunction)
{
var userSrv = new User_Resource();
userSrv.$logout({user.id}, //params
function (data) { //success
console.log("User.logout - received");
console.log(data);
if (successFunction !=undefined)
successFunction(data);
},
function (data) { //failure
//error handling goes here
console.log("User.logout - error received");
console.log(data);
var errorMessage = "Connexion error";
if (errorFunction !=undefined)
errorFunction(errorMessage);
});
}

Categories

Resources