Laravel - pass 2 variables from view to controller with ajax - php

I have this function for my delete button
Löschen
and the route in routes/web.php
Route::post('/delete-file', 'MyController#deleteEventFile');
that hits this function
public function deleteEventFile($eventid, $filename){
dd($eventid);
}
and this is my ajax function:
function deleteFile(eventid, filename){
//alert(filename);
//alert(eventid);
$.ajax({
url: '/delete-file/',
type: "post",
data:{ _token: "{{csrf_token()}}", eventid: eventid, filename: filename },
dataType: 'json',
});
}
And i always get this error:
Missing argument 1 for App\Http\Controllers\MyController::deleteEventFile()
my variables can't get through...
How to pass the eventid and filename to controller

According to your code, you are expecting route to give 2 params - eventid & filename into the controller method.
Instead it you should code your method like this:
public function deleteEventFile() {
$event_id = request()->get('eventid');
$file_name = request()->get('filename');
}
Fetch the POST data from the laravel's request() method instead.
Hope this helps!

You can access your parameters in controller using Request like bellow.
public function deleteEventFile(Request $request){
dd($request->eventid);
}

Related

How to redirect from one blade view to another blade view, and pass dynamically generated variable to it?

In my view , let's call it View-A, I get an input from user in a prompt and assign it to a variable, and then I need to load in browser another view, say View B, while passing it that variable.
Say, in my viewA.blade.php, I have taken user's input and assigned it to variable usersInput. Now I need to send it to view B, whose route in web.php is defined at Route::get('editRecord', 'MyController#displayEditRecordView')->name('editRecordFormView');.
Question is how do I load route(editRecordFormView) in browser and pass usersInput variable to it, from javascript written in my blade view?
#Tushar In in my ViewA.blade.php:
$.ajax({
url: url_editRecordView.url,
data: {
usersInput: dataToSend.usersInput,
},
method: "get",
cache: false,
success: function (dataReturned, stringStatus, jqXHR) {
console.log("dataReturned from mYController.displayEditRecordFormView:-");
console.log(dataReturned);//check
console.log("Type of dataReturned:-" + typeof dataReturned); //SAME DATA COMES BACK, AS THE DATA I SENT
},
error: function (jqXHR, stringStatus, stringExceptionThrown) {
alert("Error! status: " + stringStatus + " ExceptionThrown: " + stringExceptionThrown);//check
}
});
In my MyController:
public function displayEditRecordFormView (Request $request) {
error_log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");//check
error_log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");//check
$title= $request->input('usersInput');
error_log("In displayEditRecordFormView: title: ".$title);//check
$allPaintingsArray = $this->getAllPaintingsArraySanitized();
$data = [
"allPaintingsArray"=>$allPaintingsArray ,
"title"=>$title
];
return view("paintings.editRecordForm")->with("allGoodData", $data);
}
Instead of AJAX call why don't use something like this:
var url = "/editRecord?usersInput=dataToSend.usersInput;
window.location.href = url;
catch variable In controller:
$title= request()->filled('usersInput');// or find a way according to Laravel version
You can make use of AJAX. Just set an event handler for when the user gives an input, and send a request containing the user input to a method in your View-A controller via AJAX and from there you can redirect to View-B along with the value that you got from the request.
EDITED
Instead of using view() method try using redirect() method like this:
return redirect()->route('editRecordFormView', ['input' => 'userInput']);
To know more about redirects please refer to this

AngularJS UI-router pass param from view to state resolve

I am trying to pass params in ui-sref then access it to state resolve.
HTML View
ui-sref="reservation({check_in: check_in, check_out: check_out})"
I am trying to get the params passed in ui-sref to the resolve.
This is some code in my controller when I don't yet use a resolve.
$http.get('server/getFilteredRooms.php', {
params: {
check_in: data.check_in,
check_out: data.check_out
}
}).then(function(res){
Then I tried to implement resolve because I want to wait for the data to get before rendering the view. In that way, I believe, I will not encounter undefined due to data from http function is not yet returned.
JS (app.js)
.state("reservation", {
url: "/reservation",
templateUrl: "pages/reservation.html",
controller: "ReservationController",
resolve : {
promiseObj : function($http){
return $http({
method: 'GET',
url: 'server/getFilteredRooms.php',
params: {
check_in: check_in,
check_out: check_in
}
});
}
}
})
And I am trying to access in my PHP file like this.
PHP
$check_in = $_GET['check_in'];
$check_out = $_GET['check_out'];
To receive those parameters in the state's resolve, at first, you need to declare those in the state's configuration. Change the state's configuration, and introduce a params key as follows:
.state("reservation", {
url: "/reservation",
templateUrl: "pages/reservation.html",
controller: "ReservationController",
params: {
check_in: null,
check_out: null
},
resolve: ...
Then, modify the resolver as follows:
promiseObj: function($http, $transition$){
var params = $transition$.params();
return $http({
method: 'GET',
url: 'server/getFilteredRooms.php',
params: {
check_in: params.check_in,
check_out: params.check_in
}
});
}
This way, your resolver knows that it should extract the parameters' values from the URL and passes those to the HTTP call.

Form AJAX post response cycle in Laravel 4.1.*

I have a rather old site that I have inherited as part of a new position - it's been built to Laravel 4.1.* version specs.
My issue is Response::json returning undefined variables in the response, using standard AJAX post method with all CSRF stuff and ajaxSetup() defined correctly.
application.blade.php
$.ajax({
type: 'POST', //This will always be a post method for the supplier chain check form.
url: 'supply-us/application', //URL endpoint for the post form method: we'll set this to the controller function we're targeting.
data: { 'companyName': values['companyName'] }, //This will carry the form data that is needed to be passed to the server.
success: function (response) {
console.log(response['companyName']); << THIS LINE RETURNS "undefined"
console.log(typeof response) << THIS LINE RETURNS string
},
error: function (response) {
console.log(response);
},
});
values['companyName'] returns what I input into the form. The above "response" simple chucks back html - so I think my routes might be incorrectly defined or incorrectly defined in the AJAX url param, perhaps? Here are the two applicable routes:
routes.php
Route::controller('supply-us/application', 'ApplicationController');
Route::post('supply-us/application', 'ApplicationController#processSupplierApplication');
ApplicationController.php:
<?php
use Illuminate\Http\Request;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication(Request $request) {
if (Input::has('companyName')) {
$this->companyName = Input::get('companyName');
$data = [
'success': true,
'companyName': $this->companyName
];
return response()->json($data);
}
}
}
Any pro-tips would be greatly appreciated!
to check what your are missing in controller when posting or getting your result
usually which i follow
in blade.php
<.form method="post" action="{{url('supply-us/application')}}".>
{{csrf_field()}}
<.input type="text" name="companyName".>
<./form.>
remove dot try this it will help you to find missing thing in controller
in your blade
<.input type="text" name="companyName" id="companyName".>
in your ajax
var company = $('#companyName').val();
$.ajax({
type: 'POST',
url: 'supply-us/application',
data: { 'Company':company,'_token': '{{ csrf_token() }}' },
success: function (response) {
alert(data) // if this not work then try this alert(data.company)
},
error: function (response) {
console.log(response);
},
});
in your controller
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication(Request $req) {
if (!$req->get('Company')==null) {
$company = $req->get('Company');
return response()->json($company);
}else{
$company="no input give";
return response()->json($company);
}
}
}

Laravel: How top pass id to controllore using ajax get

I am trying to pass a productId to a controllor in order to show the related product properties in a modal booststrap.
I would like tho show the pop up in the main page index. This is the related route:
Route::get('/', 'FrontendController#index');
This is tha ajax get call:
$("#getModal").on("click",function(){
$.ajax({
url: '{{url('./')}}',
type: 'GET',
data: { productId: 1 },
success: function(response)
{
console.log('Ajax submitted);
}
});
});
This is the request detected in the console:
localhost/SHOP-ONLINE/public/?productID=1
It seems everything is working fine. But, how can I pass the productId value in the controller? if I try following I cannot pass it:
public function index(Request $request) {
$productID = $request->productId
}
you need to use the get() method of the request object.
public function index(Request $request) {
$productID = $request->get('productID');
}
I think you can try this :
public function index(Request $request) {
$productID = $_GET['productID'];
}
Hope this work for you !!!

Sending variable by ajax in use of laravel

I am trying to send two variables through ajax into the php script in laravel.
It is actually not clear to me how to move these variables.
Would you mind guys to give me some advice on it? the newComment contains some string, and id is just a number.
var newComment = document.getElementById('newComment').value;
$.ajax({
type: 'get',
url: '/editcomment',
data: {newComment: newComment,
id: id},
success:function(){
alert('success');
},
error:function(){
alert('failure');
}
});
});
Here is my route:
Route::any('/editcomment/{id}/{newComment}', 'HomeController#editComment');
And here goes the function in homecontroller:
public function editComment(){
$aaa = Input::all();
return $aaa;
}
I am struggling with this for last 2 days, constantly looking at documentations and tutorials but have no idea how to do this.
You don't need to add the variables to the url for this request. The data you include in your ajax request will be send to the server as a post body.
Try changing the route to Route::any('/editcomment', 'HomeController#editComment');
And use
public function editComment(){
return Input::all();
}
This should display the id and the newComment
you have to change your route file like this :
Route::any('/editcomment', 'HomeController#editComment'); because yo dont need to ajax request parameter to send in route file.
And yes in your controller method editComment change like this:
public function editComment(){
if(Request::ajax()) {
return Input::all();
}
}
We have to check that requested by ajax call.
Try,
$_GET['newComment'] and $_GET['id']. This will work.
Thank you :)

Categories