1

I can't find a working solution for this problem: I want to update a part of my view without reloading it, I have a form that collects the data to be passed to the controller, the controller needs to get the data from the DB and spit out a JSON to the view so that it can be filled with such data.

I tried to adapt this http://tutsnare.com/post-data-using-ajax-in-laravel-5/ but it's not working at all. The data collected is not reaching the controller.

My uderstanding is the javascript part in the view should listen to the click event and send a GET request to the controller, the controller checks if the data is sent through AJAX, gets the data from DB then returns the response in JSON form, the view is then updated. Please, does anyone have a working example or can explain?

5
  • Posting form to controller with regular POST request or via AJAX is same for controller. If your controller and form is working without AJAX then the problem is in JavaScript and it has nothing to do with Laravel controller. Commented Jul 20, 2015 at 15:53
  • ok, but then let's say you post to controller the regular way, how do you spit out a JSON response to the view instead of reloading the page? Isn't the whole AJAX posting aim to prevent reloading? Commented Jul 20, 2015 at 15:55
  • 1
    you spit out json easily return response()->json(['key'=>'value']);. This will return correct response with correct headers for JSON. Reloading or no reloading the page is all done in JavaScript. You send AJAX request to controller and get JSON response, then you have to populate the view with data your self, using whatever JS code you need. Commented Jul 20, 2015 at 16:02
  • to clarify, Laravel itself will not update your view or populate your form via ajax. You have to do it yourself. This is done with JavaScript not PHP. Laravel is PHP framework and does not include any JavaScript logic. Commented Jul 20, 2015 at 16:08
  • yes, I understand that laravel needs ajax to populate, the point is I don't find a working example hence the difficulties Commented Jul 20, 2015 at 16:10

2 Answers 2

1

Simple working example using JQuery:

In you routes.php file:

Route::post('/postform', function () {
    // here you should do whatever you need to do with posted data
    return response()->json(['msg' => 'Success!','test' => Input::get('test')]);
});

and in your blade view file:

<form method="POST" action="{{ url('postform') }}">
    <input type="hidden" name="_token" value="{{ csrf_token() }}" />
    <input type="text" name="test" value="" />
    <input type="submit" value="Send" />
</form>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
    jQuery(function ($) {
        $(document).ready(function()
        {
            var form = $('form');
            form.submit(function(e){
                e.preventDefault();
                $.ajax({
                    url: form.prop('action'),
                    type: 'post',
                    dataType: 'json',
                    data: form.serialize(),
                    success: function(data)
                    {
                        console.log(data);
                        if(data.msg){
                            alert( data.msg + ' You said: ' + data.test);
                        }
                    }
                })
            });

        });
    });
</script>

As you can see, most of the logic is done in JavaScript which has nothing to do with Laravel. So if that is not understandable for you, I'd recommend to look for jQuery ajax tutorials or rtfm :)

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

7 Comments

I am trying this code, i modified to send my data instead of test and I get a 500 internal server error
..wait, I was finally able to return response with the data I need in form of json, now how do I modify the callback function to populate a div?
however it seems to be that the data resulting is in form of array and not json
You modify the callback function as you want. If you don't know how, you should learn Javascript or post another question about that. It has nothing to do with Laravel. It is pure HTMl manipulation with JS or jQuery if you want.
data object passed to ajax success callback will contain exactly what will be returned by the URL. If you pass string, you will get string. If you pass json, you will get json (which is also string, but will be automatically converted to object/array if you set content-type to json in http headers ) . If you convert numeric array into json, it will be array in JS, while passing assoc array, you will get object. So you should really learn some JS first. Thing you want to do is very specific and you do not provide any examples, so it is impossible to help you any further at this point.
|
0

I have experienced submitting a modal form without reloading the entire page. I let the user add option to the dropdown and then repopulate the items on that dropdown without reloading the entire page after and item is added.

you can have custom route to your controller that handles the process and can be called by javascript and will return json

Route::get('/profiles/create/waterSource',function(){

    $data = WaterSource::orderBy('description')->get();

    return Response::json($data);

});

then the javascript

<script>
    $(document).on('submit', '.myForm-waterSource', function(e) {

        $.ajax({

            url: $(this).attr('action'),

            type: $(this).attr('method'),

            data: $(this).serialize(),

            success: function(html) {

                $.get('{{ url('profiles') }}/create/waterSource', function(data) {

                    console.log(data);

                    $.each(data, function(index,subCatObj){

                        if (!$('#waterSource option[value="'+subCatObj.id+'"]').length) {

                            $('#waterSource').append('<option value="'+subCatObj.id+'">'+subCatObj.description+'</option>');

                        }

                    });

                    $('#myModal-waterSource').modal('hide');

                    $('#modal-waterSource').val('');

                });

            }

        });

        e.preventDefault();

    });

</script>

You can view the full tutorial at Creating new Dropdown Option Without Reloading the Page in Laravel 5

Comments

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.