简体   繁体   中英

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

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.

You should console.log() your javascript by placing the following in you ajax post:

error : function(e){
   console.log(e);
}

You can then see what errors you are getting in your browsers' developers tools panel.

You should also be aware that that Laravel posts require a csrf token unless you have explicitly turned them off, which means you will need to add this token in to your post as well. So you should end up with:

$("#submit").on('click', function() {
    $.ajax({
        url:'/app/Http/Controllers/Search/search_address', // Is this what you meant, is this the route you set up?
        type: 'POST',
        data: {'data': objs, '_token' : '<?=csrf_token()?>'},
        success : function(data){
          // Do what you want with your data on success
        },
        error : function(e){
           console.log(e);
        }
    });
});

Notice that I've embedded php inside the javascript, which is just to illustrate the point. Ideally javascript is kept in it's own files, so you would then need to find a way to pass this token through. I personally use knockoutjs for this type of thing ( AngularJS is also popular), but you can easily do something like:

<input type="hidden" id="_token" value="{{ csrf_token() }}" />

in your HTML, then pull this value from inside your ajax request:

data: {'data': objs, '_token' : $('#_token').val()}

EDIT

I've just noticed your url, it looks like you are trying to access the controller directly. You need to set up a route in your routes.php file, such as:

Route::post('/searchAddress', 'YourController@search_address');

Then use:

url: /searchAddress

in your ajax request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM