简体   繁体   中英

passing two JSON model objects from PHP to JS via AJAX

im using Laravel for a fairly simple app.

i have this in a controller function working great:

    if(Request::ajax())
    {
        $joke = Joke::where('type', '=', 'kid')->get()->random(1);

        if (Session::has('joke'))
        {
            Session::forget('joke');
        }

        Session::put('joke', $joke);
        return Response::json($joke);
    }

however, if I change the last lines to:

Session::put('joke', $joke);
$user = $joke->user;
return Response::json([ 'joke' => $joke, 'user' => $user);

the ajax call succeeds but i cant use $joke or $user in my JS anymore.

here is the ajax call:

$.ajax({
        type: "POST",
        url: url,
        data: { rating: userRating },
        success: function(data){
            var textString = 'Thanks for rating! This little gems score is a sweet ' + data.joke.rating + '!';
            $('.jokeRating').html(textString);

        },
        error: function(){
            // load a message indicating it didnt work
            $('.jokeRating').html('It didnt work, sorry!');
        },
    });

what i would like to add is something like

var authorString = '~' + data.user.name;
            $('.author').html(author);

the eloquent relationship is set up correctly. $joke->user definitely works, as I placed:

Route::get('/var', function()
{
$joke = Joke::find(1);
$user = $joke->user;
dd($user);
});

in routes.php and it comes through perfectly.

where am i tripping up?

Try converting the User and Joke objects to arrays before returning them:

if(Request::ajax())
{
    $joke = Joke::where('type', '=', 'kid')->get()->random(1);

    if (Session::has('joke'))
    {
        Session::forget('joke');
    }

    Session::put('joke', $joke);
    return Response::json([ 'joke' => $joke->toArray(), 'user' => $user->toArray()]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM