0

So in my controller logic, I build up a large array of data, which I json_encode into a variable which is passed to my view. However, I want this data to be sortable on the client side using JavaScipt--I don't think the details of how the sorting is done are relevant but I'm curious what the best way is to get my array from PHP to Javascript. Currently, I'm thinking of just having a tag in my html like

<script type="text/javascript">var jsonData = <?php echo $myData ?>; </script>

where myData is the encoded array I made in PHP, and then jsonData is available for me to use anywhere else.

However, this would mean the entire ugly array would show up in the source code of my page. This isn't a security concern or anything, but I feel that there must be a better way to do this that's not quite as "ugly". Any advice is appreciated.

1 Answer 1

1

You have two options.

If you don't want 'ugly' HTML source, you can query your application with ajax and have your json array be stored in a variable. This can be accomplished with a simple route and controller method.

In your routes.php

Route::get('api/myData',array('as'=>'api.myData','uses'=>'MyController@getMyData'));

In your MyController.php

public function getMyData() {
    return whateverYouWant();
}

You can then do an ajax request to route('api.myData')

The route method is a global function which is available in your view. It will take the named route, api.myData and generate a URL for it.

The other option is as you described, passing the array to your view.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah, I had a suspicion ajax was the answer. Thanks!
I expanded my answer with a small example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.