Laravel x AngularJS $http.post authentication issue - php

I've successfully sent some information through AngularJS to my backend in Laravel, however, I'm facing some issues while trying to get some authenticated user data.
Basically, it just don't retrieve any authenticated user data from my backend.
AngularJS
$scope.generatePrescription = function () {
//check for token in meta tag
var csrf_token = $('meta[name=csrf-token]').attr('content');
console.log('CSRF_TOKEN =>'+csrf_token);
info = {
_token: csrf_token,
receita: $scope.receita,
receita_info: $scope.receita_info
};
$http({
method: 'POST',
url: apiURL + '/prescription/create',
data: info,
headers:{
'Content-Type': 'application/x-www-form-urlencoded',
}
}).then(
function(response){
console.log(response.data)
},
function(error){
console.log(error.data)
}
);
}
Api.php (Laravel)
Route::middleware('api')->post('/prescription/create','Dashboard\PrescriptionController#store');
PrescriptionController.php
public function store(Request $request, Prescription $prescription)
{
//receive prescription object
$data = $request->json()->all();
if(auth()->check()){
return 'authenticated!!!';
} else {
return 'user is not authenticated..';
}
}
How should I proceed to get my authenticated user variables?
Thank you in advance.

Related

How to insert sessionStorage data using ajax request in Laravel?

I'm very new to this ajax request using laravel and currently I'm stuck. I'm having trouble inserting the sessionStorage from database.
For example I have here in my sessionStorage:
Key Value
=================
gclid 12345
token abcde
I want to get the value for gclid or token values using ajax and store it in the database.
Here in my ajax I'm having trouble how to get these parameter values and store it in my db. I have this condition to get the key of the parameters like this logic:
This is in my controller:
if(key == gclid)
$traffic->traffic_type = $request->('gclid');
else if (key == token)
$traffic->traffic_type = $request->('token');
How do I pass this variables in my jquery and add a request in my controller to fetch it using ajax?
var gclid = sessionStorage.getItem('gclid');
var token = sessionStorage.getItem('token');
Ajax
// Tracking Parameters
function storeVisitorParameters() {
let url = '{{ route('trackvisit') }}';
var gclid = sessionStorage.getItem('gclid');
var token = sessionStorage.getItem('token');
const data = {};
$.ajax({
type: 'POST',
url: url,
data:data,
beforeSend: function (xhr) {
var token = $('meta[name="csrf-token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
complete: function() {
},
success: function (data) {
$.notify("Visitor Parameters Stored!", 'success');
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('server errors', thrownError);
}
});
}
TrafficController.php
class TrafficController extends Controller
{
// Store gclid or token parameters to traffic_tacking_table
public function storeVisitorParameters(Request $request)
{
$traffic = new TrafficTracking();
$traffic->user_id = $user->user_id;
if($traffic->traffic_type = $request->gclid;) // check if key = gclid
{
$traffic->traffic_type = $request->gclid; // store the key in db
$traffic->traffic_value = $request->get('gclid');
}
else if ($traffic->traffic_type = $request->token) // check if key = token
{
$traffic->traffic_type = $request->token; // store the key in db
$traffic->traffic_value = $request->get('token');
}
$traffic->ip_address = $request->ip();
$traffic->domain = $request->getHttpHost();
$traffic->save();
return response()->json($traffic);
}
}
web.php
Route::post('/trackvisit', 'TrafficController#storeVisitorParameters')->name('trackvisit');
migration
public function up()
{
Schema::create('traffic_tracking', function (Blueprint $table) {
$table->increments('traffic_id');
$table->string('ip_address');
$table->string('traffic_type');
$table->string('traffic_value');
$table->integer('user_id');
$table->timestamps();
});
}
my main goal is to only get the sessionStorage values and send a request to my controller.
In your php controller, change this if($traffic->traffic_type = $request->gclid;) to if($traffic->traffic_type == $request->gclid) , you're comparing the values right ?? It should be double == and remove ; inside if condition
In javascript catch csrf token as,
var _token = $('meta[name="csrf-token"]').attr('content');
In AJAX Request,
dataType: 'JSON', // Add datatype as JSON, optional still for good practice
data:{
_token: _token,
gclid: gclid,
token: token
},
Inside data {} you're passing the values (gclid, _token and your sessionStorage token) as JSON formatted data to laravel controller

read JSON data sent using post in jquery with laravel framework

I have this codes,
var obj = '{"items":[{"Code":"c101","Description":"Car"}]}';
$.post('get-items',obj,function(){
});
I used this code,
file_get_contents('php://input')
Because I cant get the POST Data that is sent.
Using the above code, I get the raw POST Data.
How can I read data sent without using file_get_contents('php://input')?
Because I can't use file_get_contents('php://input').
Here is my Laravel controller function,
public function getItems()
{
$data = file_get_contents('php://input');
if(isset($data))
{
...
}
}
Laravel 5.3 expects input to be sent in array format https://laravel.com/docs/5.3/requests#retrieving-input
Request sent through jQuery
$.ajax({
url: 'http://weburl.com/api/user/create',
dataType: 'json',
type: 'POST',
data: {'user': user},
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(null, status, err.toString());
}.bind(this)
});
Laravel UserController::create
public function create(Request $request)
{
$user = new User();
$user->name = $request->input('user.name');
$user->email = $request->input('user.email');
$user->password = $request->input('user.password');
$user->save();
return response($user, 201);
}
In a Laravel 5.2 controller's method you could do this:
public function store(Request $request)
{
$items = $request->input('items');
return [
'error' => false,
'items' => $items
];
}

cant't query json data in laravel 5.2

I'm making a adressbook app via laravel 5.2 and vuejs, my app needs CRUD functionality, i stuck at Update part, i send the data via ajax to laravel
and i get the data in laravel but i cant update rows.
this is my method in vuejs that handle updating:
updatecontact:function(){
var contactid = this.editingcontact.id;
var contact update = JSON.stringify(this.editingcontact);
this.$http({url: '/adressbook/'+contactid, data: {contactupdate} , method: 'PATCH'})
.then(function (response) {
console.log(response);
}, function (response) {
// error callback
});
and this the method that handles ajax request in laravel(it's a PUT)
public function update(Request $request, $id)
{
$adressbook = Adressbook::findorFail($id);
$adressbook->save($request->all());
}
at last this is how the data looks like:
contactupdate: "{"id":5,"companyName":"poolad","zamineKar":"test","tel":"44044440","fax":"44044422","email"}"
A better way to do it would just be to send this.editingcontact as the data:
updatecontact:function(){
var contactid = this.editingcontact.id;
this.$http({url: '/adressbook/'+contactid, data: this.editingcontact , method: 'PATCH'})
.then(function (response) {
console.log(response);
}, function (response) {
// error callback
});
Then this update code should work:
public function update(Request $request, $id)
{
$adressbook = Adressbook::findOrFail($id);
$adressbook->update($request->all());
}

Laravel 5 access to ajax Post Data

I'm trying to receive data from a form through AJAX on Laravel 5.
JavaScript code:
event.preventDefault(); // Disable normal behaviour of the element (Form)
var formData = {
form: $("#newCustomerForm").serialize() // Transmit all input data of the form serialized
}
console.log(formData); // Log to the console the Input data
$.ajax({
type: 'post', // POST Request
url: 'save', // Url of the Route (in this case user/save not only save)
data: formData, // Serialized Data
dataType: 'json', // Data Type of the Transmit
beforeSend: function (xhr) {
// Function needed from Laravel because of the CSRF Middleware
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
success: function (data) {
// Successfuly called the Controler
// Check if the logic was successful or not
if (data.status == 'success') {
console.log('alles ok');
} else {
console.log(data.msg);
}
},
error: function (data) {
// Error while calling the controller (HTTP Response Code different as 200 OK
console.log('Error:', data);
}
});
Route:
Route::post ('user/save', 'CustomerController#createNewCustomer');
Controller:
public function createNewCustomer (Request $request)
{
$inputArray = $request->all();
print_r ($inputArray['form']);
// Set JSON Response array (status = success | error)
$response = array ('status' => 'success',
'msg' => 'Setting created successfully',);
// Return JSON Response
return response ()->json ($response);
}
In the network tab I can see how the parameters look like:
radio-inline-left=on&firstname=sdsd&private_lastname=&private_title=&private_birthdate=&private_email=&business_email=&private_phone=&business_phone=&private_mobile=&business_mobile=&brand=&business_job_title=&business_address_street=sdsd&business_address_po_box=&business_address_addon_1=&business_address_addon_2=&private_zip=&private_location=&business_address_street=&business_address_po_box=&business_address_addon_1=&business_address_addon_2=&private_zip=&private_location=&source=social_media&source=&availability=on&additional-info={"status":"success","msg":"Setting created successfully"}
I also tried to access the data with $request->input('name of the field') but then it's always empty.
Does anybody have an idea what i'm doing wrong?
The problem is that you are calling $("#newCustomerForm").serialize(), and this method serializes the form in url-encoded parameters and not a json encoded body.
In this question an answer is provided for this to work.
You can access like this
$request['name of field'];
i think you need to receive the data in the controller as json:
$request->json('field_of_interest')
The problem is your formData variable. Instead of:
var formData = {
form: $("#newCustomerForm").serialize()
}
it should be
var formData=$("#newCustomerForm").serialize();

Http Post not sending data to another page in angular js

I am working on login form in Angular Js.The HTML and validation part is working fine.
The problem is when i send data using HTTP POST method to my servicecall PHP page and want to save it to DB.
I have tried all the way by setting this in JS
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
I have tried by setting enctype of form to
enctype="application/x-www-form-urlencoded"
as well.But none of them is working i am not able to get data via $_REQUEST, $_POST, $_GET any of these method.
I have also tried using PHP library function.
$postdata = file_get_contents("php://input");
But it gives some weird string which i can't handle because number of POST data could be hundreds.
So this there any other way to solve the problem.
Code for http request is
var req = {
method: 'POST',
url: 'servicecall.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
username: $scope.loginData.username,
password: $scope.loginData.password,
action : 'checkLogin'
} //First way of sending data
//Second way of sending data which is also not working
//data: "{username:"+$scope.loginData.username+",password:"+$scope.loginData.password+",action:checkLogin}"
}
$http(req).then(function(response){
console.log(response);
}, function(response){
alert("Error "+response);
});
At PHP page i do
print_r($_REQUEST);
print_r($_POST);
But it prints just blank array like array{}
Following the code that I am using for same purpose. Hope that may help you.
var app = angular.module('angularApp', []);
app.controller('loginCtrl', function ($scope, $http) {
$scope.login = function () {
var request = $http({
method: "post",
url: "login.php",
data: {
email: $scope.email,
password: $scope.password
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Successful HTTP post request or not */
request.success(function (data) {
if(data == "1"){
$scope.responseMessage = "Successfully Logged In";
}
else {
$scope.responseMessage = "Username or Password is incorrect";
}
});
}
});

Categories