get php array in javascript (laravel) - javascript

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.

Related

while passing php 2d array to Javascript and try to parse using json_encode() It throws uncaught type error

I i try try to access passed php 2d array using json_encode function in javascript it throws the error that its an uncaught typeerror and the array is null, but if i print the contents of array in php only it is printing and having values in it. but it is not passing to javascript.
Both javascript and php are in same file.Below is simply a sample code snippet
var javascript_var = echo json_encode($Php_2D_array);
alert(javascript_var[0].OrderDate[1]); //javascript_var['OrderDate'].[1] earlier i tried to access like this because im having php variable index as a name as mentioned
Please help me sort out this problem
Thanks.
Try this:
var javascript_var = JSON.parse("<?php echo json_encode($Php_2D_array); ?>");
alert(javascript_var[0].OrderDate[1]);
First you need to convert to json and then javascript will take it as string, then you parse it in js.
you can encode array value in javascript by using instruction
JSON.stringify
if your array variable is in php then
var javascript_var = JSON.stringify('<?php echo $Php_2D_array?>');
if your array variable is in javascript
var javascript_var = JSON.stringify(var_array);

Passing (laravel) Array in Javascript

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.

Create array from json_encode script without double quotes

*This question was created as I had no control over the JSON output at the time. So had to use JavaScript. If you have control over the JSON, refer to Mike Brant's answer. But Oka's answer solved my issue below and is a great solution..
I'm trying to create an array that doesn't contain double quotes from JSON.
I'm getting JSON and trying to build a system where I can push non quoted items to the array.
As I have no control over the JSON, I'm making it into a string and removing the double quotes and splitting it into an array again.
The problem is this still outputs the double quotes?
var artistJSON = '<?php echo $favourites ? json_encode($favourites->artists) : '[]' ?>';
var artistIds = artistJSON.replace(/"/g, '');
var artistAry = artistIds.split(',');
console.log(artistJSON);
console.log(artistIds);
console.log(artistAry);
Results from console;
["31","41","56","38","","27"]
[31,41,56,38,,27] //This is a string. I want an array.
["[31", "41", "56", "38", "", "27]"]
https://jsfiddle.net/1pu6nqu2/
Any help would be very grateful.
*Just to confirm, my aim of the game is to remove the double quotes from within the array.
Assuming you're trying to turn stringified JSON into an array, and turn the strings inside the array into numbers. You can use some combination of .map() and .filter() to achieve this.
http://jsbin.com/yojibeguna/1/edit?js,console
var artistJSON = JSON.parse('["31","41","56","38","","27"]')
.map(function (e) { return parseInt(e); })
.filter(function (e) { return isFinite(e); });
console.log(artistJSON, typeof artistJSON[0]);
If you are using json_encode() from PHP to dynamically populate the data structure, you should not populate into a string and then parse that string, just write directly to object/array literal. So change this:
var artistJSON = '<?php echo $favourites ? json_encode($favourites->artists) : '[]' ?>';
to this
var artist = <?php echo $favourites ? json_encode($favourites->artists) : '[]' ?>;
All I did was remove the single quotes (and change the variable name to something more appropriate). Now you have a data structure you can work with directly in javascript without need for additional parsing.
If the json data is stored as JSON data already, you do not need to re-encode it with php. Just echo it out and it will be assigned to your variable artistJSON.
Example:
var artistJSON = <?php echo $favourites ? ($favourites->artists) : '[]' ?>;
Edit: As Mike Brant said, you do need to re-encode it if it's not already stored as JSON literal data (in a db, or whatnot). I'm assuming it is.
Try this:
var artistJSON = '<?php echo $favourites ? json_encode($favourites->artists) : '[]' ?>';
var artists = JSON.parse( artisanJSON );
console.log( artists );
REF: How to json_encode php array but the keys without quotes
You can just run JSON.parse to convert the string to an array.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

jQuery/javascript: use PHP return value as javaScript array

is there anyway to import a javaScript array from a PHP return value?
Say that a PHP script, 'makeArray.php', would return '"first","second","third"' (without single quotes). The purpose of the below would thus be to alert 'second'.
$.get(makeArray.php, function(data){
var responseArray = new Array(data);
alert(responseArray[1]);
...
However all I get is 'undefined'. If I was to change the array index to [0], I would get '"first","second","third"'.
Thanks!
You can use JSON.
In PHP
$myarray = array('first','second','third');
return json_encode($myarray);
In JavaScript:
$.get(makeArray.php, function(data){
console.log(data[1]); //=> "second"
}, 'json');
Edit
If you don't have PHP 5.2 then you can try echoing a string and parsing it in JavaScript:
PHP:
echo join('%',$myarray);
JS:
var array = data.split('%');
Because, what you are doing is that you are including all the data recieved form the file (makeArray.php) into the first element of an array. So, obviously it would be in the zero-index of the array.
What you should do in this case is use Array.split() function on the array like - data.split(",") to create an array from the data recieved.

javascript split and JSON.parse

I want to parse array in JSON format using javascript. I have written following code.
var data = "abc, xyz, pqr";
var data_array = data.split(',');
var data_parsed = JSON.parse(data_array);
alert(data_parsed);
It gives me the error of JSON.parse
I have no idea how to resolve this javascript error.
You don't have any JSON, so don't use JSON.parse. Once you split you already have an array whose elements could be used directly:
var data = "abc, xyz, pqr";
var data_array = data.split(',');
alert(data_array[0]);
and if you want to convert this array to a JSON string you could do this:
var json = JSON.stringify(data_array);
alert(json);
That's because "abc, xyz, pqr" isn't valid JSON. Plus, JSON.parse() is meant to parse JSON strings, not arrays. What are you trying to do, perhaps we can better assist.
This is actually a convenient short cut to json processing if you only need a smaller set of variables.
PHP:
return $var1 .','. $var2 .',some_string_value.';
Javascript:
var myReturnArray = returnValue.split(',');

Categories

Resources