Search code examples
javascriptphphtmllaravellaravel-5.3

How to pass data from Laravel View to Ajax or Javascript code without html div (id or class) - Laravel 5.3


So, currently I am passing values stored in Database MySQL to View (using Controller). I do simple querying ModelName::where()->first();.

I have my data right now in View. I want to use that data in Ajax or Javascript code that I am writing.

I can have 46 values and one way to do this is to have <div id="field1"></div> for 46 times set div style to display:none in css and in Javascript use document.getElementById('field1'); to access the values and finally, do whatever I want to do with it.

But I find this quite long and un-necessary to do as there is no point of printing all the values in html first and then accessing it. How can I directly get {{$data}} in Javascript?

myCode

public function index(Request $request){

        $cattfs = Cattf::all();
        $cattts = Cattt::all();
        $cattos = Catto::all();

        return view('/index',compact('cattfs'));
}

View

Nothing in the view. and I prefer it to be none.

Javascript and Ajax

$(document).ready(function()
{
    init(); 
});

function init(){
    my_Date = new Date();
    var feedback = $.ajax({
        url:url,
        dataType: "JSON",
        type: "GET",
    }).success(function(data){
   console.log(data);
  //I have some data called data from url
  //I want some data from controller like: cattf,cattt,catto
  //I will combine url data and cattf and do simple arithmetic to it
  //finally output to the view.
  }).responseText;
}

Solution

  • One good way would be to actually make a small API to get your data. Let's say you wanted to retrieve users.

    In the api.php file in your route folder:

    Route::get('/posts', function () {
        return Post::all();
    });
    

    and then you just need to use http://yourUrl.dev/api/posts as your URL sent in your .ajax() call to work with what you need.