I'm suffering a lot trying to do this, in words:
Trying to send a token to a myfunction.php so it can do it's job, then make it return 2 variables so I can use em in my Javascript controller (Made with angularJS).
So far i heard I should use $http, but I can't understand how I should do this
create an angularjs service and use it in your controller.
here is the service which can provide Create, read, write and delete functionality:
app.service("MainService", ['$http', function ($http) {
this.getItems = function (url) {
return $http.get(url);
};
this.getItem = function (id, url) {
return $http.get(url + "/" + id)
};
this.post = function (itemToCreate, url) {
var request = $http({
method: "post",
url: url,
data: itemToCreate
});
return request;
};
this.put = function (id, itemToChange, url) {
var request = $http({
method: "put",
url: url + "/" + id,
data: itemToChange
});
return request;
};
this.delete = function (id, url) {
var request = $http({
method: "delete",
url: url + "/" + id
});
return request;
};
}]);
next add this service as a dependency to your controller and use it's methods like this:
app.controller("MyCtrl", ['$scope', '$rootScope', '$timeout', 'MainService', function ($scope, $rootScope, $timeout, MainService) {
//Get All Items::
$scope.GetItems = function () {
var getAllItems = MainService.getItems("YOUR_API_URL_FOR_GET_ITEMS");
getAllItems.then(function (response) {
$scope.items = response.data;//use items with ng-repeat in you html code
})
.catch(function (response) {
alert("YOUR_ERROR_MESSAGE");
})
.finally(function () {
alert("AFTER_METHOD_EXECUTION");
});
};
//Create New Item::
$scope.Create = function () {
//CREATE an Object and send it via post request. for example:
var category = new CategoryObject($scope.Title, $scope.Description);
var promisePost = MainService.post(category, "YOUR_API_URL_FOR_Post_Item");
promisePost.then(function (response) {
alert("SUCCESSFUL");
})
.catch(function (response) {
alert("YOUR_ERROR_MESSAGE");
})
.finally(function () {
alert("AFTER_METHOD_EXECUTION");
});
};
//Edit an Item::
$scope.Edit = function () {
//CREATE an Object:
var category = new CategoryObject($scope.Title, $scope.Description);
//Then set it's Id
category.Id = $scope.CategoryId;
var promisePut = MainService.put($scope.CategoryId, category, "YOUR_API_URL_FOR_Put_Item");
promisePut.then(function (response) {
alert("SUCCESSFUL");
})
.catch(function (response) {
alert("YOUR_ERROR_MESSAGE");
})
.finally(function () {
alert("AFTER_METHOD_EXECUTION");
});
};
//Delete an Item::
$scope.delete = function (id) {
var promiseDelete = MainService.delete(id, "YOUR_API_URL_FOR_Delete_Item");
promiseDelete.then(function (response) {
alert("SUCCESSFUL");
})
.catch(function (response) {
alert("YOUR_ERROR_MESSAGE");
})
.finally(function () {
alert("AFTER_METHOD_EXECUTION");
});
}
}]);
Related
New to Angular, I am accessing data from db via $http services and want to replace values in a textarea content matching words found in the db.
app.controller('myController', function($scope, $http) {
$scope.translate = function() {
$http
.get('translate.php')
.then(function(data){
var alldata = data.data;
angular.forEach(alldata, function(v,k) {
$scope.message = alldata.replace("\\b"+v.one+"\\b/gi",v.two);
});
}, function(data) {
// error handling
});
};
})
Textarea has ng-model of "message". It's not working and I'm getting an error:
TypeError: alldata.replace is not a function
try this,
app.controller('myController', function($scope, $http) {
$scope.message = '';
$scope.translate = function() {
$http
.get('translate.php')
.then(function(data){
var alldata = data.data;
angular.forEach(alldata, function(v,k) {
$scope.message = $scope.message.toString().replace("\\b"+v.one+"\\b/gi",v.two);
});
}, function(data) {
// error handling
});
};
})
I tried to upload a file via api to server.
function uploadUsing$http(file) {
file.upload = Upload.http({
url: 'api/upload' + $scope.getReqParams(),
method: 'POST',
headers: {
'Content-Type': file.type
},
data: file
});
file.upload.then(function (response) {
file.result = response.data;
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
file.upload.progress(function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
If console.log(file), there is image data, but when i send the request to server i get an empty array.
server function:
public function uploadAPI(Request $request)
{
$image = $request->file('file');
dd($image); ---------> return []/null
return response()->json('upload hit server');
}
What's the problem here? Thanks!!
Have you tried using
Upload.upload({
url: 'upload/url',
data: {file: file, 'param1': $scope.param1}
});
Instead?
i would like to submit my form to a php file
var myApp = angular.module('myApp',[]);
myApp.controller('FormController', function($scope, $http) {
$scope.task = {
group: 'fix',
showme: true,
select1: 'basique',
select2: 'micro',
select3: '1',
select4: '1',
select5: 'jour'
};
var server = 'http://localhost/myserver.php?cd=add';
var parameters;
$scope.submit = function(form) {
angular.forEach($scope.task, function(value, key) {
if(value) {
if(key === 'date') {
value = new Date(value).getTime();
}
parameters += '&'+key+'='+value;
}
});
console.log(server+parameters);
//$http.post(server+parameters)
//.success(function(result) {
// console.log("success", result);
//})
//.catch(function(error) {
// console.log("error", error);
//})
}
})
this is the codpen codepen
is this valid?
the result at should be http://localhost/myserver.php?cd=add'name='&'describe='
You are create query string using foreach() and pass with server url but. you are use $http.post(). you have to use $http.get() if you want pass with server url.
Below example with help
$scope.submitForm = function($valid)
{
myobject = {'email' : $scope.user.email, 'pass' : $scope.user.pass};
Object.toparams = function ObjecttoParams(obj)
{
var p =[];
for (var key in obj)
{
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
url: WSURL + '/login',
method: "POST",
data: Object.toparams(myobject),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config)
{
}
}).error(function (data, status, headers, config)
{
});
}
I am trying make an ajax request to php from angular js. But I am not getting the data I have sent by php file.
I'm getting this error:
Error:input is undefined
My source:
File view.html:
<div class="content-panel" >
<div class="content-panel-title">
<h2> Date : {{jalse.contentDate}}</h2>
</div>
<div>
<h4>{{jalse.contentAbstract}}</h4>
<div>
{{jalse.contentText}}
</div>
</div>
</div>
File app.js:
(function () {
var app = angular.module('myApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'contentsCtrl',
templateUrl: 'views/contents.php'
})
.when('/jalse/:jalseId', {
controller: 'recordsCtrl',
templateUrl: 'views/jalse.php'
})
.otherwise({redirectTo: '/'});
});
}());
File jalseFactory.js:
(function () {
'use strict';
var jasleFactory = function ($http, $q) {
var factory = {};
factory.getJalse = function () {
var deferred = $q.defer();
$http({method: 'GET', url: 'includes/records.php'}).
success(function (data, status, headers, config) {
deferred.resolve(data);
}).
error(function (data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
};
return factory;
};
jasleFactory.$inject = ['$http', '$q'];
angular.module('myApp').factory('jasleFactory', jasleFactory);
}());
File recordsCtrl.js:
(function () {
'use strict';
var recordsCtrl = function($scope, $routeParams , jasleFactory) {
var jalseId = $routeParams.jalseId;
$scope.records = jasleFactory.getJalse();
$scope.jalse = null;
function init() {
for (var i = 0, len = $scope.records.length; i < len; i++) {
if ($scope.records[i].contentID == parseInt(jalseId)) {
$scope.jalse = $scope.records[i];
break;
}
}
}
init();
};
recordsCtrl.$inject = ['$scope','$routeParams', 'jasleFactory'];
angular.module('myApp').controller('recordsCtrl', recordsCtrl);
}());
Your code is making an ajax and then assuming that the response is set the records variable, As you are dealing with async call you should call the method which are going to call on $scope.records inside its success.
Factory Method
factory.getJalse = function () {
return $http({method: 'GET', url: 'includes/records.php'});
};
Controller
(function() {
'use strict';
var recordsCtrl = function($scope, $routeParams, jasleFactory) {
var jalseId = $routeParams.jalseId;
jasleFactory.getJalse().success(function(data, status, headers, config) {
$scope.records = data.records;
init(); //this will fix your error.
}).
error(function(error, status, headers, config) {
console.log("error occured " + error)
});
$scope.jalse = null;
function init() {
for (var i = 0, len = $scope.records.length; i < len; i++) {
if ($scope.records[i].contentID == parseInt(jalseId)) {
$scope.jalse = $scope.records[i];
break;
}
}
}
//we will call this as soon as $scope.records gets filled
//init();
};
recordsCtrl.$inject = ['$scope','$routeParams', 'jasleFactory'];
angular.module('myApp').controller('recordsCtrl', recordsCtrl);
}());
Update
Your json is also not valid because it contains a malicious field which
"contentText": "1\ u0645\ u0637\ u0644\ u0628 < \/p>",
"3":"1\ u0645\ u0637\ u0644\ u0628 < \/p>",
If you remove this two field, you code will work as is
Working Plunkr
I am trying make an ajax request to php from angular js. But I am not getting the data I have sent by php file.
I'm getting this error:
Error: [ng:areq] http://errors.angularjs.org/1.3.15/ng/areq?p0=recordsCtrl&p1=not%20a%20function%2C%20got%20undefined
My source:
File app.js:
(function () {
var app = angular.module('myApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'contentsCtrl',
templateUrl: 'views/contents.php'
})
.when('/jalse/:jalseId', {
controller: 'recordsCtrl',
templateUrl: 'views/jalse.php'
})
.otherwise({redirectTo: '/'});
});
}());
File view.html:
<div class="content-panel">
<div class="content-panel-title">
<h2> {{jalse.contentDate }}</h2>
</div>
<div ng-repeat="jalse in records">
{{jalse.contentDate }}
</div>
File jalseFactory.js:
(function () {
'use strict';
var jasleFactory = function ($http, $q) {
var factory = {};
factory.getJalses = function () {
var deferred = $q.defer();
$http({method: 'GET', url: 'includes/records.php'}).
success(function (data, status, headers, config) {
deferred.resolve(data);
}).
error(function (data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
};
return factory;
};
jasleFactory.$inject = ['$http', '$q'];
angular.module('myApp').factory('jasleFactory', jasleFactory);
}());
File recordsCtrl.js:
(function () {
'use strict';
var recordsCtrl = function ($scope, $http, $routeParams) {
var jalseId = $routeParams.jalseId;
$scope.records = jasleFactory.getJalse();
$scope.jalse = null;
function init() {
for (var i = 0, len = $scope.records.length; i < len; i++) {
if ($scope.records[i].contentID == parseInt(jalseId)) {
$scope.jalse = $scope.records[i];
break;
}
}
}
init();
};
}());