i really don't understand how to handle with post data from ajax request. This is my javascript:
$.ajax({
type: "POST",
url: Routing.generate('save'),
contentType: 'application/json; charset=UTF-8',
data: {
title: title,
description: description,
questions: questions,
}
});
The only way to get the data inside my controller action is this:
$content = $request->getContent()
$content is a url parameter string. Why don't i get the data normally with:
$request->get('title')
What is the correct way to handle the post data with jquery ajax methd?
Thank you very much.
EDIT
So, i found out the following issue:
In my current project the request looks like this:
$.ajax({
type: "POST",
url: Routing.generate('poll_save'),
data: {
title: title
}
})
The data is requested via Request Payload but i don't know why.
In a clean project the request looks like this:
$.ajax({
type: "POST",
url: '{{path('_demo')}}',
data: {
title: 'title',
description: 'description',
questions: 'questions',
pollid: 1
}
})
Anything in my project is going wrong. Do you have an idea why the data is requested via Request Payload?
quiz - form name serialize -populate the variables
$.ajax({
url: $("#quiz").attr("action"),
data: $("#quiz").serialize(),
type: 'POST'
});
or
$.ajax({
url: $("#commentForm").attr("action"),
data: {
comment: commentFormID.val()
},
type: 'POST'
});
Controller - More like what previous comments suggested.
$request = $this->get('request');
$usercomment=$request->request->get('parameterName');
Do you use the request object in your controller?
<?php
namespace Acme\DemoBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
//...other things to use
class MyController extends Controller
{
public function handleRequestAction() {
$request = $this->get('request');
//request your data
$title = $request->get('title');
//or in one line
$title = $this->get('request')->request->get('title');
}
}
?>
This is my normal way when I want to get data from an ajax call. Could you post what $content contains?
I see no problem with posting the data like you did. Constructing a json object might be helpful but the way you're doing it seems fine to me. I did this too.
EDIT
Normally you could also access all data in the request by doing this:
$all = $request->request->all();
Maybe you could then var_dump()
the variables to see if something is in them.
You can construct your json object and pass the JSON object to your controller using JSON.stringify.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify
var obj = {
title: title,
description: description,
questions: questions
};
$.ajax({
type: "POST",
url: Routing.generate('save'),
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify(obj)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With