I want to pass/store Laravel array in JavaScript variable. I used ->all() so I get the result like this rather than object:
array:83 [▼
0 => 1
1 => 11
2 => 12
...
]
I can access this in view using {{ $theArray }}.
However whatever I tried, I couldn't make this to javascript array.
I tried
var array = {{ $theArray }};
var array = {{{ $theArray }}};
I feel like I'm close but I couldn't figure it out
var app = #json($array);
Works like a charm
you can use json_encode()
var array = {{ json_encode($theArray) }};
or parse the json string using JSON.parse()
var array = JSON.parse('{{ json_encode($theArray) }}');
This works for me :)
var array = {!! json_encode($theArray) !!};
Sometimes you may pass an array to your view with the intention of rendering it as JSON in order to initialize a JavaScript variable. For example:
<script>
var app = <?php echo json_encode($array); ?>;
</script>
However, instead of manually calling json_encode, you may use the #json Blade directive. The #json directive accepts the same arguments as PHP's json_encode function:
<script>
var app = #json($array);
var app = #json($array, JSON_PRETTY_PRINT);
</script>
The #json directive is also useful for seeding Vue components or data-* attributes:
<example-component :some-prop='#json($array)'></example-component>
https://laravel.com/docs/5.8/blade#blade-and-javascript-frameworks
you have enclodse with quotes,or use json_encode()
var array = "{{ $theArray }}";
^ ^
or, if the value in an array()
var array = "{{ json_encode($theArray) }}";
^ ^
Without having quotes around javascript variable, it will throw you error. you can check in your console.
this one worked for me.
let array = JSON.parse('{!! json_encode($array) !!}');
Sometimes all() is not enough to convert your Laravel collection to array. I encountered this issue trying to pass the collection of custom type objects to JS via Laravel view.
To get the array on the front end JS you have to apply Collection::values() method before all() method.
So:
// In your HTTP controller
$collection = collect([myObj1,myObj2]); // The collection filled with custom type objects.
$myArray = $collection->values()->all(); // Then converted to an array. Just `all()` is not enough;
return view('myview', $myArray);
{{-- In your myview.blade.php --}}
<script>window.myArray= #json($myArray)</script>
Then in your JS window.myArray you get an array [], not an object {}.
A Bit Of Details
This is probably happens due to the fact that when an array indexes are not ascending ordered PHP considers the indexes to be object keys, then it considers the array to be an object. Thus the transformation to an object instead of an array. Laravel collection values() resets the array keys. I suspect it applies PHP array_values() under the hood.
In my case I needed a Laravel Collection to pass through as an iterable array on the JavaScript client. The following worked:
return array_values($job_summaries->toArray());
Using the blade directive #json was the simplest thing that worked for me.
<script>
var jsArray = JSON.parse(#json($phpArray, JSON_PRETTY_PRINT));
</script>
Here is the full list of parameters for #json and json_encode https://www.php.net/manual/en/json.constants.php
Both jsArray and JSON.parse() are javascript
The blade directive is #json()
No curly braces needed with directives
Simply, escape the special characters using the blade syntax. Try this.
var array = {!! $theArray !!};
Best part, you don't need to parse it to its object form in JavaScript.
Related
I am using the Flask framework to obtain a dictionary object with the key set to the user ID and the value set to the username. From the view in Flask I am converting it to json using jason.dumps and when rendering the template, outputting direct to the Javascript code for example:
<script type="text/javascript">
var = {{ users }};
...
</script>
When I examine the rendered HTML code the string value outputted looks as below, example given for one user:
var = {"5d626ba11c9d4400004665b5": "shears"};
As you can see it is encoding the quote characters to their character value. How do I get this to output as a JSON object in the Javascript?
You could render a template variable inside a string, unescape HTML and then parse the result as JSON.
function unescapeHtml(safe) {
return $('<div />').html(safe).text();
};
var usersDict = JSON.parse(unescapeHtml('{{ users }}'));
The usersDict variable is an object:
Object { 5d626ba11c9d4400004665b5: "shears" }
Hope this helps.
I want to pass php array in javascript code . when i use like this:
var resData = "{{ json_encode($data['calendarItems']) }}";
or this :
var resData = "{{ $data['calendarItems'] }}";
in both the result is :
[{"title":"rfvd vc","expired_at":"2018-12-31 00:00:00"}] //formatting
and JSON.parse return error. I can not get the array
There's two issues here. The first is that you're quoting the json output and the second is that the result is escaped to html entities.
Remove the quotes and output the result in raw format:
var resData = {!! json_encode($data['calendarItems']) !!};
Omitting the quotes around the result will remove the need to use JSON.parse(), since the variable will contain proper json from the start.
Read more about unescaped data in blade in the manual
When you do {{ }} it converts string elements inside into html entities. so { will be converted to "
I will suggest to use this package, which has cleaner implementation of passing data as usable js variables in your blade file.
You can try this:
var mapData = JSON.parse('<?php echo json_encode($latLng) ?>');
where $latLng is a PHP array.
What I want to accomplish is to pass a 2D array from javascript to something that ruby will recognize. All objects are strings
I have been using gon-sinatra, but it doesn't do exactly what I need.
I can pass store the string I want to pass as gon.text doing
#temp = gon.text
array.push(#temp)
This doesn't work because it shows gon.text as a nil object type, when I want it as a string. gon.text.to_s returns an empty string, so when I try to display it, nothing happens. alert("<%= #temp %>") // displays an empty string
I'm at a bit of a loss here and don't know the best way to approach this. Would it be better to store the array as a json, and then read in the json using ruby instead?
Yes. Convert your array to json(a string) with js:
var data = JSON.stringify(yourArray);
Send the string to your ruby script. Then parse the string into an Array with ruby:
require 'json'
arr = JSON.parse(the_string)
In Javascript you do something like the following:
var myArray = [ ['str1','str2'], ['str3','str4'] ];
$.get('/endpoint', { myArray: myArray })
And your endpoint with sinatra would be:
get 'endpoint' do
myArrayStr = params[:myArray]
error!('invalid array') unless myArrayStr
#myArray = JSON.parse(myArrayStr)
gon.rabl 'goners/yourFile.rabl', :instance => self
end
And in your gon file you would reference this with:
alert(gon.myArray[0][0]); // str1
I am getting response in below format for every product and in a single call there can be many products. I am trying to access this data via jQuery but I'm not able to access it.
Productdata['someid'] = { "Product Json data"}
I am using below syntax in jQuery but not getting the data. Please suggest.
alert(Productdata['someid']);
Its not going as JSON format .
JSON is a key : value pair format ;
so your Productdata should be in below format:
Productdata = { 'someid' : "Product Json data"}
A Json like this
var data={"name":"somebody"};
To call
return data.name
Or
return data["name"]
The problem here is that JavaScript does not support associative arrays (scroll down to "Associative arrays, no way!"). It has some internal workarounds which make it appear as if it does, but really all it does is just adding the keys as properties.
So you would most likely be able to access it using Productdata.someid = ....
EDIT:
So assuming you have the following JSON string: {"id":"123"} (which is valid JSON), you can use it like this:
var jsonString = '{"id":"123"}';
var parsedJSON = $.parseJSON(jsonString);
var productID = "product_" + parsedJSON.id;
Does this help?
Some useful links: JSON format checker to make sure the JSON is valid.
Unfortunately I wasn't allowed to add more than 2 links, so the jQuery parseJSON function link is still in the comment below.
I've never seen this problem before, and I can't find the issue anywhere online. I'm using Angular to post form data to a PHP page. I'm using the file_get_contents() method of retrieving the POST data, which is a simple JSON object.
The problem arises with the data attributes - when I assign php vars to the data, they always have the value "{" or "[" (I echo'd and logged them). Any idea what could be causing this problem?
The relevant form declaration:
<form name="itemForm" ng-if="true" id="newItemForm" class="add-item" ng-submit="addItem(itemForm)">
<input type="text" class="form-control data-entry" ng-model="itemForm.itemType" placeholder="Type" ng-focus="true">
Here's my Angular function:
$scope.addItem = function(itemForm) {
$http.post("../ajax/addItem.php", itemForm).success(function(data) {
//console.data(JSON.stringify(itemForm));
console.log(data);
currItem = itemForm;
itemsArr.push(angular.copy(itemForm));
$scope.itemForm = defaultForm;
getItem();
});
};
partial PHP:
<?php
$params = file_get_contents('php://input');
if($params){
$item = $params["item"];
$type = $item["itemType"];
//get other parameters, insert into MySQL database
echo json_encode(["type = " => $type]);
}
?>
You're using string-based keys for your array. In Javascript terms, that has to be represented as an Object, which uses {} as the delimiters. Proper arrays, which use [], only accept numerical keys.
And note that type = as an array key is somewhat redundant. Why not just type?
The file_get_contents function returns a string, so the $params variable is a string not an array. However, strings in php can be accessed in an array like fashion (except the key must be a number). In your code $item = $params["item"] should will give you a php warning and php will automatically assume an index of 0 since the key you gave was not a number. This is why you were getting { or [ when you echoed the data from php (because valid json is enclosed by {} or []).
To use $params as an array like you are trying to do you first need to do $params = json_decode($params). This will only work assuming you have a valid json string in the file you are reading from.