How to pass multiple forms as parameter in laravel? - php

(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');

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

400 Bad Request after sending AJAX post request in Yii 2

I want to post data via ajax to some specific controller like this :
<script>
var myUrl = "<?php echo Url::to(['table/edit']); ?>";
</script>
$.ajax({
type : "POST",
url : myUrl,
data: {id: userID},
success : function(response) {
alert("Table is editted");
}
});
And in the controller I want to get this posted data and do some thing else.
But when I try this I am getting an error "400 (Bad Request)".
If someone can help it would be great! Thanks!
Just add csrf like :
<script>
var myUrl = "<?php echo Url::to(['table/edit']); ?>";
</script>
$.ajax({
type : "POST",
url : myUrl,
data: {id: userID,_csrf:'<?=\Yii::$app->request->csrfToken?>'},
success : function(response) {
alert("Table is editted");
}
});
yii\web\BadRequestException (represents HTTP error with code 400) can be thrown in following cases:
1) Unable to verify your data submission. CSRF validation is enabled and failed. I don't think it's the reason in your case, because it's enabled by default and included in meta tags. When using jQuery, you don't have to send it manually.
2) Missing required parameters.
If you have parameters without default values, for example:
public function actionTest($someParam)
{
...
}
If you didn't pass someParam, exception will be thrown.
3) Invalid JSON data in request body.
If you send JSON as parameter and it's not a valid JSON.
4) Invalid data received for parameter. Thrown during binding parameters to action:
if ($param->isArray()) {
$args[] = $actionParams[$name] = (array) $params[$name];
} elseif (!is_array($params[$name])) {
$args[] = $actionParams[$name] = $params[$name];
} else {
throw new BadRequestHttpException(Yii::t('yii', 'Invalid data received for parameter "{param}".', [
'param' => $name,
]));
}
Last two are rarely meet, especially the last one (can't remember even single time when I met it).
These should be all possible cases at the moment, I did global search through sources just to make sure.

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 :)

Sending json to symfony controller

I need to pass json data to my Symfony Controller. My ajax function looks like this:
var data = '{"firstname":"John"}';
$.ajax({
type: "POST",
url: save_url, //path to controller action
data: {json:data},
success: function(response) {
// Do something
}
});
In my controller, I try to get my data through:
public function createAction(Request $request) {
$data = $this->getRequest()->get('firstname');
return $this->render('MyBundle:Counter:test.html.twig', array(
'data' => $data
));
Just to see if this works, I send $data to be echoed in a template. In Firebug I can see the data being sent and everything seems to work, but $data is empty and nothing is echoed. Where am I doing this wrong?
EDIT: When I check the response in Fireburg console, I see my data there, in place, but it never appears in the template. var_dump($data) tells that $data is null. So, it seems data is being sent but the controller ignores it.
As Marek noticed:
$this->getRequest()
already returns the request object, you're accessing the request property of the request, that doesn't add up. Either try:
$data = $this->request->get('json');
Or use:
$data = $this->getRequest()->get('json');
You can, of course assign the return value of $this->getRequest() to a variable, and call the get method on that var from there on end... anyway, here's my initial answer, it does contain some more tips, and considerations you may find useful:
You should be able to get the data this way, though AJAX requests + echoing in a template? That does sound a bit strange. I don't see you passing the $data variable to a $this->render call anywhere.
This is a copy-paste bit from a controller action in one of my projects. It works just fine there:
public function indexAction()
{
if (!$this->getRequest()->isXmlHttpRequest())
{//check if request is AJAX request, if not redirect
return $this->redirect(
$this->generateUrl('foo_bar_homepage')//changed this, of course
);
}
$id = $this->getRequest()->get('id',false);//works fine
However, I can't begin to grasp why you're doing this:
var data = '{"firstname":"John"}';
Why not simply go for:
$.ajax({
type: "POST",
url: url,//post how you get this URL please...
data: {firstname: 'John'},//jQ will sort this out for you
success: function(response)
{
console.log(response);
}
error: function()
{
console.log('an error occured');
console.log(arguments);//get debugging!
}
});
Then, in your controller you're able to:
$this->getRequest()->get('firstname');//it should be John
You could even pass {json:{firstname: 'john'}} as the data param to $.ajax, the only difference in your controller will be, that you have to do this:
$data = $this->getRequest()->get('json');
$firstName = $data['firstname'];
That should work just fine, unless there's somthing you're not telling us :)
RECAP:
This is what I'd write:
public function createAction()
{//no Request param in controller
if (!$this->getRequest()->isXmlHttpRequest())
{//no ajax request, no play...
$this->redirect(
$this->generateUrl('homepage_route')
);
}
$data = $this->getRequest()->get('firstname');
//return json response:
return new Response(json_encode(array('dataReceived' => $data));
//return rendered HTML page:
return $this->render('MyBundle:Counter:test.html.twig', array(
'data' => $data
));
}
Of course, then the JS code should read:
$.ajax({
type: "POST",
url: 'route/to/create'
data: {firstname:'John'},
success: function(response)
{
console.log(response);
}
});
I have tested this, and I see no reason why this shouldn't work. It works just fine for me...
Please note this was #EliasVanOotegem original example but there are some obvious steps missing
in the controller i'm reading a few replies as in "I cannot see how this works as i'm getting null" this is because your not correctly keying your object.
i.e.
var data = { name : 'john' };
$.ajax({
type: "POST",
url: url,//post how you get this URL please...
data: {json : data},//jQ will sort this out for you
success: function(response)
{
console.log(response);
}
error: function()
{
console.log('an error occured');
console.log(arguments);//get debugging!
}
});
as you can now see accessing the requerst object like
$request->get('json');
refers to the post key for the json data
Is the content what you're trying to retrieve, neither params nor headers.
Try:
$request->getContent();
In your case $request->request->get('json') should do.

How to pass Array from Javascript to PHP

I have a function which saves an array each time the button is clicked to localStorage.The button will be clicked multiple times and I need to put this Array list into PHP somehow which is on another page from this file.
Thanks
a.js
(this function listens onLoad of the page)
function doFirst(){
var button = document.getElementById("button");
button.addEventListener("click", save, false);
var buttons = document.getElementById("clear");
buttons.addEventListener("click", clear, false);
var buttonss = document.getElementById("submittodb");
buttonss.addEventListener("click", toPHP, false);
$.ajax({
method: 'post',
dataType: 'json',
url: 'edit.php',
data: { items: oldItems }, //NOTE THIS LINE, it's QUITE important
success: function() {//some code to handle successful upload, if needed
}
});
}
function save(){
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {
'num': document.getElementById("num").value,
'methv': document.getElementById("methv").value,
'q1': document.getElementById("q1").value,
'q2':document.getElementById("q2").value,
'q3':document.getElementById("q3").value,
'q4':document.getElementById("q4").value,
'comm':document.getElementById("comm").value,
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));}
edit.php
$parsed_array = json_decode($_POST['items']);
and i get the error: Notice: Undefined index: items in /home/project/edit.php on line 9
In order to pass this array to PHP you need to:
JSon-encode it
Make an AJAX or POST request to PHP
Parse the passed array into PHP array
If you're using jQuery (if you're not you should start - it is really handy tool) steps (1) and (2) is as simple as
$.ajax({
method: 'post',
dataType: 'json',
url: 'the URL of PHP page that will handle the request',
data: { items: oldItems }, //NOTE THIS LINE, it's QUITE important
success: function() {//some code to handle successful upload, if needed
}
});
In PHP you can parse the passed array with just
$parsed_array = json_decode($_POST['items']);
There is a direct connection between { items: oldItems } and $_POST['items']. The name of variable you give to the parameter in javascript call will be the name of key in $_POST array where it ends up. So if you just use data: oldItems in javascript you'll have all your entities scattered around the $_POST array.
More on $.ajax, and json_decode for reference.
You can create an AJAX function (use jQuery) and send the JSON data to the server and then manage it using a PHP function/method.
Basically, you need to send the data from the client (browser) back to the server where the database hosted.
Call JSON.stringify(oldItems); to create the json string
Do a Do a POST request using AJAX.
Probably the simplest way is using jQuery:
$.post('http://server.com/url.php', { items: JSON.stringify(oldItems) }, function(response) {
// it worked.
});

Categories