Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 950
Pars Avatar asked Oct 30 '13 19:10

Pars


2 Answers

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.

like image 139
Shauna Avatar answered Oct 01 '22 01:10

Shauna


Use string method before view file

return (String) view('Company.allUserAjax');
like image 21
Imtiaz Pabel Avatar answered Oct 01 '22 00:10

Imtiaz Pabel