Pars
Pars

Reputation: 5262

Return a view via ajax in laravel

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.

Upvotes: 6

Views: 13943

Answers (2)

Imtiaz Pabel
Imtiaz Pabel

Reputation: 5443

Use string method before view file

return (String) view('Company.allUserAjax');

Upvotes: 3

Shauna
Shauna

Reputation: 9596

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.

Upvotes: 3

Related Questions