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);
}
Related
I am trying to call a controller function from an AJAX call. The view loads from the same controller, but I'm not able to call the function.
Here is the controller code:
// This function will get ajax call where pass two variables and a method name doSomeAction
class Posts extends \Core\Controller
{
public function addNewAction()
{
View::renderTemplate('Posts/addnew.html', [
// 'posts' => $posts
]);
}
public function doSomeAction()
{
echo "here";
// your action code ....
}
}
Here is my Ajax script call function
<script>
$(".submitcontr").click(function() {
$.ajax({
url: 'POST/doSomeAction',
dataType: 'json',
data: {
id: 'value'
},
success: function (data) {
console.log(data);
},
error: function () {
alert('error');
}
});
});
</script>
Laravel 5.
I load view from controller using ajax.
When load first time then everything okay.
But when press f5 then it not work. ctrl+f5 then Okay.
I don't know what happen.
Please help me.
Controller
class TopSliderController extends Controller
{
public function index(Request $request)
{
return view('home.top_slider');
}
}
My javascript
(function($) {
load_view("/topic", "GET", "#test_top", []);
}(jQuery));
function load_view(url, method, field_id, param = []) {
$.ajax({
url: url, //+= '?_=' + (new Date()).getTime()
method: method,
data: {param},
timeout: 10000,
datatype: "html",
success:function(result)
{
$(field_id).html(result);
}
});
}
View
<div id="test_top">
</div>
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]);
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');
I'm using cakePHP 3.0 and I have a problem while using ajax. Indeed, I would like to execute the action "viewTab" of my controller "SpecimensController" on an array coming from my view "specimen"
<script type="text/javascript" >
var tab = new Array();
function updateResult(){
$.ajax({
type:"POST",
url:"<?php echo Router::url(array('controller'=>'specimens','action'=>'index'));?>",
data:{datas: $("select[name='filtreVariable\\[\\]']").map(function(){return $(this).val();}).get()},
dataType: 'text',
async:false,
success: function(data){
alert('success');
},
error: function (data) {
alert("error");
}
});
}
$("#filtre").submit(function(){
updateResult();
});
</script>
The action "viewTab" is just doing:
echo "success";
But I can't find the right url so the function success can be called. I tried many things and I always have the function error of ajax that is called. :/
If you haven't yet, place this line of code in your AppController where your initialize function is:
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
In your controller for the function you're calling via ajax, try something like this:
public function index()
{
$data = ['testing'];
$this->set(compact('data'));
$this->set('_serialize', 'data');
}
http://book.cakephp.org/3.0/en/controllers/components/request-handling.html