7

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

4
  • Check the network tab in developer tools.. Commented Oct 22, 2015 at 8:29
  • did your ajax loading?Have you checked your browsers console to see if any errors are thrown? Commented Oct 22, 2015 at 8:29
  • Forget about JavaScript/AJAX for a second... Can you build a form in HTML/PHP/Laravel that does what you want it to do? I want to make sure that your controller and routing works first. Commented Oct 28, 2015 at 22:33
  • Hey Sajan. Any progress with this? Commented Nov 2, 2015 at 23:59

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

No, Input::get, I'm currently working on a project with Laravel, this is how we do it.
I wouldn't know why or if $_POST would not work since I never used that in a Laravel project, just gave an example of how I get my data from an ajax call.
0

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.

2 Comments

I tried your suggestion and it still doesnt work. Any other things I need to be aware of?
What result did you get in your browsers javascript console? Also, have you checked your logs to see if there were any errors thrown?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.