this is my controller:
/**
* #Route("/order", name="finish")
*/
public function createAction(Request $request)
{
$form = $this->createForm(OrderType::class);
// get data using the ids pass to the request...
// handle the form and redirect to homepage
return $this->render(
"orders/order_view.html.twig",
['order'=>$form->createView()]
);
}
I would like to pass some IDs to the request so i can get the needed data with doctrine.
After that handle the form create new order and add to it the products that i already have thanks to the ids passed.
i tried passing the ids using ajax on button click:
$.ajax(
{
type: 'POST',
url: '/order',
data: {'arr':[2,3,4]} // sample ids
}
).done(function (data) {
console.log(data)
}).fail(function () {
console.log("some error")
})
but it just returns the HTML. What i need is to render the form in the specified route ("/order") so i can handle it and insert into the database the new order with products added to it
I here answered to like this question:
Symfony2.8. How to get data from post request
You can use for POST request :
$request->request->get('data');
For GET request:
$request->query->get('data');
For FILE queries:
$request->files.
Related
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
I'm trying to send a text that is typed via ajax to a php page that will make a query using that text that is received. I want to know how to send the value of variable nmClient to the php page. I tried the following code and the return was 500 (Internal Server Error). I'm using the framework Symfony
Jquery
var name = $("#name").val();
$.ajax({
url: "../search",
type: "POST",
data: {'name':name},
dataType: "json"
}).done(function(response) {
console.log(response);
}).fail(function(jqXHR, textStatus ) {
console.log("Request failed: " + textStatus);
}).always(function() {
console.log("done");
});
PHP
public function searchAction(Request $resquest)
{
if ($request->isXMLHttpRequest()) {
$name = $request->get('name');
return new JsonResponse(array('name' => $name));
}
return new Response('This is not ajax!', 400);
}
I believe you're trying to access the parameter name in the incorrect place. The get() method is available on the ParameterBag instance, not the Request instance. Try the following:
$name = $request->request->get('name');
Per the docs here:
Each property is a ParameterBag instance (or a sub-class of), which is a data holder class:
request: ParameterBag;
query: ParameterBag;
cookies: ParameterBag;
attributes: ParameterBag;
files: FileBag;
server: ServerBag;
headers: HeaderBag.
All ParameterBag instances have methods to retrieve and update their data:
get() Returns a parameter by name.
Here is the example from that same page:
// the query string is '?foo[bar]=baz'
$request->query->get('foo');
In the docs example case, the parameters are passed via the GET method as a query string but they access them via the query ParameterBag instance. You'll want to use the request Parameter Bag instance since your parameters are passed via the POST method.
In my view I have some data that I can use $data in this $data are several other arrays with a key. Now my goal is to when a user selects something from a dropdown I want to update this $data array without doing a redirect.
I am aware I need to use AJAX and my AJAX call works fine I am just a tad confused on what I am supposed to do in my controller method I need to do something like this but without refreshing the page but this would remove all my other data that is already in the $data array from before
This is my method:
/**
* Fetches a company
*
* #param $companyId
*/
public function fetchCompany($companyId)
{
$company = Company::where('id', $companyId)->first();
$data['company'] = $company;
return view('this should be the same view that I did my ajax call from', ['data' => $data]);
}
So I want to add this $company to the already existing $data array that I am using in my view.
Answering from what I have understand so far.
public function fetchCompany($companyId)
{
$company = Company::where('id', $companyId)->first();
return response()->json($company);
}
then you need to call ajax like this
<script>
$(document).ready(function(){
$("whatever your dropdown id").change(function(){
$.ajax({
url:'yoururl',
type: 'whatever datatype',
dataType:'json',
success: function(data){
var x;
for(x in data){
$("#div1").append(data[x]);
}
}
});
});
});
</script>
(1/1) ErrorException
Argument 2 passed to App\Http\Controllers\priceDetails::finalSubmit() must be an instance of Illuminate\Http\Request, none given
Error I'm getting while passing multiple parameters with controller function.
Ajax code:
<script type="text/javascript">
$(document).ready(function () {
$('#finalSubmit').click(function() {
var form1 = $('#priceform').serialize();
var form2 = $('#formdescription').serialize();
var form3 = $('#additionaldescription').serialize();
$.ajax({
url:"{{url('dbvalue')}}",
type: 'GET',
data: {form1: form1, form2: form2, form3: form3},
dataType:'json',
success:function(data){
alert(data);
}
});
});
});
</script>
Laravel route:
Route::get('dbvalue','priceDetails#finalSubmit');
Controller:
public function finalSubmit(Request $priceform,Request $formdescription)
{
$var1 = $this->addPriceDetails($priceform);
$var2 = $this->addProductDetails($formdescription);
$var3 = $this->addAdditionalInformation($additionaldescription);
$var4 = $this->addImages($imagesform);
echo("success");
}
This what I'm trying to give multiple form parameters in laravel controller function.
addPriceDetails fn:
public function addPriceDetails(Request $priceform)
{
$priceInfo = new priceInfo ;
$priceInfo->id=$this->getpriceDetailsId();
$priceInfo->SKUID=$priceform->input('skuid');
$priceInfo->deviceCategoryId=$priceform->input('dataId');
$id=$priceInfo->id;
$priceInfo->save();
return response()->json([
'SKUID' => $priceInfo->SKUID,
'sellingPrice' => $priceInfo->sellingPrice,
'id' =>$this->getpriceDetailsId()
]);
}
What you are attempting to do simply does not work. Just because you sent data of two form in your 1 ajax request does not mean laravel will interepret it as two request. That is simply not possible.
What you have done in your code is get get data from 3 forms and make a json object from them and sent that json object in 1 get request. You cannot send multiple request in 1 request. This is as fundamental as it gets.
The best way to get the result you want is to accept 1 request object in you controller and parse it to get data from multiple forms that you sent.
You need to make your function as
public function finalSubmit(Request $request)
{
$var1 = $this->addPriceDetails($request->form1);
$var2 = $this->addProductDetails($request->form2);
$var3 = $this->addAdditionalInformation($request->form3);
//$var4 = $this->addImages($imagesform);//you dont't have $imagesform
return response()->json(["response"=>"success"]);
}
Also change http verb from GET to POST
type: 'POST', //in ajax, it is good send bulk data in post not in get
In route
Route::post('/dbvalue','priceDetails#finalSubmit');
I'm using Laravel 5.2. On my index page, I've got a button to add a new entry, which brings up the form in a lightbox. This form then submits via the create method.
I also have each entry listed on this page, with the ability to edit them inline, which submits via the update method.
I've setup validation via a Request. This means when someone misses something on the add, it redirects to the index method with errors. The errors only show though, when the lightbox is triggered by the user.
I know I can use $errors to see any errors, but I don't see how I can differentiate between the create and update forms for the sake of forcing the lightbox to appear on reload with create errors. Is there a way to do that?
Update:
Suggestion was made to use AJAX to bypass the reload issue, but now I'm getting a 422 return:
AJAX call:
(function(){
var submitAjaxRequest = function(e){
var form = $(this);
var method = form.find('input[name="_method"]').val() || 'POST';
$.ajax({
type: method,
url: form.prop('action'),
data: form.serialize(),
success: function(data){
console.log(data)
}
});
e.preventDefault();
}
$('form[data-remote]').on('submit', submitAjaxRequest);
})();
Request:
public function response(array $errors)
{
$response = parent::response($errors);
if ($this->ajax() || $this->wantsJson()) {
return $response;
}
return $response->with('requestMethod', $this->method());
}
I've also tested the ajax call and it works fine when the validation rules are met. It only fails if the validation comes back with something incorrect in the input.
You could override the response method so that you can flash the type of request.
In you Request class you could add
public function response(array $errors)
{
$response = parent::response($errors);
if ($this->ajax() || $this->wantsJson()) {
return $response;
}
return $response->with('requestMethod', $this->method());
}
(With ajax you wouldn't need to worry about the page reload so we can just return the original response.)
In the above I'm assuming you're using POST for your create methods and PUT or PATH for your update methods. If this is not the case you could use a way that make sense to you to differentiate between the requests.
Then in your view you could do something like:
#if(session('requestMethod') == 'POST')
https://laravel.com/docs/5.2/responses#redirecting-with-flashed-session-data
If you are going to use ajax, as I mentioned in the comment above, you will need to make sure you use the error method within the ajax call:
$.ajax({
type: method,
url: form.prop('action'),
data: form.serialize(),
success: function (data) {
console.log('success', data)
},
error: function (data) {
console.log('error', data)
}
});
Hope this helps!