JS variable inside JSON string from PHP - javascript

I am generating a JSON string from a PHP array to echo a JS object.
This is what I want to get in js:
var myVar = 123;
//php output:
var obj = {a:1, b:[1,2], c: myVar, d:Date.UTC(2014, 0, 07)}
This is what I have:
<?php
$array = array('a'=>1, 'b'=>array(1,2), 'c'=>???, 'd'=>???);
echo json_encode($array);
?>
The question is: What I put in PHP instead of question marks so that it won't be converted to string?

JSON doesn't support variables or special Date objects. You can only use scalar values (strings, numbers, booleans), arrays and objects (associative arrays).
A way to get what you want would be to return a .js file and have the browser execute that (by including it as a script) instead of transferring simple JSON data. Otherwise you could only define "special" strings that are handled by the receiving side. (For example, array ["var", "myVar"] could be parsed accordingly.)

You could actually do something like that:
<?php
$array = array('a'=>1, 'b'=>array(1,2),
'c'=>'##myVar##',
'd'=>'##Date.UTC(2014, 0, 07)##'
);
$json = json_encode($array);
echo preg_replace('/\"\#\#(.*?)\#\#\"/', '${1}', $json);
?>
But in js JSON.parse won't work, so:
eval("var x = " + json_from_php);
Not such a good idea, but if you need it, it'll work. Just remember not to use this with any "json" which are generated not by your server.

Related

How to generate a javascript like object in php

I am trying to write empty object in my database: {} however, php is always adding quotation marks.
$model->maps = json_encode("{}");
so my output becomes "\"{}\""
And I can't use this either as it will output syntax error `$model->maps = json_encode({});
Also ['' => ''] is saving it as array instead of object. Or using empty array like = [], it saves it as []
What is the proper way of handling this case? All I want is empty javascript alike object = {}
Try this: https://3v4l.org/Vb0Mb
a string '{}' is already a valid json imo but if you want to use json_encode try the code below.
<?php
// Proper way
$jsonA = json_encode(new stdClass);
// This works but more complex
$jsonB = json_encode((object)array());
echo $jsonA;
echo PHP_EOL;
echo $jsonB;

Creating "objects" and "arrays" in PHP in a way that would allows JS to distinguish between them

PHP's syntax to create an array (either indexed or assosiative) is the same, aka
$arr = [];
However, json_encode will convert an empty PHP "array" (note the quotes) to an empty JS array ([]), which is not desirable in certain situations.
Is there a way I can create an empty assosiative array in PHP, so json_encode will convert it to an empty JS object, aka {}, instead of [].
You can use stdClass:
$obj = new stdClass();
echo json_encode($obj);
This gets me the intended {} output.
Use a stdClass():
php > $x = new StdClass;
php > echo json_encode($x);
{}
Of course, once it's a stdclass, you wouldn't be able to use it as an array anymore. But this is at least one way of forcing an empty object in JSON, so you could just special-case your code:
if (count($array) == 0) {
$json = json_encode(new StdClass);
} else {
$json = json_encode($array);
}
You can just pass the JSON_FORCE_OBJECT option to the json_encode function. This will force any empty arrays to be objects as well.
JSON_FORCE_OBJECT (integer) Outputs an object rather than an array
when a non-associative array is used. Especially useful when the
recipient of the output is expecting an object and the array is empty.
Available since PHP 5.3.0.
So:
if (empty($array)) {
$json = json_encode([], JSON_FORCE_OBJECT);
} else {
$json = json_encode($array);
}
This looks cleaner than converting an object in my opinion.
Or even
$json = json_encode($array, empty($array) ? JSON_FORCE_OBJECT : 0);

Pass array from php to javascript method

In my php i make a db call, and the result is
$options = mysqli_fetch_array($result);
Now, I want to make a javascript method call and pass this function. My javascript method looks like
function myFunction(options){
//iterate over each option
}
and what I am doing is
<?php echo "<script>myFunction('".$options."')</script>";
This gives me error on my server that I am doing array to string conversion.
I thought javascript determined the datatype on runtime and hence I'll be ok with this. can someone please tell me the correct way of doing this?
Thanks
To have PHP print out an array JavaScript can use, you can convert the array to JSON string and then echo that directly.
# Convert PHP array to JSON array
$json_options = json_encode($options);
# Echo JavaScript and JSON without single quotes
<?php echo "<script>myFunction(".$json_options.")</script>";
You can not pass a php array into javascript function as array. However you can pass it as stated by Grokify or you can pass it directly assign into your a javascript variable if your function is on same page by giving into php environment.
function myFunction(){
var options = <?php echo json_encode($options); ?>;
}
Firstly, declare your JS function.
function myFunction(options){
options = JSON.parse(options);
for(var i=0; i<= options.length; i++){
console.log(options[i]);
}
}
And in your PHP side, convert array into JSON and pass it to JS function
$json = json_encode($options);
# Echo JavaScript and JSON without single quotes
<?php echo "<script>myFunction(".$json.")</script>";

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

PHP shows "{" or "[" for JSON Object Attributes sent via Angular $http

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.

Categories

Resources