0

I am using Symfony 2.7 and I query the information from the database and show it on the page however i want to get the current values via api connection through Ajax call by clicking the button but I always get the null response from Ajax Controller.

<div>
    <p id="product">1K0615301M1</p>
    <p id="product">1K0615301M2</p>   
    <input type="button" id="submit" value="Check"/>
</div>

<script>
     $(document).ready(function(){
         $('#submit').click(function(event) {
             var productNr = [];
             $('#product').each(function() {
                 productNr.push($(this).html());
             });
             console.log(ProductNr); // value of ProductNr
             var ajaxRequest;
             event.preventDefault();

             ajaxRequest = $.ajax({
                 url: " {{ path('frontend_api_product') }}",
                 type: "post",
                 processData: false,
                 contentType: 'application/json; charset=UTF-8',
                 data: ProductNr,
                 success: function (data) {
                     console.log(data);
                 }
             });
         });
     });
 </script>

My Controller:

public function AjaxAction(Request $request)
{
    $sparepart = $request->request->get('data');

    if ($request->isXMLHttpRequest()) {
        return new JsonResponse(array(
            'sucess'=> true,
            'data' => $sparepart
        ));
    }
    return new Response('This is not ajax!', 400);
}

Console.log

 Object { sucess: true, data: null }
chalasr
  • 12,971
  • 4
  • 40
  • 82
gabf Hahn
  • 117
  • 1
  • 3
  • 13

2 Answers2

1

Because your data object has no data key, you cannot retrieve it by doing $request->request->get('data');

To get the whole object, use $data = $request->request->all();

There is many errors in your code.
You are pushing values in productNr instead of ProductNr.
You have many elements with the same id (An id is uniq, you have to use classes).

EDIT

The problem is coming the format of the data your are sending. To send an object like {"data":["1K0615301M1","1K0615301M2"]} , use:

var ProductNr = { data: [] };
var ajaxRequest;

$('.product').each(function() {
    var product = $(this).text();
    ProductNr.data.push(product);
});
ajaxRequest = $.ajax({
    url: "/ajax",
    type: "POST",
    data: JSON.stringify(ProductNr),
    processData: false,
    success: function (data) {
        console.log(data);
    }
});

Use JSON.stringify to serialise data before send it.
See How do I POST an array of objects with $.ajax (jQuery or Zepto)

Community
  • 1
  • 1
chalasr
  • 12,971
  • 4
  • 40
  • 82
  • I do have Request Param in the code... But I still get **null** response from the controller for both `$data = $request->request->all()` and `json_decode($request->getContent(),true` – gabf Hahn Feb 08 '16 at 17:11
  • Try to remove the contentType – chalasr Feb 08 '16 at 17:12
  • also how can i add 'data' key so that its easier to get the value in the Controller – gabf Hahn Feb 08 '16 at 17:18
  • I have also tried with `ajaxRequest = $.ajax({ url: " {{ path('frontend_api_product') }}", type: "post", processData: false, data:'asdf', success: function (data) { console.log(data); } });` and I still get **Null** response – gabf Hahn Feb 08 '16 at 17:25
  • See changes in my answer, the code is working well now. – chalasr Feb 08 '16 at 20:04
  • I have copied the exact same thing as above([code](https://gist.github.com/gghhh456/a9ca07b7fe5ca3af54f7)) and i still have "null" data. [image](http://tinypic.com/r/29vltw/9) – gabf Hahn Feb 09 '16 at 09:03
  • I just copy/paste the code of your gist and it works well. See [screenshot](http://prntscr.com/a0wust) . Try to clean your cache by doing `rm -rf app/cache/*` . If it doesn't work, say me your symfony version – chalasr Feb 09 '16 at 09:15
  • I have cleared cache many times that was the first thing i did. It is still null [ScreenShot](http://tinypic.com/r/9swhhx/9) I am using Symfony version 2.7.8 – gabf Hahn Feb 09 '16 at 09:29
  • The problem is surely coming from you (jQuery version, server configuration, or just mistakes). It can come from a lot of reasons and I cannot help you beyond making the code functional (for me). – chalasr Feb 09 '16 at 09:34
  • Thanks for the effort, Just one last question how can set the data object to `data`? Simply `ajaxRequest = $.ajax({ url: "{{ path('frontend_api_product') }}", type: "POST", data: {'data' : ProductNr, processData: false, success: function (data) { console.log(data); } ` then simply in controller do `$data = $request->request->get('data');` right? – gabf Hahn Feb 09 '16 at 09:41
  • I've created a repository that you can test and use to debug and find where is the problem in your code. https://github.com/chalasr/stackoverflow-trying – chalasr Feb 09 '16 at 10:05
  • I've updated my answer for you have a `data` object. I've also push the changes to the repository, you can use it and try. – chalasr Feb 09 '16 at 10:17
  • Thank you so much.. I will accept it as the answer. – gabf Hahn Feb 09 '16 at 10:19
  • You're welcome, if you find what was causing the problem in your project, please keep me informed here – chalasr Feb 09 '16 at 10:20
0

Change
data: ProductNr,
to

data:{data:ProductNr}
paranoid
  • 6,799
  • 19
  • 49
  • 86