Send POST Data with Ajax, withtout form, to a Symfony2 Controller, in JSON format - ajax

Good evening everybody!
I would like to send JSON Post Data to a Symfony Controller without form, but it doesn't work. I build a JSON data line and it is well built, it is NOT the problem. When I send my data with AJAX, the request is not filled.
Here is my Javascript code:
function validerSession()
{
//I don't describe the composition of the dataline.
var dataObject = JSON.stringify(obj); //My dataline JSONified
$.ajax({
type: "POST",
url: Routing.generate('cloud_money_drop_validerSession', { id: {{ partie.id }}, idSession: sessionId }),
data: dataObject,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (donnees) {
alert("Hello");
}
});
}
The AJAX call work.
Here is the PHP Symfony Controller method which received data:
public function validerSessionAction(Partie $partie, Session $session)
{
$request = $this->get('request');
$data = json_decode($request->getContent());
$serializer = $this->container->get('jms_serializer');
$response = $serializer->serialize($data, 'json');
return new Response($response);
}
But there is not any data in $data.
EDIT : An example of the dataline JSONified
{"trappes":{"1":{"id":"134","montant":"5000"},"2":{"id":"135","montant":"15000"},"3":{"id":"136","montant":"20000"},"4":{"id":"137","montant":"0"}}}
Do you have any idea ? I'm sure this is a common issue.
Thank you for your participation !
CloudCompany

I found the solution.
It's not really difficult.
It is not necessary to JSonify data. The controller has the capability to understand the original datatype.
So here is my simplified AJAX call:
function validerSession()
{
obj = new Object();
obj["title"] = "Title for example";
$.ajax({
type: "POST",
url: Routing.generate('cloud_money_drop_validerSession', { id: {{ partie.id }}, idSession: sessionId }),
data: obj,
success: function (donnees) {
data = Parse.JSON(donnees);
alert(data.title); //Show "Title for example"
}
});
}
And here is my Controller. It can recover data as an array of values.
public function validerSessionAction(Partie $partie, Session $session)
{
$request = $this->get('request');
$data = $request->request->all();
$serializer = $this->container->get('jms_serializer');
$response = $serializer->serialize($data["title"], 'json');
return new Response($response);
}
Thanks for the help!

Related

why is codeigniters raw_input_stream null?

I was wondering why is the raw_input_stream returning null. Here is my ajax call that I do from UI5.
$.ajax({
url: "/CI/controllername/functionname",
type: "POST",
data: JSON.stringify(oParameters),
contentType: "application/json",
success: function (data) {
MessageToast.show(data);
},
error: function (e) {
MessageToast.show(e.status);
}
});
Here is my controller
class controllername extends CI_Controller
{
public function functionname()
{
echo $this->input->raw_input_stream;
if ($this->input->raw_input_stream == null) echo "null";
}
}
When I run this code raw_input_stream is null. Not sure why. I check the request payload on chrome developer tools and the data is send. Here is request payload.
Try using Following:
parse_str(urldecode($this->input->raw_input_stream), $output);
$data = $output;
This may help.

Not getting post data in controller from ajax

I am posting my form data to A controller but when I post data I am not getting in the controller when I call print_r($_POST); its returning null array I don't know what I have missed
Please let me know what inputs you want from my side
var data2 = [];
data2['user_firstname'] = user_firstname;
data2['user_lastname'] = user_lastname;
data2['user_phone'] = user_phone;
data2['user_email'] = user_email;
data2['user_username'] = user_username;
data2['user_password'] = user_password;
console.log(data2);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "http://localhost/shago/register/submit",
data: { 'data2': data2 },
// dataType: "text",
success: function(resultData) { console.log(resultData); }
});
controller code
public function submit()
{
print_r($_POST);
}
You can use the following
public function submit(Request $request)
{
dump($request);
}
Try adding Request as parameter on your submit function
public function submit(Request $request)
{
print_r($request);
}
Also, do you really need to pass your information as an array?
You could just create a new object and pass that as well.
var data2={
'user_firstname': user_firstname,
'user_lastname': user_lastname,
'user_phone': user_phone,
'user_email': user_email,
'user_username': user_username,
'user_password': user_password
};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "http://localhost/shago/register/submit",
data: data2,
success: function(resultData) { console.log(resultData); }
});
You need to inject Request Class injection into submit method. This can help you:
public function submit(\Illuminate\Http\Request $request)
{
dd($request->all()); // will print all data
}
of if you don't want to inject Request then this code may helps you
public function submit()
{
dd(request()->all()); // will print all data
}
Good Luck !!!
Maybe the request was intercepted by Laravel CSRF Protection policy.In order to prove it, you should add request URL in VerifyCsrfToken middleware file, like following:
protected $except = [
'yoururl'
];
If you can get the data you expect in your controller, then I am right.
Thanks all i found error in when i am sending array data now i have modified code and its working fine
see code
$.ajax({
url: "register/submit",
type: "post",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {'user_firstname':user_firstname,'user_lastname':user_lastname,'user_phone':user_phone,'user_email':user_email,'user_username':user_username,'user_password':user_password},
success: function(result){
console.log(result);
}
});
}

Laravel - add to cart ajax issue

guys when I try to add item to EMPTY(empty session) cart asynchronously it doesn't work. But if I refresh the item appears in cart and from there I can add items asynchronously. What am I missing?
controller function:
public function addToBasket(Request $request, $id)
{
$newBasket = new Basket($previousBasket);
$newBasket->addProduct($product, $product->id);
Session::put('basket', $newBasket);
return response()->json(['added' => Session::get('basket')->quantity], 200);
}
ajax:
var id = $(this).data('id');
var url = "/product/add-to-basket/"
$.ajax({
type: "GET",
url: url+id,
dataType: "json",
data: { id: id },
success: function(data) {
if(data) {
$('#counter').html(data['added']);
console.log(data);
}
It's because the session[basket] variable isn't initialised for the first request. but how do I resolve it?

pass an array to action using ajax YII

Hi i'm really new with YII, please help me to solve a simple problem.
I'm trying to pass some values from js to action and then to put them into database.
Most of this code i got from tutorial
public function actionInsert(){
$post = file_get_contents("php://input");
$data = CJSON::decode($post, true);
$read = new Read();
$read->attributes = $data;
$response = array();
$read->save();
}
Then i send:
$.ajax({
type: "POST",
url: "/read/insert/",
data: "name=imja&short_desc=korotkoe&author=avtor&image=photo",
error: function (){
alert('Error');
},
success: function(data){
alert('success');
}
});
But i get an 'error' alert and nothing goes to DB.
The values from .ajax don't get submitted as a JSON array, the values should simply be in the $_POST array. Also I like to return something like 'complete'. Try changing your code to this:
public function actionInsert(){
$read = new Read();
$read->attributes = $_POST;
$response = array();
$read->save();
echo 'complete';
die();
}
Or you can send it as a JSON array from the javascript side:
var data = {
name: 'imja',
short_desc: 'korotkoe',
author: 'avtor',
image: 'photo'
};
$.ajax({
type: "POST",
url: "/read/insert/",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
error: function (){
alert('Error');
},
success: function(data){
alert('success');
}
});
However even if you do this apache will see the header type and still populate the $_POST array correctly. So it really isn't needed.
Also if you haven't already install Firebug onto Chrome or Firefox so you can see that actual ajax calls in the console. See what error you are getting from your action function in your controller.

Unable to receive json data in controller with knockout

I am new with knockout and mvc, so I need some help, my question is
my dropdown list is populating successfully from server, and on clicking save button calls Save method in controller. But problem is that in controller I am unable to receive json data i.e it is null. here is my code in view
var initialData = #Html.Raw( new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model));
var viewModel = function(){
var self = this;
self.HomeAgencies = ko.observableArray(initialData.HomeAgencies);
self.selectedOrgUnit = ko.observable();
self.Save = function () {
$.ajax({
url: "#Url.Action("Save")",
type: "POST",
data: ko.toJSON(this),
contentType: "application/json; charset=utf-8",
dataType:"json",
success: function(result) {alert(result.message)}
});
}
}
var vm = new viewModel();
ko.applyBindings(vm);
Where in controller i have following code
public JsonResult Save(string someData)
{
var message = string.Format("Saved {0} ", "successfully");
return Json(new { message });
}
string someData is always null, where I am expecting some json data.
Try to replace this to self in data and introduce field name and remove contentType.
$.ajax({
url: '#Url.Action("Save")',
type: 'POST',
data: { someData: ko.toJSON(self) },
dataType: 'json',
success: function (result) { alert(result.message); }
});
In your case context of the method can be changed from your object to html element that invoked them method or to window.
issue resolved. Problem was at controller side, in Action of controller pass the same model class instead parsing json manually.

Resources