Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing JavaScript array from view to Laravel controller

I am trying to pass objs array to a function in Laravel controller using ajax. I am not recieving any data after the post.

<script>

        var itemCount = 0;
        var objs=[];
        $(document).ready(function(){


            var temp_objs=[];

            $( "#add_button" ).click(function() {

                var html = "";

                var obj = {
                    "ROW_ID": itemCount,
                    "STREET_ADDRESS": $("#street_address").val(),
                    "CITY": $("#city").val(),
                    "ZIP": $("#zip").val()
                }

                // add object
                objs.push(JSON.stringify(obj));

                itemCount++;
                // dynamically create rows in the table
                html = "<tr id='tr" + itemCount + "'><td>" + obj['STREET_ADDRESS'] + "</td> <td>" + obj['CITY'] + " </td> <td>" + obj['ZIP'] + " </td><td><input type='button'  id='" + itemCount + "' value='remove'></td> </tr>";

                //add to the table
                $("#multiple_table").append(html)

                // The remove button click
                $("#" + itemCount).click(function () {
                    var buttonId = $(this).attr("id");
                    //write the logic for removing from the array
                    $("#tr" + buttonId).remove();
                });

            });

            $("#submit").click(function() {
                $.ajax({
                    url:'/app/Http/Controllers/Search/search_address',
                    type: 'POST',
                    dataType:'json',
                    contentType: 'application/json',

                    data: objs
                });

            });

        });



    </script>

In my controller function is like this

public function search_address(){
    $data = json_decode($_POST['data'], true);
    print_r($data);
}

I guess that I am having a problem with the url in ajax and I am not sure how a controller's url is obtained.

Thank you

like image 737
Sajan Silwal Avatar asked Oct 22 '15 08:10

Sajan Silwal


1 Answers

Can you change:

$data = json_decode($_POST['data'], true);

to:

$data = json_decode(Input::get('data'));

and make sure you have: use Input; above your class extends Controller

See if that works.

Edit: Also make sure your routes (in the Controllers folder) are correct.

like image 171
Maarten Avatar answered Nov 03 '22 00:11

Maarten