I need to pass 4 variables to controller so that I can do what I want to do with it, however I get an error:
Missing argument 1 for
App\Http\Controllers\ProfileController::getGoogle()
Here's my Controller:
function getGoogle($lat, $lng, $destinationLat, $destinationLng) {
print_r($lat);
print_r($lng);
print_r($destinationLat);
print_r($destinationLng);
}
and ajax:
function getDirections(lat, lng, destinationLat, destinationLng) {
$.ajax({
url: '/google/',
type: 'post',
data: {
lat: lat,
lng: lng,
destinationLat: destinationLat,
destinationLng: destinationLng
},
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
Route:
Route::post('google/', 'ProfileController#getGoogle');
You are actually sending POST variables to the controller, but you are accepting them in controller as GET variables,if you want to read the variables, your controller should be like this:
function getGoogle(Request $request) {
print_r($request->input('lat'));
print_r($request->input('lng'));
print_r($request->input('destinationLat'));
print_r($request->input('destinationLng'));
}
Remember to import Request as use Illuminate\Http\Request;
You aren't passing any parameter via the url and is passing via ajax POST params so you need to change your controller method definition to
function getGoogle() {
print_r(Input::get('lat'));
print_r(Input::get('lng'));
print_r(Input::get('destinationLat'));
print_r(Input::get('destinationLng'));
}
Related
I am new to Laravel.
Trying to Pass ID from View to Controller but getting Error
POST http://127.0.0.1:8000/getbuffaloidformonitor 404 (Not Found)
This is my View BuffaloMonitor :
$(document).on('click', '.viewmonitormodal', function() {
var modal_data = $(this).data('info').split(',');
$('#viewbuffaloID').val(modal_data[1]);
var buffaloid = document.getElementById('viewbuffaloID').value// get buffalo id from textbox to get data for that ID
alert(buffaloid);
//alert(data);
$(function() {
$.ajax({
method : "POST",
url: "/getbuffaloidformonitor",
data: {
'_token': $('input[name=_token]').val(),
'id': buffaloid,
},
success : function(response) {
alert(response);
}
});
});
}
This is BuffalomonitorCOntroller :
public function getbuffaloidformonitor(Request $req) {
$data = buffalodata::find($req->id);
alert(data);
$id = $req('data');
return $id;
}
This Is Route
Route::post('/getbuffaloidformonitor/{id}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
Your post route has {id} but it's not necessary. This is what you need Route::post('/getbuffaloidformonitor','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
pass id to the link http://127.0.0.1:8000/getbuffaloidformonitor
as you write the route
Route::post('/getbuffaloidformonitor/{id}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
You are just pass id by routes Params, so the URL must like this
http://127.0.0.1:8000/getbuffaloidformonitor/yourbuffaloid
You need to change URL.
$.ajax({
method : "POST",
url: "/getbuffaloidformonitor/" + buffaloid,
data: {
'_token': $('input[name=_token]').val(),
//'id': buffaloid, remove this line
},
success : function(response) {
alert(response);
}
});
If you use this script in you blade template just use
const url = '{{ route("getbuffaloidformonitor",":id") }}'
$.ajax({
method : "POST",
url: url.replace(':id',buffaloid),
data: {
'_token': $('input[name=_token]').val(),
//'id': buffaloid, remove this line
},
success : function(response) {
alert(response);
}
});
If your routes {id} is optional just
Route::post('/getbuffaloidformonitor/{id?}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
with question on your id route you can use both by pass id by route params or you can pass id by data post.
In controller
public function getbuffaloidformonitor(Request $req, $id = null)
{
// id is get from route params
$getId = $req->get('id') // this one get from data post.
}
I would to avoid nesting a bunch of ajax calls inside the 'success' event of one another. I was wondering if someone could guide me in the right direction on how to do something like this? Where one ajax call is dependent on another's return value?
The getLoginAccess() function will be used in many other methods in a similar manner.
If the first one fails i would like to just have it return a 'null' value which i can then take into account before running the second ajax call. Below i demonstrate a psuedo example of what im trying to do.
The method getLoginAccess returns a dictionary of data that is required for the second method createItem to execute. So only if getLoginAccess returns valid data will createItem continue on to call the actual ajax call.
Thank you
function getLoginAccess() {
$.ajax({
url: '.../api/v1/auth/access_token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Connection': 'keep-alive'
},
data: {
grant_type: 'client_credentials',
username: 'johnDoe',
password: '******'
},
success: function (data) {
console.log(JSON.stringify(data));
return data;
},
error: function (data) {
console.log(data);
return null;
}
})
}
function createItem() {
var login = getLoginAccess();
if (login == null) {
return false;
}
$.ajax({
url: '.../api/v1',
method: 'POST',
headers = {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'access': `${login.access_token}`
};
data: {},
success: function (data) {
console.log(JSON.stringify(data));
},
error: function (data) {
console.log(data);
}
})
}
window.onload = function(){
createItem();
};
If you want to refactor the part where the login is verified we could create an intermediate function .. something like this:
Your login function here
function getLoginAccess(){
// Return login data or null
}
Here we can create an intermediate function to deal with the dependencies of the next execution. If the login returns something other than null, the function passed as a parameter will be executed.
function intermediateFunction(functionName,login){
if(login){
window[functionName]();
}
}
Here are the other functions you have created.
function createItem() {
// Do something
}
function listItem() {
// Do something
}
Here instead of calling the createItem() function you call the intermediary
window.onload = function(){
intermediateFunction(getLoginAccess(), "createItem");
};
So basically you would always call the intermediate function that would check the login before calling a particular function. I believe that this is how I would refactor :)
i want to ask about this question, because this is make me crazy.
So i want to load datatables using ajax, i got this in view
$.ajax({
type: "GET",
url: "facility/getAllData",
success: function(data) {
console.log(data);
}
});
Then this is my routes
Route::get('/master_data/facility/getAllData', 'FacilityController#getAllData')->name('facility.getAllData');
The last Part is my controller
public function getAllData()
{
$facilities = Facility::all();
return response()->json($facilities);
}
Thats all my code, i already use App\Facility; what is wrong with my code? thanks
You are using a named route so you will need to add something like this to your view:
$.ajax({
type: "GET",
url: {{ route("facility/getAllData") }}, // named route
success: function(data) {
console.log(data);
}
});
or use the full route url url: "/master_data/facility/getAllData"
I am posting my form data to A controller but when I post data I am not getting in the controller when I call print_r($_POST); its returning null array I don't know what I have missed
Please let me know what inputs you want from my side
var data2 = [];
data2['user_firstname'] = user_firstname;
data2['user_lastname'] = user_lastname;
data2['user_phone'] = user_phone;
data2['user_email'] = user_email;
data2['user_username'] = user_username;
data2['user_password'] = user_password;
console.log(data2);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "http://localhost/shago/register/submit",
data: { 'data2': data2 },
// dataType: "text",
success: function(resultData) { console.log(resultData); }
});
controller code
public function submit()
{
print_r($_POST);
}
You can use the following
public function submit(Request $request)
{
dump($request);
}
Try adding Request as parameter on your submit function
public function submit(Request $request)
{
print_r($request);
}
Also, do you really need to pass your information as an array?
You could just create a new object and pass that as well.
var data2={
'user_firstname': user_firstname,
'user_lastname': user_lastname,
'user_phone': user_phone,
'user_email': user_email,
'user_username': user_username,
'user_password': user_password
};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "http://localhost/shago/register/submit",
data: data2,
success: function(resultData) { console.log(resultData); }
});
You need to inject Request Class injection into submit method. This can help you:
public function submit(\Illuminate\Http\Request $request)
{
dd($request->all()); // will print all data
}
of if you don't want to inject Request then this code may helps you
public function submit()
{
dd(request()->all()); // will print all data
}
Good Luck !!!
Maybe the request was intercepted by Laravel CSRF Protection policy.In order to prove it, you should add request URL in VerifyCsrfToken middleware file, like following:
protected $except = [
'yoururl'
];
If you can get the data you expect in your controller, then I am right.
Thanks all i found error in when i am sending array data now i have modified code and its working fine
see code
$.ajax({
url: "register/submit",
type: "post",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {'user_firstname':user_firstname,'user_lastname':user_lastname,'user_phone':user_phone,'user_email':user_email,'user_username':user_username,'user_password':user_password},
success: function(result){
console.log(result);
}
});
}
In my laravel 5.3 application I have enable CSRF checking globally for all ajax requests.
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
But I have an ajax GET request for an external api as follows.
$.ajax({
url: "https://api.xxxxxxxxxxx/v1/" +code+ "?api_key="+API_KEY,
type: "GET",
dataType: "text",
success: function (data) {
},
error: function (msg) {
}
});
I need to avoid CSRF checking here. I have tried two ways but nothing works for me. In VerifyCsrfToken.php
1st way
class VerifyCsrfToken extends BaseVerifier
{
protected $except = [
'https://api.xxxxxxxxx/v1/*'
];
}
2nd way
class VerifyCsrfToken extends BaseVerifier
{
if ( ! $request->is('https://api.xxxxxxxxx/v1/*'))
{
return parent::handle($request, $next);
}
return $next($request);
}
Please figure it out, how to solve this issue.
Finally, I figured out a way within javascript. We can delete the particular header before ajax call, then reassign the header again.
delete $.ajaxSettings.headers["X-CSRF-Token"];
$.ajax({
url: "https://api.xxxxxxxxxxx/v1/" +code+ "?api_key="+API_KEY,
type: "GET",
dataType: "text",
success: function (data) {
},
error: function (msg) {
}
});
$.ajaxSettings.headers["X-CSRF-Token"] = $('meta[name=_token]').attr('content');
You can override the ajaxSetup in that ajax call like this.
$.ajax({
url: "https://api.xxxxxxxxxxx/v1/" +code+ "?api_key="+API_KEY,
type: "GET",
dataType: "text",
headers : {},
success: function (data) {
},
error: function (msg) {
}
});
Although, you shouldn't use ajaxSetup.
The settings specified here will affect all calls to $.ajax or Ajax-based derivatives such as $.get(). This can cause undesirable behavior since other callers (for example, plugins) may be expecting the normal default settings. For that reason we strongly recommend against using this API. Instead, set the options explicitly in the call or define a simple plugin to do so. : https://api.jquery.com/jquery.ajaxsetup/
This should help
$.ajax({
type:'GET',
url:"https://api.xxxxxxxxxxx/v1/" +code+ "?api_key="+API_KEY,
data:{_token: "{{ csrf_token() }}",
},
success: function( msg ) {
}
});