Cleanly passing large JSON array from Laravel to Javascript - javascript

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.

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.

Related

Using PHP in a Javascript music player playlist

I've been working on a music player that's quite simple and to add music to it you would have to upload it to Dropbox and then manually edit the file (in this case index.php) where the playlist is held.The player then plays the links.
But what I've done is made a file which inserts value through mysql into the database.Two columns:
songname, url
Index.php:
`$(document).ready(function(){
var myPlaylist = new jPlayerPlaylist({
jPlayer: "#jquery_jplayer_N",
cssSelectorAncestor: "#jp_container_N"
}, [
{
title:"C O O L",
artist:"Le Youth",
mp3:"this is where the link must sit",
},`
How can I implement PHP query that selects the name and the link from database into that part of javascript code?
I'm sorry if there's some unclear things for you, please ask I will try to make everything clear.
PHP is a server-side language and it dies after it renders the page. So, you have two good options here.
First one is to grab all the links/names from the database, and then echo that into a JS object (using JSON seems the easiest way to handle the conversion), and then just call the link you need from that JS object. You can build the whole title/artist/mp3 object using PHP and be good to go. It should look something like this:
var mySonglist = <?php echo json_encode($databaseData) ?>;
The other option would require making AJAX calls to retrieve the link of the selected mp3. Although this might seem closer to what you're asking, due to its speed (it makes another server call), I'd suggest you do it only if you have a really, really huge number of songs at once.
So, the bottom line is: extend your PHP functionality to grab everything you need from the database, all the data, and then put that data into a JS variable which you will use to configure your player.
I am not sure that you can do db queries inside your script functions, But Do the queries outside the function and pass the php variables as arguments for the function. Below is an example.
<?php
$var="Select query here";
$name=$var[0]; $url = $var[1];
?>
<script>
play('$name','$url');
function play(name,url);
{
//your code goes here..
}
</script>

Codeigniter - sending json to script file

I query the db i my model like so
function graphRate($userid, $courseid){
$query = $this->db->get('tblGraph');
return $query->result();
}
My controller gets data back from my model and I json encode it like so
if($query = $this->rate_model->graphRate($userid, $courseid)){
$data['graph_json'] = json_encode($query);
}
$this->load->view('graph', $data);
And thats returns me a json object like so
[
{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
]
In my view graph I'm loading an js file
<script type="text/javascript" src="script.js"></script>
Now I want to use $data that is being sent from my controller to my view, to my external script.js to use as labels and data to feed my chart. But How do I get that Json data to my external script.js so I can use it?
1 more thing about the json data, isn't it possible to get the output of the json data as
{
"obj1":{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
"obj2":{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
"obj3":{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
}
The problem isn't a Codeigniter problem, it's a javascript scope/file inclusion/where-do-i-get-my-data-from problem.
I run into this all the time and have used these solutions:
naming my php files with .php extensions and loading them as if they're views.
Just putting the script that needs data from a view IN the view file where it's used
Using an ajax request in my included js file to hit a controller and get json data.
I use #2 most frequently (for things like datatables where I WANT the js code right there next to the table it's referencing.
I use #1 occasionally, but try NOT to do that because it means some .js files are in my webroot/js dir and some are in teh application/views directory, making it confusing for me or anyone else who wants to support this project.
#3 is sometimes necessary...but I like to avoid that approach to minimize the number of requests being made and to try to eliminate totally superfluous requests (which that is).
You need to print the result of the output json string to the html generated file.
But you need to parse the string with some script. I would recommend you: http://api.jquery.com/jQuery.parseJSON/
For the second question. It is possible by doing:
$returnValue = json_encode(
array (
"obj1" => array("id"=>"1","title"=>"myTitle","score"=>"16","date"=>"2013-08-02"),
"obj2" => array("id"=>"2","title"=>"myTitle2","score"=>"17","date"=>"2013-09-02"),
"obj3" => array("id"=>"3","title"=>"myTitle3","score"=>"18","date"=>"2013-10-02"),
)
);
Print the output using PHP like:
echo json_encode($query);
Then from the client-side (where JavaScript resides) load that JSON that you printed using PHP. This can be done easily using JQuery.
Like this:
$.get("test.php", function(data) {
alert("Data Loaded: " + data);
});
You can find more information about this here: http://api.jquery.com/jQuery.get/
Now you'll need to parse this data so that JavaScript can understand what you got as text from the server. For that you can use the JSON.parse method on the "data" object in the aforementioned example. Once parsed, you can use the object like any other object in JavaScript. You can find more information about JSON.parse here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
I hope that helps.

Servlet calling from window.showModalDialog(...)

I am calling another application context from window.showModalDialog but confused with following work. Same code to pass parameter within showModalDialg.
var myArguments = new Object();
myArguments.param1 = "Hello World :)";
window.showModalDialog("java2sTarget.html", myArguments, '');
and i can read these myArguments(parameters) in generated HTML using following code:
<script>
document.write(window.dialogArguments.param1);//Hello World :)
</script>
I can't use query string & i am sending myArguments(parameter) because i want to hide parameter from Application user.
Now i am calling servlet from showModalDialog(..)
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
But as per my knowledge
Servlet --> Servlet container --> HTML+JS+CSS
so JS will be available at last phase, but i want to use in first phase(Servlet).
Now, i need to make some Decision in servelt code based on myArguments(parameter).
is there any way to read these myArguments(parameters) in servlet code?
Pass it as a request parameter in the query string.
var queryString = "param1=" + encodeURIComponent("Hello World :)");
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test?' + queryString, myArguments, '');"
No, there's no other alternative. The request URL is not visible in the modal dialog anyway.
As main objective is to hide query string from User to avoid misuse of those parameters.
I tried following work around.
Developers send hidden parameters to get relative information form source(e.g.:DataBase). And we also know that we can send hidden information in Window.showModalDialog using dialogArguments
Work Around:
(i) I got relative information from server one-step before calling Window.showModalDialog using jQuery.getJSON()
(ii) i used google-gson API at servlet side to convert JavaBeans into Json strings.Solution 1 Solution 2
(iii) Convert JSON into javascript object using jQuery.parseJSON
var args = jQuery.parseJSON(json);
window.showModalDialog("pages/"+args.pageName, args, '');
i used args.pageName to make things dynamic
Please suggest improvements in this work-around. Thanks

Incorrect JSON data format

I am trying to create some JSON to be used for displaying a chart using Highcharts
http://www.highcharts.com/
I have copied one of their examples:
http://www.highcharts.com/stock/demo/basic-line
Click "View Options" under the graph to see the source. There is also a JSFiddle there to play with
If I copy that locally it all works fine.
The problem is when I try to use my own data source.
I have an ASP.Net MVC controler which is spitting out a list of arrays, just like their data source. However, that doesn't work.
Their datasource looks like this
http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
and they retrieve it like this
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) {
So I thought I'd take a step back and copy thier data exactly and put it in a text file on my server and try that:
So I tried this
$.getJSON('/data.txt', function (data) {
and this
$.get('/data.txt', function (data) {
but neither work
I have also tried using both JSON.parse and jQuery.parseJSON after retrieving the data, but again - that doesn't seem to work
I am also wondering what the ? is at the start of their data
Their data looks like this
?([[<some data>],[some data]]);
I don't get any error message, the graph just doesn't display
any ideas?
SOLVED IT
Just need to retrive the data and turn it into an array and pass it to the chart.
Needs to be an array, not JSON
That datasource is ouputting JSONP, which is for cross-domain AJAX requests. It's not valid 'raw' JSON because of that extra callback(...) wrapper.
Read up about it here: http://api.jquery.com/jQuery.ajax/ under the 'dataType' section.
As you say in your tags, it's not JSON, it's JSONP. Do not parse it, catch it with a callback. Use jQuery.getScript to do it, and define function callback(data). Inside that function, data should contain the (parsed) object. Also, replace the ? in the URL with callback (or whatever you named your function) - ? is not a valid identifier in JavaScript, so ?([....]) is nonsense.

JQuery and JSON

Here's something I want to learn and do. I have a JSON file that contains my product and details (size, color, description). In the website I can't use PHP and MySQL, I can only use Javascript and HTML. Now what I want to happen is using JQuery I can read and write a JSON file (JSON file will serve as my database). I am not sure if it can be done using only JQuery and JSON.
First thing, How to query a JSON file? (Example: I would search for the name and color of the product.)
How to parse the JSON datas that were searched into an HTML?
How to add details, product to the JSON file?
It will also be great if you can point me to a good tutorial about my questions.
I'm new to both JQuery and JSON.
Thanks!
Since Javascript is client side, you won't be able to write to the JSON file on the server using only Javascript. You would need some server side code in order to do that.
Reading and parsing the JSON file is not a problem though. You would use the jQuery.getJSON function. You would supply both a url and a callback parameter (data isn't needed, because you're reading a file, so no need to send data). The url would be the path to your JSON file, and the callback would be a function that uses the data.
Here's an example of what your code might look like. I don't know exactly what your JSON is, but if you have a set called "products" containing a set of objects with the details "name" and "price", this code would print those out:
$.getJSON("getProductJSON.htm",
function(data) {
$.each(data.products, function(i, item) {
var name = item.name;
var price = item.price;
// now display the name and price on the page here!
});
},
);
Basically, the data variable in $.getJSON makes the entire contents of the JSON available to you, very easily. And the $.each is used to loop over a set of JSON objects.

Categories