Ajax url not working in magento1.9 under Adminhtml folder of custom module - magento-1.9

Ajax url not working in magento1.9 under Adminhtml folder of custom module tried many method but still not work for me.
function getsubcategories(cat_id){
$j.ajax({
type : 'GET',
url:'<?php echo $this->getUrl('modulename/Adminhtml_controllername/function_name/?category_id='+cat_id); ?>',
success:function(data){
console.log(data);
//~ var returnedData = JSON.parse(data);
//~ alert(returnedData);
//~ var str='';
//~ $.each(returnedData, function(key, value) {
//~ str=str + '<option value='+key+'>'+value+'</option>';
//~ });
//~ $('#subcategory').html(str);
}
});
}
Please tell me how to pass controller's function name in URL

Instead of $this->getUrl(), you can try
Mage::getUrl('modulename/Adminhtml_controllername/function_name/?category_id='+cat_id');
And you can this function in your controller
protected function _isAllowed() {
return true;
}

Related

Cannot access data of deserialized json

I'm using ajax to send data to my controller, here's how I do it
var formData = JSON.stringify( $('#SubmitForm').serializeArray() );
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
data: {formData},
url: '{{route("fileController.sendFiles")}}',
success: function(response) {
console.log(response);
},
error: function(response){
console.log(response);
}
});
Here's the route
Route::post('/sendFiles', ['uses' => 'FileController#sendFiles'])->name('fileController.sendFiles');
And the controller
public function sendFiles(Request $request)
{
//$data = json_decode($request->input('formData'), true);
//return $request->input('allFiles');
$data = json_decode($request->input('formData'), true);
return $data['allFiles'];
}
However, I get this error
"message": "Undefined index: allFiles"
When I check the contents of $request, I can see that allFiles array is clearly there, but how do I access it?
P.S. I've tried changing the second param when decoding to false, there's no difference.
$request data array
First of all your request data is simple array of objects. So you cannot index it with "allFiles".
Second since we have multiple objects with attribute name="allFiles[]", what you can do is filter those objects and return the values of it. (I don't know how are you going to use it, but this is how the code looks)
public function sendFiles(Request $request)
{
//$data = json_decode($request->input('formData'), true);
//return $request->input('allFiles');
$data = json_decode($request->input('formData'), true);
//filter all allFiles object
$allFiles = array_filter($data, function($obj){
if(isset($obj->name)){
return $obj->name=="allFiles[]";
}
return false;
});
//get values for all the filtered objects
$allFilesValues = array_map(function($obj){ return $obj->value; }, $allFiles);
return $data['allFiles'];
}
Let me know if this works for you.

How to access rootscope in component view

I have angular controller dashboard and set the root scope value in dashboard and access that root scope value in component inside the dashboard template using scope..but i don't know whether this is correct or not..and am not able to get that value
function DashBoardController($http, $window, $rootScope, apiurl, $scope, $location,$interval) {
var ctrl = this;
ctrl.$onInit = function () {
getUser();
};
function getUser(){
$http({
method: 'GET',
url: apiurl + '/getUser',
}).success(function (data, status) {
if (data.status == true) {
$rootScope.user = data.result;
$rootScope.test = "TEST";
}
});
}
function Controller1($rootScope,$scope, $timeout,$http, apiurl,$interval) {
var ctrl = this;
$scope.value = $rootScope.test;
alert($scope.value);
$scope.value1 = $rootScope.user;
console.log($scope.value1);
}
app.module('app').component('component1', {
templateUrl: '../resources/views/component/component1.html',
controller: Controller1
});
})(window.angular);
am getting undefined
From template you can access rootscope variables via $root.varName

how to define angular methods

I'm a regular consumer of advice from Stackoverflow. It's an invaluable tool - thanks for all the help!
But this is my first question: I'm very new to Angular but I've been doing server side stuff for donkeys years.
I've got a method on a controller, which calls a server REST service. My problem is that the method is called whenever the controller is instantiated. I know there's got to be another way of declaring the function, but I've got no idea of what to search for.
Here's my html:
<html lang="en" data-ng-app="mLS" ng-controller="mLSController">
<head>....</head>
...
<li><a ng-if="userName" ng-click="Logout()">logout</a></li>
and my module (the module def is elsewhere, but it seems ok)
var app = angular.module('mLS');
app.controller('mLSController', function ($scope, $http, $window, $location) {
$http({
url: '/api/UI/GetUsername',
method: 'GET'
}).success(function (data, status, headers, config) {
$scope.userName = data;
$scope.desiredPath = $location.path();
if (!$scope.userName && $scope.desiredPath != '/Account/Login')
$window.location.href = '/Account/Login';
});
});
function Logout($http) {
$http({ url: '/api/UI/Logout', method: 'GET' });
}
//app.
// controller('mLSController', function ($scope, $http) {
// $scope.Logout = function () {
// $http({ url: 'api/UI/Logout', method: 'GET' });
// };
// });
//app.
// controller('mLSController', ['$scope', '$http', 'Logout', function ($scope, $http, Logout) {
// $scope.callLogout = function () {
// Logout();
// };
// }]).
// factory('Logout', ['$http', function (protocol) {
// protocol({ url: 'api/UI/Logout', method: 'GET' }).success(function() {
// $scope.Logout = true; });
// }]);
So my problem is that the current code:
function Logout($http) {
$http({ url: '/api/UI/Logout', method: 'GET' });
}
just isn't called at all, and if I put it on the controller, Logout() is called when the controller is instantiated. Which isn't ideal.
Please help!
If you want the Logout function to be exposed to DOM (via Angular), you need to put it on $scope. There is no other option to call it using angular directives (ng-click).
Else, if you want it to be called before your app/controller are instantiated, use native javascript's onclick() event.
Warning: if you use onclick, you cannot set $scope variables.
So, thanks to Bharat, I've got it working!
This is the solution:
var app = angular.module('mLS');
app.controller('mLSController',
// function added to the controller
function ($scope, $http, $window, $location) {
$scope.Logout = function () {
$http({ url: 'api/UI/Logout', method: 'GET' });
return ;
};
$http({ url: '/api/UI/GetUsername', method: 'GET' }).success(function (data, status, headers, config) {
$scope.userName = data;
$scope.desiredPath = $location.path();
if (!$scope.userName && $scope.desiredPath != '/Account/Login')
$window.location.href = '/Account/Login';
});
});
For completeness, I could wrap the GetUsername call in a function, but the question is answered.
I can't upvote your answer, Bharat, because I haven't asked enough questions yet, but thanks so much!

AngularJS : Factory JSON Array with HTTP GET

I'm developing my first AngularJS app using the Google Docs API to pass it JSON data.
This is an example of the factory I'm using:
app.factory('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
return {
news:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/1/public/values?alt=json', {cache: true});
},
updates:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/2/public/values?alt=json', {cache: true});
},
docs:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/3/public/values?alt=json', {cache: true});
}
}]);
I wanted to clean up a bit the code and decided to use services instead of making the calls in the controller itself. It works normally, but it's a pain in the ass the fact that I still need to write long $scopes because of the structure of the Google API. This is how I get the values in the controller:
app.controller('homeCt', ['$scope', 'Data', function ($scope, Data){
Data.news().success(function (data) {
$scope.totalNews = data.feed.entry.length;
});
}]);
Is there a way that I can set the factory service to pass me the data just using:
$scope.totalNews = Data.news()
Or at least removing the 'feed.entry'?
Data.news().success(function (data) {
$scope.totalNews = data.length;
});
Thank you very much!
example of service - resolve the success with the data you want
app.service('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
this.news =function(){
return $http.get(googleDocs + apiKeys.googleDoc +'/1/public/values? alt=json', {cache: true})
.then(function(data){
return data.feed.entry.length;
});
}
}]);
the controller - since you already resolved the data in service hence..
app.controller('homeCt', ['$scope', 'Data', function ($scope, Data){
Data.news().then(function (data) {
$scope.totalNews = data;
});
}]);
working example
var app = angular.module('app', ['ionic'])
.service('Data', ['$http',
function($http) {
var googleDocs = 'https://spreadsheets.google.com/feeds/list/1aC1lUSxKatfxMKEy1erKDSAKgijSWOh77FDvKWhpwfg/1/public/values?alt=json';
this.news = function() {
return $http.get(googleDocs, {
cache: true
}).then(function(res) {
return res.data.feed.entry;
});
}
}
])
.controller('homeCt', ['$scope', 'Data',
function($scope, Data) {
Data.news().then(function(data) {
console.log(data);
})
}
]);
I'll give you a way of doing it, a way that I don't recommend at all (a service should not handle the scope), but for me it is the only way you have if you don't want to destroy the "async" of your ajax call :
app.factory('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
return {
news:news,
updates: updates,
[...]
}
function news(scopeValue) {
$http.get(googleDocs + apiKeys.googleDoc +'/1/public/values?alt=json', {cache: true}).success(function(data){
scopeValue = data;
});
}]);
and then, call it that way in your controller :
Data.news($scope.totalNews);

angularJS add JSON by http request

want to download a JSON of beercat('bieres.json') in this.bieres
How could I do?
function() {
var app = angular.module('monStore', []);
app.service('dataService', function($http) {
this.getData = function() {
return $http({
method: 'GET',
url: 'bieres.json'
});
}
});
app.controller('StoreController', function($scope,dataService){
this.bieres = [];
dataService.getData().then(function(dataResponse) {
$scope.bieres = dataResponse.data;
});
...
});
I think it's my access by this.bieres that it's wrong,
the Json is loaded in the console, but a blank page is in result