How to get Ajax post request by symfony2 Controller - ajax

I send text message like this
html markup
<textarea id="request" cols="20" rows="4"></textarea>
javascript code
var data = {request : $('#request').val()};
$.ajax({
type: "POST",
url: "{{ path('acme_member_msgPost') }}",
data: data,
success: function (data, dataType) {
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error : ' + errorThrown);
}
});
symfony2 controller code
$request = $this->container->get('request');
$text = $request->request->get('data');
but $text is null ...
I have tried normal post request (not Ajax) by firefox http request tester.
/app_dev.php/member/msgPost
Controller works and $text has a value.
So I think the php code is OK, there is the problem on Ajax side, however
'success:function' is called as if succeeded.
How can you get the contents of javascript data structure?

First, you don't need to access the container in your controller as it already implements ContainerAware
So basically your code should look like this in your Controller.php
public function ajaxAction(Request $request)
{
$data = $request->request->get('request');
}
Also, make sure by the data you are sending is not null by using console.log(data) in the JS of your application.
And finally the answer of your question : you are not using the right variable, you need to access the value of $('#request').val() but you stored it in a request variable and you used a data variable name in your controller.
Consider changing the name of the variable, because it's confusing.

If you're sending the data as JSON — not as form urlencoded — you need to access the request body directly:
$data = json_decode($request->getContent());

You are doing it wrong when obtaining the value, you must use:
$data = $request->request->get('request');
'cause request is the name of your parameter.

Related

How to fetch ajax request data in cakephp 2 controller?

I'm trying to send some data from my view to my controller via ajax. How do I retrieve this data in my action?
I've tried jQuery's $.ajax and $.post methods, providing the url and data, but using $this->data, $this->request->data, $_POST, $_GET or $_REQUEST doesn't work (all return as empty arrays).
$.ajax({
url: "<?php echo Router::url( array("controller" => "Progression", "action" => "submit", $user['User']['id']) ); ?>",
type: 'post',
data: { name: "John" }
}).done( function(data) {
console.log(data);
});
function submit() {
$this->request->allowMethod('ajax');
$this->autoRender = false;
$data = array();
$data['answer'] = $this->request->data; // or any of $_POST, $_GET, etc.
return json_encode($data);
}
My console always keeps printing {"answer":[]}. I checked the network tab of my devtools and the data is successfully listed under Form data, yet I can't seem to get hold of the data in the action.
EDIT:
Thanks to Greg Schmidt I found out that my request indeed got redirected: first it gives me a 302, then it makes a new request without the post data and returns a 200. I just can't find what the critical difference is between the two requests (URLs look the same, no case difference or anything). Can anybody help me with that?
First request:
Second request:

Laravel 5.6: Why does AJAX POST to Controller not show data load in Controller?

I have been working on this for hours,and not getting anywhere. Essentially, my Ajax call appears to be working well. I am pulling in form data from a view. I can see the XHR data when I look into Chrome Network. I have a status 200, and "OK". However, no matter what I do, I can not get any data to show in my controller. I have tested my route by commenting it out and sure enough I get an error, so that is positive. Also the XHR data shows the correct url as well. But even just a simple dd($request) inside the controller gives me nothing, not even an empty []. I have tried every option and Googled this to death. What am I doing wrong - Thanks !
Abbreviated HTML
<form action="" method="POST" id="formData">
<fieldset>
{{ Form::hidden('customer_id',$customer[0]->id,['id'=>'customer_id'])}}
{{ Form::hidden('lastname1',$customer[0]->lastname1,['lastname1'=>'lastname1'])}}
{{ Form::hidden('reference',$quotation[0]->reference,['id'=>'reference'])}}
</fieldset>
</form>
AJAX
$("#editsubmit").on('click', function () {
event.preventDefault();
var formData =$("#formData").serialize();
var id = $("#reference").val();
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
type: 'POST',
contentType:'JSON',
processData: false,
url: '/save_edit/'+id,
data: {
"_method": 'POST',
"result": formData,
},
error: function () {
alert('there has been a system level error - please contact support')
}
});
});
Route
Route::post('/save_edit/{id}','QuotationController#save_quote_edited');
Controller
public function save_quote_edited(Request $request){
dd(json_decode($request->getContent(), true));
}
To process forms you should not be calling $request->getContent() you should be calling $request->all() to get all parameters, $request->get('foo') or $request->foo to get a single parameter, or $request->get(['foo','bar','baz') to get multiple parameters.
And for bonus points if you used Laravel's Form Request Validation you could call $request->validated() and get only the parameters which passed the validation checks.
Your route requires a parameter of "id" but you do not have that parameter in your controller method.
Route::post('/save_edit/{id}','QuotationController#save_quote_edited');
Try :
public function save_quote_edited(Request $request, $id){
*** insert code here ***
}

Method not Allowed error on Ajax Post request (500 error) Laravel Framework

I am working on a Post Ajax request Function. Where the function takes some data and send it through an enabled CSRF_token post Request to a controller and then after evaluations on controller a message sent back to the view. but it seems i miss a small thing in my code.
My controller
public function PostMessage(Request $request){
$message=$request->someData; //getting data from request variable
return response()->json($message);
}
My jquery Ajax request function
$('.SendAjaxPostRequest').on('click', function() {
var value=$('.MessageHolder').val();
$.ajax({
method: 'POST',
url:'{{route('SVCate')}}', //SVCate is my route to the controller
dataType: 'JSON',
data: {_token:token,'someData':value,}
// #token gets it's value from a local view javaScrip Variable
})
.done(function (data) {
console.log(data);
})
});
My route function
Route::post('SendMessage','NessageController#PostMessage')->name('SVCate');
Check your apostrophes in the url. You are ending the string and beginning the string around SVCate change it to url:"{{route('SVCate')}}" to make sure that SVCate stays a string and does not break your string.

Laravel ajax send multi dimension associative array

I would like to do something very simple but I can't make it work, I only want to send via jquery ajax a multi dimensional array to laravel and get the data back.
For example:
var info = JSON.stringify([{'key':'val1'},{'key':'val2'},{'key':'val3'}]);
$.ajax({
type: "POST",
url: "{!! route('ajaxactivityperemployee') !!}",
data: {"mydata":info},
success: function(msg){
console.log(msg);
}
On the other side, on my controller, I try this:
public function postActivityPerEmployee(Request $request)
{
$input = $request->all();
return $input['mydata'][0]['key'];
}
I ve tried various combinations but I always end up with a 500 page error or in the console, I only get [ and nothing else.
Don't stringify your info because you will send a string.
use this instead :
var info = [{'key':'val1'},{'key':'val2'},{'key':'val3'}];
which mean that you want to send an array of Objects

how to get the result from controller in ajax json

Isend the some aruguments to controller using ajax but it does not return the value.
My concept : selected #html.dropdownlist value i send to the controller , using this value thats perfrom the get the valus for bind the property to another dropdownlist using mvc3
IGot this answer : verfif given link
verfif given link
you are passing type option in ajax twice and the url is not formatted properly
function onChange(bookid) {
$.ajax({
type: "GET",
url: '#Url.Action("books","subject")',
data : { bookid: bookid},
dataType: "json",
success: function (result) {
alert('success');
//do whatever you want
},
error: function(result){
}
});
};
You are passing dataType as json. So, if you want to hit the success result for $.ajax, you need to return Json from your action result instead of returning as View.
When you return as View it gives error always.
public ActionResult books(string bookid)
{
var books= service.books(projectId);
// books are stored in list format
return Json(books);
}
Hope it helps you.

Resources