Reading a very simple ajax request in Laravel - php

I lately managed to get a simple ajax post to work but can't get any of the data in the controller :
Ajax :
function verify(event) {
var title = event.title;
var start = event.start.format("h:m");
$.ajax({
url: "/admin/timetable/verify",
headers: {
'X-CSRF-TOKEN': $('#crsf').val()
},
type: "post",
contentType: "application/json; charset=utf-8",
data: {type : 'hi',titles : title},
dataType: "json",
success: function(response){
if (response['state']==='0')
toastr.error('Are you the 6 fingered man?'+response['msg']);
if (response['state']==='1')
toastr.info('Are you the 6 fingered man?');
},
error : function(e){
console.log(e.responseText);
}
});
}
Controller :
$d = Request::all();
dd($d);
return response()->json(['state'=>'0','msg'=>$d['titles']],200);
I tried Request all, Input all, Input::json()->all() .. nothing works always null or empty array [] ! I'm just trying to read the data sent from the ajax form !

I faced this lately. The problem (I don't know why) was about Get and POST.
Just transform route to a GET, make the ajax type as GET, and try with a very simple Input::all.
public function verifyClassroom(){
$Data = Input::all();
dd($Data);
}

This is my tested code and it works
function verify(event) {
$.ajax({
url: "/test",
headers: {
'X-CSRF-TOKEN': $('#crsf').val()
},
type: "post",
data: {type : 'hi',titles : "title"},
success: function(data){
alert(data);
},
error : function(e){
console.log(e.responseText);
}
});
}
and in my route closure
Route::post('test', function(\Illuminate\Http\Request $request){
$type = ($request->input('type'));
return $type;//returns type->hi
});

in the php controller you need to have something like this.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class YourcontrollernameController extends Controller {
public function test(Request $request) {
echo $request->input('type');
echo '/';
echo $request->input('titles');
die;
}
}
you can access the type and title by $request->input('type') and $request->input('titles')
ALso try using get method and
in yourproject/routes/web.phpweb.php
Route::get('/test', 'YourcontrollernameController#test');

Related

send data from jQuery to laravel controller

i'm using laravel and i want to receive data from jQuery to my controller to insert it to the database , i tried many methodes but without success
this is my script :
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$.ajax({
url:'/test',
type: 'POST',
dataType: 'JSON',
data: {
"name": "Name",
"color": "red",
},
});
and the controller :
public function test()
{
if(Request::ajax()) {
$data = Input::all();
}
dd(json_decode($data));
}
and finally the Route :
Route::post('/test',[
'uses' => 'TagsController#test'
]);
it seems ok for me but the result :( :
Maybe the problem is in your controller, because you don't tell the server, which table do you want to use to store your data
or maybe because of your url.. jquery does not understand what is {{}}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/test',
method: 'post',
data: $('#form-id').serialize(), // prefer use serialize method
success:function(data){
console.log(data);
}
});
Controller:
use Illuminate\Http\Request;
public function test(Request $request)
{
if($request::ajax()) {
$data = $request->color;
}
dd(json_decode($data));
}
I am using serialize because It's so powerful, I don't need to input one by one the field name
I don't know if your controller is used for only retrieve the data from client or you want to use ajax to store your data in database.. so, I am using $request->color to make sure that the data is retrieved from the client side
Add this meta tag in main blade page
<meta name="csrf-token" content="{{ csrf_token() }}">
And instead of old scholl jquery ajax.. just use Axios. it exist inside app.js. simple and very easy. it already detect the csrd-token meta tag. so no need to do in the form or header
change this
$.ajax({
url: '{{route("test")}}',
method: 'post',
data : {
"name": "Name",
"color": "red",
},
success:function(data){
console.log(data);
}
});
to this
axios.post('{{route("test")}}', {
"name": "Name",
"color": "red"
})
.then(function(response) {
console.log(response);
});
Your Route must be like this.
Route::post('/test',[
'uses' => 'TagsController#test'
])->name('test');
Your controller seems fine..
public function test(Request $request)
{
if($request->wantsJson()) {
$data = $request::all();
return $data;
}
}

How to correctly implement a simple search functionality with ajax in laravel?

I am trying to code a simple search functionality for learning purposes, but I am failing to make it work.
What I want for now is simply to pass some data(to a controller function) in a blade view with ajax and then display this data in another view via the same controller function.
What I currently have is this :
Routes :
Route::get('/search-results', 'HomeController#search')->name('search');
search in HomeController :
public function search(Request $request){
$data = $request->data;
return view('search-results')->with('data',$data);
}
the search-results view
#extends('layouts.app')
#section('content')
<h1>{{$data}}</h1>
#endsection
And finally the ajax :
var data = "success";
$.ajax({
url: 'search-results',
type: "get",
data: {data : data},
success: function(response){
if(data == "success")
console.log(response);
}
});
Can someone help me make this work? I am not sure what am I doing wrong...
You should return JsonResponse object to easy use data in JavaScript
Action:
public function search(Request $request){
$data = $request->data;
return new JsonResponse(compact('data'));
}
JavaScript:
$.ajax({
url: "/search",
type: "get",
data: {data : data},
success: function(response){
console.log(response);
}
});
Routes :
Route::get('/search-results', 'HomeController#search')->name('search');
search in HomeController :
public function search(Request $request){
$result = [];
$result['data'] = $request->data;
return response()->json($result);
}
the search-results view
#extends('layouts.app')
#section('content')
<h1 class="header"></h1>
#endsection
Ajax call :
var data = "success";
$.ajax({
url: "{{ route('search') }}",
type: "get",
data: {'data' : data},
success: function(response){
if(response.data == "success")
console.log(response.data);
$('.header').text(response.data);
}
});
Hope it's help you!!!
An AJAX call is asynchronous therefore you can make a call and return the results in a separate form. If you want to show your results in a separate form, i advise that you submit the form and then return the view with your data return view('search-results')->with('data',$data); or if you stick to an an ajax call, you return a response which will be sent to the form where the data was submitted from return response()->json(["data" => $data]);

Ajax request on Controller fails

I have a problem with the following code in Laravel. I need to send some variables to my controller, do something with them and return three variables back. I made have made the ajax call, the route and the controller but the ajax call fail. As an error code I receive this.
View
function gg() {
var slider_value = document.getElementById('paradnyi').value;
var checkbox_value = document.getElementById('check_box').value;
var dto = {slider_value : slider_value, checkbox_value : checkbox_value};
$.ajax({
url : "/calc_change",
contentType : 'application/json',
data : JSON.stringify(dto),
type : 'POST',
success: function(data) {
document.getElementById('visits').innerHTML = data[0];
document.getElementById('slaves').innerHTML = data[1];
},
error: function(xhr, str){
alert('Возникла ошибка: ' + xhr.responseCode);
}
});
}
Routes
Route::post('/calc_change',['uses'=>'PagesController#calc_change','as'=>'calc_change']);
Controller
public function calc_change(Request $request){
$data = array();
$data[]=1;
$data[]=2;
//dd($data);
return response()->json($data);
}
You have to add this code before ajax call in jquery section
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

Laravel: Send Data to Controller via AJAX Without Form

I need to send data via JS to a Laravel controller on a button click. I'm not using any form because the data is being created dynamically.
Every time i try to send the data, i get an Internal Server Error (500), but unable to catch that exception in the controller or the laravel.log file.
Here's what i'm doing:
Route:
Route::post('section/saveContactItems', 'SectionController#saveContactItems');
Controller:
public function saveContactItems($id, $type, $items, $languageID = "PT"){ ... }
JS:
$('button').on("click", function (evt) {
evt.preventDefault();
var items = [];
var id = $("#id").val();
var languageID = $("#languageID").val();
var data = { id: id, type: type, items: JSON.stringify(items), languageID: languageID };
$.ajax({
url: "/section/saveContactItems",
type: "POST",
data: data,
cache: false,
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (response)
{
console.log(response);
}
});
});
What am i doing wrong? How can i accomplish this?
UPDATE: Thanks to #ShaktiPhartiyal's answer (and #Sanchit's help) i was able to solve my issue. In case some else comes into a similar problem, after following #Shakti's answer i wasn't able to access the data in the controller. So, i had to stringify the data before sending it to the server:
data: JSON.stringify(data),
You do not need to use
public function saveContactItems($id, $type, $items, $languageID = "PT"){ ... }
You have to do the following:
public function saveContactItems()
{
$id = Input::get('id');
$type = Input::get('type');
$items = Input::get('items');
$languageID = Input::get('languageID');
}
and yes as #Sanchit Gupta suggested you need to send the CSRF token with the request:
Methods to send CSRF token in AJAX:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
If you use this approach you need to set a meta tag like so:
<meta name="csrf-token" content="{{csrf_token()}}">
or
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
UPDATE
as #Sanchit Gupta pointed out use the Input facade like so:
use Input;

Yii2 how to access POST data that's been sent using AJAX

I want to create a variable within my controller function that equals the POST value however I am unsure on how to access the POST value.
An answer would be great but any tips for debugging would be great too.
I have tried $_POST['save_id'] as well as $_POST[0]['save_id']
$('#save-file').click(function() {
var fileid = $(this).data('fileid');
$.ajax({
type: "POST",
url: "/files/save",
data: { 'save_id' : fileid },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//do something
console.log(fileid);
alert("working");
},
error: function (errormessage) {
//do something else
alert("not working");
}
});
});
for your url if the code is inside a PHP file i suggest you a proper path eg :
url: <?=Url::to(['/files/save']) ?>,
(Remenber of add use use yii\helpers\Url;)
If not a php refer to the absolute path properly
inside your FilesController in save Action
public function actionSave()
{
if (Yii::$app->request->isAjax) {
$data = Yii::$app->request->post();
//data: { 'save_id' : fileid },
$mySaveId = $data['save_id']
// your logic;
......
}
}

Categories