How to send data from angular js to laravel 5 server - angularjs

I am trying to send data from angular js to server.. Laravel5 is running on my server.. I can fetch data using this but can not send data.. My code is bellow
AngularJs Code:
var request = $http({
method: "get",
url: "http://www.myserver.com/json",
data: { email: $scope.email },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
request.success(function (data) {
alert(data.email);
});
Server code :
route is Route::get('json','JsonController#Json_login');
Controller code is
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Input;
class JsonController extends Controller
{
public function Json_login()
{
$email = Input::get('email');
$arr_Id_Status=array('email'=>$email);
echo json_encode($arr_Id_Status);
}
}
But it giving me null alert

Sounds like you should be using a POST rather than a GET request. You would need to create an appropriate POST route on your server but it's pretty much the same syntax on the client side, just change GET to POST.
var request = $http({
method: "POST",
url: "http://www.saadetera.com/json",
data: { email: $scope.email },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (data) {
alert(data.email);
});
Not used Laravel for a while but it would be something like:
Route::post('json','JsonController#handleLoginRequest');

Ideally, sending data will require a POST method while fetching will be using a GET method. Let's make the complete flow assuming you want to call a controller called your_controller and use its your_method function :
This suits for Laravel 5
Laravel Controller :
use Illuminate\Http\Request;
public function your_method(Request $request)
{
$data = $request->input(my_data);
//Server side data processing here
//Returning Json or anything else here
return response()->json(your_answer_here);
}
Route :
Route::post('your_url', ['uses' => 'your_controller#your_method']);
AngularJS : Here is the chunk of code allowing data sending, it requires $http service. Let's assume your data is contained in the my_data object.
$http.post('your_url', my_data)
.then(you_callback_success, your_callback_fail);

Related

angular $http post not sending data for service

I´m trying user $http post in angular, where the rest service receive an object. The data is a Json where I need pass with parameter for method in service.
My angular code (it´s doesn´t work for me):
$http({
method:'POST',
url:request.url,
data: JSON.stringify(objcsr);
headers: {'Content-Type':'application/json; charset=utf-8'}
}).then(function(objS){
alert('Success :- '+JSON.stringify(objS));
},function(objE){
debugger;
alert('error:- '+JSON.stringify(objE));
});
If I comment the row data, the comunication with service it´s ok:
$http({
method:'POST',
url:request.url,
//data: JSON.stringify(objcsr);
headers: {'Content-Type':'application/json; charset=utf-8'}
}).then(function(objS){
alert('Success :- '+JSON.stringify(objS));
},function(objE){
debugger;
alert('error:- '+JSON.stringify(objE));
});
My method in service:
public UserAccessDTO Authenticate(AuthenticationDTO authentication)
{
.....
}
I hope the object you are passing in data parameter is same as AuthenticationDTO class, its properties must be same. If that is fine then try running this.
$http.post('url',JSON.stringify(data),{headers: {'Content-Type':'application/json'}})
.success(function (data) {
alert('Success :- '+JSON.stringify(data));
});
As well I am assuming that you have included [HttpPost] attribute before your method. like this:
[HttpPost]
public UserAccessDTO Authenticate(AuthenticationDTO authentication)
{
.....
}

how i can send post data array angular and get data on api laravel

i have code like it on angular
my array :
[{"kode":"123","nama":"satu dua tiga"},{"kode":"321","nama":"tiga dua satu"}]
$http({
method: 'POST',
url: 'api/insertCustomerArr',
data: myarray
}).then(function successCallback(response) {
}, function errorCallback(response) {
});
and how i can get this data on controller laravel and how i can looping ?
public function insertCustomerArr(Request $request)
{
echo count($request);
exit;
}
this code result count 1, how i can get data?
You can check using
return $request->all();
this will return all the data you posted from angular request
Laravel $request object has a request property inside of it.
So that basically $request->request->all(); should contain all the data that came from angular.

Angular: $http change method on adding data with post

I am using fuse template and accessing my web service by using $http, its working fine if i am using method: 'POST' without send any data but whenever i am adding some data with post like: data: {text:'test'} and send request to my web service its change the method type POST to OPTIONS.
My Code:
$scope.submit = function(){
$http({
method: 'POST',
url: 'http://www.example.com/api-link',
data: {test: 'hello'},
header: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(result){
console.log(result);
});
}
When i am checking in browser network its showing method type OPTIONS. Can anyone please tell what is wrong in my code?
Thanks

What is type of data angular sending?

What is type of data angular sending? I use laravel + angular. I`m trying, but this script return 405 error. Method not allowed.
.controller('adminCtrl', function( $scope, $http ){
$scope.collection = [];
$scope.newData = [];
$scope.newrecord = function() {
$scope.collection.push($scope.newData);
$http({
url: '/newrecord',
method: "POST",
data: $.param($scope.collection),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function(data){
console.log(data);
})
}
})
You are getting 405 - Method not Allowed because the server you are sending your request does not have POST it the white list of methods allowed to be used to perform requests to that given API.
It's not an angularJS issue, it's a server configuration issue.
$http sends data as json.
You do not need to serialize params using "$.param", data is plain javascript object, which is send to your REST endpoint.
So attach just "$scope.collection) and do not set Content Type manually, it is json by default.
POST can be send also with convenience method.
$http.post('/someUrl', data, config).then(successCallback, errorCallback);

Slim, Postman and AngularJs : $app->request->getBody() vs $app->request->post()

I'm a beginner. I've written a test application made of an AngularJs GUI on the client side and a PHP API on the server side.
This is the angular service handling the requests
myApp.factory('Book', ['$resource', 'API_URL', function($resource, API_URL){
return $resource(API_URL + '/books/:bookId', {bookId: '#bookId'}, {
get: { method: 'GET', isArray:true },
update: { method: 'PUT'},
save: { method: 'POST'},
delete: {method:'DELETE'},
});
}]);
When I submit a book from the Angular app I can catch the POST in Slim by using
$post_a = json_decode($app->request->getBody());
//$post_b = $app->request->post(); //this would be empty
When I use Postman and I perform a POST I can catch the POST in Slim by using
//$post_a = json_decode($app->request->getBody()); // this would be empty
$post_b = $app->request->post();
I don't get why there is this difference. Could you please explain?
Am I not meant to catch the post just with $app->request->post(); in both the cases? Why the post coming from Angular can be caught only with $app->request->getBody()?
The $app->request->post() method retrieves key/value data submitted in a application/x-www-form-urlencoded request. If the request uses a different content-type (e.g. application/json), you can retrieve the raw request body with the $app->request->getBody() method and decode it as necessary. Let me know if you have further questions.
You could still use
$post_b = $app->request->post()
in Slim.
As long as you call this REST service from html form (AngularJS) by passing the data as form value formatted instead of as JSON.
If in AngularJS you have the data in JSON format, you have to translate it first into form. Below is the example how to invoke this REST service:
Object.toparams = function ObjecttoParams(obj) {
var p = [];
for (var key in obj) {
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
method: 'POST',
url: url,
data: Object.toparams(myobject),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
myobject is the data in JSON format that is going to be created
Thanks Josh..Your answers works for me.
Steps to follow:
1.You need to send request in json format under raw tab like this:
{"username":"admin","password":"admin"}
2.You need to set Content-Type to application/json in the headers.
That's it and it will work.

Resources