cant't query json data in laravel 5.2 - php

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

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

Laravel x AngularJS $http.post authentication issue

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.

Angularjs Get Method

Getting the error below in console and data is not fetching from mysql. Can anyone suggest on the error below:
Used angularjs, php, mysql and materializecss
Error: $http.get(...).success is not a function
Here is the code of my controller:
.controller('dashBoardCtrl', ['$scope', '$http', function ($scope, $http)
{
$http.get("dbconnection/db_read.php")
.success(function(data)
{
$scope.data = data;
console.log(data);
})
.error(function()
{
$scope.data = "error in fetching data";
});
}]
);
Can you try
$http.get().then(function(result){console.log(result)});
I believe .success is deprecated.
You're more than likely using AngularJS 1.6+
.success(fnSuccess) and .error(fnError) don't exist any more.
Use .then(fnSuccess, fnError) instead.
So
$http.get(...).success(function(){})
is now
$http.get(...).then(function success() {}, function error() {});
Let's look at the documentation:
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
So you pass your success and error callbacks to then() not success().

Laravel 5: Fetch ajax data in route and pass to controller

I'm using Laravel 5 and want to make ajax call to a controller with some data:
$.ajax({
url : "/getOrgById",
data : JSON.stringify({id:1})
})
The routes.php has:
Route::get('/getOrgById', 'HomeController#getOrgById');
HomeController.php:
public function getOrgById($data) {
//code here fails with message 'Missing argument 1 for HomeController::getOrgById()
}
How can I pass the data from ajax to route and then to controller?
I think the below example is what you're looking for
Route
Route::post('/getOrgById', 'HomeController#getOrgById');
Controller
public function getOrgById(Request $request) {
$id = $request->input('id');
}
JS
var myJsonData = {id: 1}
$.post('/getOrgById', myJsonData, function(response) {
//handle response
})
You should really look into resourceful controller actions. If you are wanting to fetch an organisation by its ID then you have an organisaiton entity, so create a corresponding organisation controller. This controller can then have a method to show an organisation by on its primary key value:
class OrganisationController
{
public function show($id)
{
return Organisation::findOrFail($id);
}
}
The route for this would look like:
Route::get('/organisations/{id}', 'OrganisationController#show');
You can then request this route via AJAX like so:
$.ajax({
method: 'GET',
url: '/organisations/' + id
});
You can use Input to get your variable
public function getOrgById() {
$data = \Input::get('data')
}
You can define paramers in your route:
Route::get('/getOrgById/{id}', 'HomeController#getOrgById');
And call it through:
$.ajax({
url : "/getOrgById" + id
})
You were almost right, but when using $data in your function declaration you're actually requiring a Query String variable, rather than a form request.
You have to add your Form Request in your Controller method, like so:
public function getOrgById(Request $request){
// do something here...
return response()->json(array('foo' => 'bar'));
}
Try with this,
HTML Form
<div id="loadingResponse"></div>
{!!Form::open(array('url'=>'test/submit', 'id'=>'submitForm','method'=>'POST'))!!}
{{Form::token()}}
<input type="text" name="data"/>
<button type="submit" class="btn btn-small btn-info">Send Data</button>
{{Form::close()}}
JS Ajax
$("#submitForm").submit(function(event) {
event.preventDefault();
$.ajax({
url : 'test/submit',
data : new FormData($("#submitForm")[0]),
dataType : 'JSON',
type : 'POST',
beforeSend: function(){
$("#loadingResponse").html("<img src='{{asset('img/loading.gif')}}' />");
},
success: function(response){
console.log(response);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('Error '+xhr.status+' | '+thrownError);
},
});
});
PHP Route
...
Route::post("test/submit","TestController#submit");
...
PHP Controller
class TestController extends Controller
{
...
public function submit(Request $request)
{
response()->json(['msj' => $request->input('data')]);
}
...
}
ajax:
$.ajax({
type:'get',
url:'/getOrgById',
data:{
id:1
},
success:function(res){
}
});
routes.php:
Route::get('/getOrgById', 'HomeController#getOrgById');
HomeController.php:
public function getOrgById(Request $request) {
dd($request);
}

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

Categories