Controller must return a response in Symfony2 - ajax

I have an ajax call in my code. What I want to achieve with the call works fine. I want to delete some records from the database which is actually deleted when the method is called via ajax but as in symfony method it must return a response and thats why when the method is executed its gives me the error
My Ajax call is
$.ajax({
type: "POST",
data: data,
url:"{{ path('v2_pm_patents_trashpatents') }}",
cache: false,
success: function(){
document.location.reload(true);
}
});
And the method that is executed is
public function trashpatentAction(Request $request){
if ($request->isXmlHttpRequest()) {
$id = $request->get("pid");
$em = $this->getDoctrine()->getEntityManager();
$patent_group = $em->getRepository('MunichInnovationGroupPatentBundle:PmPatentgroups')->find($id);
if($patent_group){
$patentgroup_id = $patent_group->getId();
$em = $this->getDoctrine()->getEntityManager();
$patents = $em->getRepository('MunichInnovationGroupPatentBundle:SvPatents')
->findBy(array('patentgroup' => $patentgroup_id));
if($patents){
foreach($patents as $patent){
if($patent->getIs_deleted()==false){
$patent->setIs_deleted(true);
$em->flush();
}
}
}
$patent_group->setIs_deleted(true);
$em->flush();
}
else{
$em = $this->getDoctrine()->getEntityManager();
$patent = $em->getRepository('MunichInnovationGroupPatentBundle:SvPatents')->find($id);
if ($patent) {
$patent->setIs_deleted(1);
$em->flush();
}
}
return true;
}
}
How can I successfully return from this method ?
Any ideas? Thanks

Replace return true; with return new Response();. Also don't forget to write use Symfony\Component\HttpFoundation\Response; at the top.

You can also pass error code 200 and the content type like below.
return new Response('Its coming from here .', 200, array('Content-Type' => 'text/html'));
Here is the full example of the controller
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class WelcomeController extends Controller
{
public function indexAction()
{
return new Response('Its coming from here .', 200, array('Content-Type' => 'text/html'));
}
}

Related

laravel using jQuery Ajax | Ajax Cart

I'm Trying to Save The Product into The Database By Clicking On Add To Cart
But It's Not Adding I Also Use Ajax `
I Want To Add The Cart To DataBase And It's Not Adding.
This is The Error That I cant Add Any Product To The Cart Because Of It
message: "Call to undefined method App\User\Cart::where()", exception: "Error",…
enter image description here
Model Page.
class Cart extends Model
{
use HasFactory; I
protected $table = 'carts';
protected $fillable = [
'user_id',
'prod_id',
'prod_qty',
];
}
Controller page.
public function addToCart(Request $request)
{
$product_qty = $request->input('product_qty');
$product_id = $request->input ('product_id');
if(Auth::check())
{
$prod_check = Product::where('id',$product_id)->first();
if($prod_check)
{
if(Cart::where('prod_id',$product_id)->where('user_id',Auth::id())->exists())
{
return response()->json(['status' => $prod_check->pname." Already Added to cart"]);
}
else
{
$cartItem - new Cart();
$cartItem->user_id = Auth::id();
$cartItem->prod_qty = $product_qty;
$cartItem->save();
return response()->json(['status' => $prod_check->pname." Added to cart"]);
}
}
}
else{
return response()->json(['status' => "Login to Continue"]);
}
}
javascript page.
This Is MY First Time To Use Ajax And Sure That Every Thing Is Correct I Want Know Why Its Not Add
$('.addToCartBtn').click(function (e) {
e.preventDefault();
var product_id = $(this).closest('.product_data').find('.prod_id').val();
var product_qty = $(this).closest('.product_data').find('.qty-input').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: "POST",
url: "/add-to-cart",
data: {
'product_id': product_id,
'product_qty': product_qty,
},
success: function (response) {
alert(response.status);
}
});
// alert(product_id);
// alert(product_qty);
// // alert ("test ") ;
});
Route:
Route::middleware(['auth'])->group(function () {
Route::post('/add-to-cart', [App\Http\Controllers\User\indexController::class, 'addToCart' ]);});
So why this error occurs, how can I fix it?`
This look like an error in importation like App\Models\Cart not like this?
verify if you had added use App\Models\Cart;

AJAX POST to laravel returning 404 not found

I am trying to process POST data from ajax to laravel controllers but I can't access it. Here is what I am doing in AJAX.
$.ajax({
type:'POST',
url:'/complete_ca_fin',
data: {fin_id: id},
success:function(data){
console.log(data);
$('#modal_complete').modal('hide');
$('html, body').animate({
scrollTop: 0 }, "slow");
$('#message_form').empty().css('display','block').removeClass('alert-danger').addClass('alert-success').text('Finished Good CA has been successfully completed.');
$('#message_form').fadeOut(4000);
setTimeout(function(){
window.location = '/quality_control';
}, 3000);
refresh_check = true;
window.onbeforeunload = null;
},
error: function (data) {
console.log('Error: ' + data);
} // end of error
}); // ajax
id should be accessed in the controller. Here is my route
Route::post('/complete_ca_fin', 'DatasheetController#complete_ca_fin');
And here is my controller
public function complete_ca_fin(Request $request) {
$id = $request->id;
$complete_ca = FinishedCA::findOrFail($id);
if ($complete_ca){
$complete_ca->status = '5';
$complete_ca->save();
return 'success';
}
//return 'success';
}
When I try to return $id just to test I noticed that it is empty ( I don't if it has anything to do with it ) but I know that var id in the ajax has a value because I tested it in the console.
Here is a sample of the console log. 37 is the value of the id so there should be a value in the controller
You are using findOrfail which means it will throw a 404 if there is no email, you want to be validating if it exists, not 404'ing of not
public function complete_ca_fin(Request $request) {
$id = $request->id;
$complete_ca = FinishedCA::find($id);
if ($complete_ca->exists()){
$complete_ca->status = '5';
$complete_ca->save();
return 'success';
}
//return 'success';
}
Use Input::get('id'); instead of request , So your method will like this
public function complete_ca_fin(Request $request) {
$id = Input::get('id');
$complete_ca = FinishedCA::findOrFail($id);
if ($complete_ca){
$complete_ca->status = '5';
$complete_ca->save();
return 'success';
}
//return 'success';
}

Make an Ajax request in Symfony2

My problem is that the method doesn't return a true result.
I want to test if the email of input exists in my entity or not.
Here is the controller:
public function verificationAction(Request $request)
{
if ($this->container->get('request')->isXmlHttpRequest()) {
$email=$request->request->get('email');
$em=$this->getDoctrine()->getEntityManager();
$resp= $em->getRepository("CMSiteBundle:Prospect")->findBy(array('email'=>$email));
$response =new Response(json_encode($resp));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
You could try an old-trick. Since in Symfony Controller Actions, You must return a Response why not fake a DEAD RESPONSE like so:
<?php
class ABCController {
public function verificationAction(Request $request) {
if ($this->container->get('request')->isXmlHttpRequest()) {
$email = $request->request->get('email');
$em = $this->getDoctrine()->getEntityManager();
$resp = $em->getRepository("CMSiteBundle:Prospect")
->findBy(array('email' => $email));
//$response = new Response(json_encode($resp));
//$response->headers->set('Content-Type', 'application/json');
// THE TRICK IS THAT DIE RUNS FIRST
// THUS SENDS YOUR RESPONSE YOU THEREBY
// STOPPING THE RETURN FROM FIRING... ;-)
return die(json_encode($resp));
}
}
}
Perhaps this very Old Trick still works for you... ;-)

Symfony2: Save Record From Ajax Form Submission

I am totally lost. There's only so much documentation one can read before it all starts making zero sense.
I want to be able to save form data passed from outside of my Symfony application. I have already installed FOSRestBundle, JMSSerializerBundle, NelmioCorsBundle, etc.
First off, I have a FormType that looks like this:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('requestDate')
->add('deliverDate')
->add('returnDate')
->add('created')
->add('updated')
->add('contentChangedBy')
;
}
Then I have a REST controller containing the POST method which is supposed to store the new record:
class AvRequestController extends Controller
{
...
public function postAvrequestAction(Request $request){
$entity = new AvRequest();
$form = $this->createForm(new AvRequestType(), $entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return new \Symfony\Component\HttpFoundation\JsonResponse($entity, Codes::HTTP_CREATED);
}
return new \Symfony\Component\HttpFoundation\JsonResponse($request, 400);
}
}
Here is the test with the mock ajax form data:
$('#postform').submit(function(event){
event.preventDefault();
console.log("submitted");
ajaxObject = {
url: $("#postform").attr("action"),
type: 'POST', // Can be GET, PUT, POST or DELETE only
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true,
contentType: "application/json; charset=UTF-8",
data: JSON.stringify({"id":2, "title":"billabong", "requestDate":"2000-01-01 11:11:11", "deliverDate": "2000-01-01 11:11:11", "returnDate": "2000-01-01 11:11:11", "created": "2000-01-01 11:11:11", "updated": "2000-01-01 11:11:11", "content_changed_by":"cpuzzuol"})
};
// ... Add callbacks depending on requests
$.ajax(ajaxObject)
.done(function(data,status,xhr) {
console.log( two );
})
.fail(function(data,status,xhr) {
console.log( status );
})
.always(function(data,status,xhr) {
console.log( data );
});
console.log("END");
});
When I submit the form, the 400 Bad Request is tripped in my POST method. Worse, my $request bag is always empty:
{"attributes":{},"request":{},"query":{},"server":{},"files":{},"cookies":{},"headers":{}}
If I do
$request->getContent()
I get my stringified data:
"{\u0022id\u0022:2,\u0022title\u0022:\u0022billabong\u0022,\u0022requestDate\u0022:\u00222000-01-01 11:11:11\u0022,\u0022deliverDate\u0022:\u00222000-01-01 11:11:11\u0022,\u0022returnDate\u0022:\u00222000-01-01 11:11:11\u0022,\u0022created\u0022:\u00222000-01-01 11:11:11\u0022,\u0022updated\u0022:\u00222000-01-01 11:11:11\u0022,\u0022content_changed_by\u0022:\u0022cpuzzuol\u0022}"
I've read that this might have something to do with FOSRestBundle's "body listener" but I've already enabled that:
body_listener: true
UPDATE
body_listener doesn't seem to play a role at all. As the answer below states, you have to create a form with a blank name since the form you are submitting from outside of the system isn't going to have the name it would normally have if it were made inside of Symfony. Also, make sure to turn off CSRF if you don't have that set up at first.
Form isValid checks also for CSRF token validation. You can turn off csrf token validation in AvRequestType.
//...
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\AvRequest',
'csrf_protection' => false
));
}
//...
Also, I suggest your form has name. isValid also checks for your form name.
// form without name
public function getName()
{
return '';
}
Or
$form = $this->get('form.factory')->createNamed('', new AvRequestType(), $avRequest);
If you want to create entity, you should send data without id(from JS).
I have used "JMS serializer" to serialize my entity to json.
//Controller
public function postAvRequestAction(Request $request)
{
$avRequest = new AvRequest();
$form = $this->createForm(new AvRequestType(), $avRequest);
$form->handleRequest($request);
$form = $this->get('form.factory')->createNamed('', new AvRequestType(), $avRequest);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($avRequest);
$em->flush();
$serializer = $this->get('serializer');
$serialized = $serializer->serialize($avRequest, 'json');
return new Response($serialized);
}
return new JsonResponse(array(
'errors' => $this->getFormErrors($form)
));
}
protected function getFormErrors(Form $form)
{
$errors = array();
foreach ($form->getErrors() as $error) {
$errors['global'][] = $error->getMessage();
}
foreach ($form as $field) {
if (!$field->isValid()) {
foreach ($field->getErrors() as $error) {
$errors['fields'][$field->getName()] = $error->getMessage();
}
}
}
return $errors;
}

retriev data from controller using ajax

below code returns me blank in ajax response please help me
when i check my controller it also gives me blank.
Can you please check the code below to find out the reason of problem
here is my ajax code:
window.onload = function() {
$.ajax({
type:'json',
url:"http://localhost/myapne/admin/adminMenu/getMsg",
success:function(data){
alert(data);
// PrintSms(data);
},
error: function(error){
console.log(error);
}
});
}
here is my controller:
class AdminMenu extends CI_Controller{
function getMsg(){
$this->load->model('adminGetModel');
$data = $this->adminGetModel->getSms();
return array("status"=>"success","rows"=>$data);
}
}
here is my model:
class AdminGetModel extends CI_Model{
function getSms(){
// $a = $count*10;
// $b = $a + 10;
$this->load->database();
$query = $this->db->get('tblsms');
$rows = array(); //will hold all results
foreach($query->result_array() as $row)
{
$rows[] = $row; //add the fetched result to the result array;
}
return $rows;
}
}
Json_encode the data and use echo instead of return:
echo json_encode(array("status"=>"success","rows"=>$data));
This will return a string. If you want to turn it back into an object, you will then have to use JSON.parse() (or $.parseJSON if you're using jquery) in your ajax success handler.

Resources