Request conflict symfony action - php

I have an Ajax call that calls an action in the controller.
The Ajax call looks like this
$(document).on('click', '.editQuestionButton', function() {
var question_id = $(this).data('question');
console.log(question_id);
$.ajax({
type: "POST",
url: "/dashboard/form/AjaxEditQuestionForm/" + question_id + "",
success: function(data) {
$('#form-modal').html(data);
}
});
});
$(document).on('click', '.modal .fn-submit', function() {
$(this).closest('.modal').find('form').submit();
});
And this is the action.
/**
* #Route("/AjaxEditQuestionForm/{question}")
* #Template
* #ParamConverter("question", class="AppBundle:Question")
*/
public function ajaxEditQuestionFormAction(Request $request, $question)
{
$edit_question_form = $this->createForm(new AddQuestionType(), $question);
$edit_question_form->handleRequest($request);
if ($edit_question_form->isValid()) {
$em->flush();
return $this->redirectToRoute('app_form_create');
}
else{
die();
}
return array(
'question' => $question,
'editAjaxQuestionForm' => $edit_question_form->createView(),
);
}
The problem is that the action never returns the form but goes straight into checking if the form is valid.
I figure this has something to do with the $request but I'm not sure how to change this.
The action should first get the data from the Ajax call, return the form and if the form is submitted, check if the form is valid and flush the Question entity.
Any idea on how I should do this?

Related

Pass a Symfony form from one view to another in ajax

I'm trying to make a tabs nav with a central block that contains a Symfony form.
When I click into a link in a tab navs, I reload the block with form and data.
But the issue is how to pass formView object from the first twig to the AJAX twig response view?
My controller
/**
* #Route("/change-tab/{tabId}", name="change_tab")
* #param Request $request
* #return Response
*/
public function changeTab(Request $request, $tabId): Response
{
$firstElement = $this->getDoctrine()->getRepository(Element::class)->findOneBy([
'cart'=>$tabId,
]);
return $this->render('partials/_bloc-cart.html.twig',[
'firstElement '=> $firstElement ,
//'form' => $request->getContent()
]);
}
My twig view
<div class="row p-2">
<div class="col-md-12 px-0" id="bloc-form">
{{ include('partials/_form.html.twig') }}
</div>
</div>
And the ajax JS :
$(document).on('click', '.linkToChange', function () {
$('.linkToChange.active').removeClass('active');
$(this).addClass('active');
let formPlan = $('#bloc-form').data('form');
$.ajax({
type: "POST",
data : formPlan,
url: "/ajax/change-tab/" + $(this).data('cart'),
success : function (datas) {
$('#bloc-form').html(datas);
}
});
});
You have different ways to do it, if you use the Form Component, you can do something like this:
public function changeTab(Request $request, $tabId): Response
{
$firstElement = $this->getDoctrine()->getRepository(Element::class)->findOneBy([
'cart'=>$tabId,
]);
$form = $this->createForm(ElementType::class, $firstElement);
$form->handleRequest($request);
// Save if form is submitted and valid
return $this->render('partials/_bloc-cart.html.twig',[
'firstElement '=> $firstElement ,
'form' => $form->createView()
]);
}
You can try:
/**
* #Route("/change-tab", name="change_tab", method="{POST}")
* #param Request $request
* #return Response
*/
public function changeTab(Request $request)
{
$tabId = $request->get('tab_id');
$firstElement = $this->getDoctrine()->getRepository(Element::class)->findOneBy([
'cart'=>$tabId,
]);
$html = $this->render('partials/_bloc-cart.html.twig',[
'firstElement '=> $firstElement ,
//'form' => $request->getContent()
]);
return $this->json(['html' => $html]);
}
Jquery:
$.ajax({
type: "POST",
data : formPlan,
url: "{{ url('change-tab') }}",
dataType: 'json',
data: {
'tab_id' : $(this).data('cart'),
}
success : function (data) {
$('#bloc-form').remove();
$('#bloc-form').html(data.html);
}
});

Laravel 5.5 send data to view without reloading page

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>

How to get data attribute to controller from ajax?

I’m having trouble passing my $_POST variable to my controller from an jQuery/ajax request.
Ultimately I want to be able to use that to update a field in my database.
My problem is that in trying to access $_POST[‘quantity’] in my controller. I keep getting the notice quantity is undefined and I’m var_dumping it and it’s null.
I’m new to jQuery/ajax and I’m not really sure how to go about fixing this issue. I could really use help in getting the data attribute, quantity, in my ajax request to my controller and understanding why $_POST[‘quantity’] is null.
I hope I am clear in my questioning and thanks for your help!
Controller function:
/**
* Updates quantity using ajax/jQuery request from showCart twig file
*
* #Route("/{id}/quantityUpdate", name="product_quantityUpdate")
* #Method("POST")
* #Template()
*/
public function quantityUpdateAction(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$productId = $em->getRepository('ShopBundle:Product')->find($id);
$cart = $em->getRepository('ShopBundle:UserCart')->findOneBy(['user' => $this->getUser(), 'submitted' => false]);
$quantity = $em->getRepository(ShopBundle:Quantity')->findOneBy(['quantity' => $productId->getId()]);
var_dump($this->get('request')->request->get('quantity'));
$quantity = isset($_POST['quantity']) ? var_dump($_POST['quantity']) : false;
// $quantity->setQuantity(/* Code for finding correct product to update quantity */);
// $em->persist($quantity);
// $em->flush();
return new Response ("This has been successful!");
}
twig / ajax & jQuery:
<script type="text/javascript">
$(".spinner").spinner();
$('input.spinner').on('spinstop', function(){
min: 0
console.log('spinner changed');
var $this = $(this);
var value = $('spinner').val();
var request = $.ajax({
url: "{{ path('product_quantityUpdate', {'id': prodId }) }}",
method: "POST",
data : {
quantity: value
}
}).done(function(result){
console.log('success', result);
}).error(function(err){
console.log('error');
});
});
</script>
Change
var value = $('spinner').val();
to
var value = $('.spinner').val();
Your selector is having problem as I see that is missing.
If you have multiple elements with same class then better use this.value;

Can we process a form with Symfony2 without redirect to another url at the end?

I have problem with processing the data on a form in two tables with Ajax for not updating screen. Sumfony2 redirects to process the data to a url in the end, as you can see in the following code:
public function createAction(Request $request)
{
$entity = new Users();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('users_new'));
}
return $this->render('BackendBundle:Userss:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
ajax call:
$('.form_student').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: Routing.generate('student_create'),
data: $(this).serialize(),
success: function(response) {
alert(response.result);
},
error: function (xhr, desc, err){
alert("error");
}
})
return false;
});
Is there any way that does not forward it to any URL and can use Ajax to load anything in that window?
You can check on the $request if is an ajax call with the isXmlHttpRequest method.
So you can do something like:
use Symfony\Component\HttpFoundation\JsonResponse;
....
if ($form->isValid()) {
// do something
if ($request->isXmlHttpRequest()) {
// generate a response for tour client, as example:
return new JsonResponse(array("result" => 1);
}
return $this->redirect($this->generateUrl('users_new'));
}
Hope this help
replace
return $this->redirect($this->generateUrl('users_new'));
by
return new JsonResponse($this->generateUrl('users_new'));
this will return the url instead of redirecting to it, you can then use javascript to load it.

Action is not returning a single value

It seems to be an easy one but I am not able to manage an ajax post vor validation.
Via Ajax post I am sending data to an validation-action. so far so far so good.
the next step is returning a single value. Here is the problem. My action doesn't return the value.
Here is the action
public function solveEquationAction(){
$riddle = new Question();
$request = $this->getRequest()->getPost()->get('equation');
return $riddle->solveEquation($request);
}
Here is my ajax post
function validateAnswer(answer){
var equation = jQuery('#riddleAnswer').text();
$.ajax({
url : '/riddle/solveequation',
type: 'POST',
data: {'equation': equation},
success:function(data, textStatus, jqXHR)
{
console.log(data);
},
//...
});
}
I need the action to return only the solved equation so I can check it in the succes-part in my ajax post
Thanks in advance
You'd better use ViewJsonStrategy here.
public function indexAction()
{
$riddle = new Question();
$request = $this->getRequest()->getPost()->get('equation');
return new \Zend\View\Model\JsonModel(array(
'result' => $riddle->solveEquation($request),
'success' => true
));
}
Read more.

Categories