0

I have a javascript array which I want to send to a controller via an ajax get method.

My javascript looks like this:

    var requestData = JSON.stringify(commentsArray);

    console.log(requestData);
    //logs correct json object
    var request;

    request = $.ajax({
        url: "/api/comments",
        method: "GET",
        dataType: "json",
        data: requestData
    });

I can tell that my requestData is good because I am logging it and it looks right.

and the controller is being accessed correctly (i know this because I can log info there and I can return a response which I can log in my view after the response is returned).

when trying to access requestData I am getting an empty array.

My controller function that is called looks like:

public function index(Request $request)
    {

        Log::info($request);
        //returns array (
        //)
        //i.e. an empty array
        Log::info($request->input);
        //returns ""
        Log::info($_GET['data']);
        //returns error  with message 'Undefined index: data '
        Log::info(Input::all());
        //returns empty array

        return Response::json(\App\Comment::get());
    }

And I am getting back the response fine.

How can I access the requestData?

user3494047
  • 1,643
  • 4
  • 31
  • 61
  • 1
    Try this: `data: { data: requestData }` in your `$.ajax()` call – Dave Feb 16 '16 at 18:12
  • that did it. thanks! – user3494047 Feb 16 '16 at 18:14
  • 1
    Although if that's anything complicated, you're going to want to use POST, because otherwise you're going to run into various length limits for the URL. – Dave Feb 16 '16 at 18:14
  • Ah. thanks. what I'm doing is not complicated at all (just fetching something from database based on a string and an id), but I think I am sending a lot of unnecessary data, so that might be something to think about. – user3494047 Feb 16 '16 at 18:25
  • Also, @Dave , is this always the way to send data with ajax? if not, would you mind explaining why in this case it is? – user3494047 Feb 16 '16 at 18:29
  • You can structure your JSON data any way you want - the specific structure will depend on your needs and how your server-side code accesses passed JSON. I don't know PHP well and I don't know laravel at all so I can't really comment on your best options there. – Dave Feb 16 '16 at 18:35

2 Answers2

1

Dave's solution in the comments worked:

Changed ajax request to:

request = $.ajax({
    url: "/api/comments",
    method: "GET",
    dataType: "json",
    data: {data : requestData}
});
user3494047
  • 1,643
  • 4
  • 31
  • 61
  • how about send `commentsArray` into jQuery.ajax data option directly. – Francis.TM Feb 16 '16 at 18:43
  • This works also. was not sure how to do this/what best practices where and [this](http://stackoverflow.com/questions/5035547/pass-javascript-array-php) post suggested JSON. I am not sure why actually. The only reason I saw was that is a more 'universal solution`. I want to comment on that post and ask why he says that is a more universal solution, but I don't have 50 rep. – user3494047 Feb 16 '16 at 18:51
0

This is how push item in an array using jQuery:

function ApproveUnapproveVisitors(approveUnapprove){
    var arrUserIds = [];
    $(".visitors-table>tbody>tr").each(function(index, tr){
        arrUserIds.push($(this).find('a').attr('data-user-id'));
    });

    $.ajax({
        type:'POST',
        url:'/dashboard/whitelistedusers/' + approveUnapprove,
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        data: {data : arrUserIds}, 
        success:function(data){
            alert(data.success);
        },
        error: function(e){
            //alert(e.error);
        }
    });
}

And this is how I access them in my controller //Approve all visitors function ApproveAllWhitelistedUsers(Request $request){ $arrToSend = request('data');

    foreach ($arrToSend as $visitor) {
        $vsitor         =    User::findOrFail($visitor);
        $vsitor->update(['is_approved'=> '1']); 
    }
    return response()->json(['success'=>'Accounts approved successfully!']);
}
hackernewbie
  • 1,606
  • 20
  • 13