Return a view via ajax in laravel

13,797

Solution 1

Well, for starters, you have an error in your view. The error you're getting is in reference to an array you're trying to access that doesn't actually have the key you're trying to use ($arr[0]).

Once you fix the errors with the view itself, it should work fine. The JavaScript will get the data as HTML, and you can just insert it into wherever you want it to show up.

Solution 2

Use string method before view file

return (String) view('Company.allUserAjax');
Share:
13,797

Related videos on Youtube

Pars
Author by

Pars

Web and Mobile Developer at Chista Group. Prior lead Web Developer and Mobile Developer at Fanavari Tandis. Prior Web Developer at Lifeweb co. Prior Web Developer at Caspian co. Prior lead Web Developer at Padafand IT.

Updated on June 04, 2022

Comments

  • Pars
    Pars almost 2 years

    I want to display a view to the user whenever user clicks on a button using ajax.
    This is my code.

    // BASE = localhost/project/public/
    
        $('#button').click(function() {
            $.ajax({
                url: BASE + "user/settings",
                type: 'GET'
            })
            .done(function( data ) {
                console.log( data );
            });
        });  
    

    And my routes.php

    Route::get('user/settings', 'UserController@getSettings');
    

    And UserController.php

    public function getSettings(){
        return View::make('user.settings');
    }
    

    But output is this error:

    {"error":{"type":"ErrorException","message":"Undefined offset: 0","file":"H:\\dev    \\xampp\\htdocs\\lchat\\vendor\\laravel\\framework\\src\\Illuminate\\Support    \\Collection.php","line":470}}
    

    EDIT: error was in view. I fixed it.

    Problem2: The page which is loading via ajax, itself contains another ajax post request. but it's not sending data via ajax anymore. refreshes the page to send data.

    The jquery code:

    $('#settings :submit').click(function(e){
        e.preventDefault();
        $.post(BASE +  'settings/save', {
            'userName' : $('#userName').val()
            }, function(data) {
                return 'OK';
        });
    });
    

    Problem solved: I used .on to bind event:

    $(document).on('click', '#settings :submit', function(e){ ... } );
    

    It's working... Thank everyone.

    • Antonio Carlos Ribeiro
      Antonio Carlos Ribeiro over 10 years
      Does your view works outside ajax (on our browser)? http://localhost/project/public/user/settings
    • Antonio Carlos Ribeiro
      Antonio Carlos Ribeiro
      That's how bugs works, you never remember to look where you need to. :) Nice it's working now. Enjoy Laravel!
  • Josh Forbes
    Josh Forbes about 9 years
    Thanks, this worked for me. I was trying to pass my view partial to Pusher and it was coming through as a javascript object. Using (String) fixed it.