Skip to content

Instantly share code, notes, and snippets.

@jimgwhit
Created June 30, 2020 01:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimgwhit/2a39e9956c6c686933860cb431c7d4a5 to your computer and use it in GitHub Desktop.
Save jimgwhit/2a39e9956c6c686933860cb431c7d4a5 to your computer and use it in GitHub Desktop.
Json response with Jquery

Just quick examples, so apply validation and authentication and authorization as needed.

For returning a single record:

    public function testc() {
        $dogid = Request::input('somevar');
        $dog = Dog::find($dogid)->toArray();
        return Response::json($dog);
    }

And in the success:

success: function (data) {
    if (data.error) {
        //handle the error
    } else {
        $('#dogname').val(data.dogname);
        $('#comment').val(data.comments);
    }
}

Multible records returned:

    public function testg() {
        $dogid = Request::input('somevar');
        $dog = Dog::select('dogname', 'comments')
                ->where('dogid', '<', $dogid)
                ->get()->toArray();
        return Response::json($dog);
    }

And in success

success: function (data) {
    $('#dogname').val(data[0].dogname);
    $('#comment').val(data[0].comments);
    $('#dogname2').val(data[1].dogname);
    $('#comment2').val(data[1].comments);
    // just showing two rows
    }

Or looping

for (var i = 0; i < data.length; i++)
    {
      var item = data[i];
      alert(item.dogname + " " + item.comments);
    }
    // alert just for example
    // do what you need to do with the data
@jimgwhit
Copy link
Author

Note: Notice the use of

->toArray();

I have never had trouble with a Json response when using that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment