I am working with Blockly to make some Blocks. All the errors came up when I am making Blockly Blocks.
IS there anyone who knows why my code is not working in Blockly?
I have a URL including a set of JSON code.
I got the content in a myPhp.php file using:
$data = file_get_contents("URL");
and then, I decode the data using:
$objects = json_decode($data, true);
$objects contains:
[0] => Array
(
[name] => Light
[x] => 5
[h] => 5
[y] => 5
[status] => on
)
Now I want to push this array of data into a JavaScript array using:
<script type="text/javascript">
var obj = new Array();
<?php
foreach($objects as $key => $value){
?>
obj.push('<?php echo $value; ?>');
<?php } ?>
</script>
And $value needs to have all those data.
But I am getting Invalid or unexpected token JavaScript error. and when I look at to the source code, it shows the error is related to this line: obj.push and it says obj.push('<br /> <b>Notice</b>: Array to string conversion in <b>myPhp.php</b> on line <b>20</b><br /> Array');.
Your $value itself is an array and here your $key is 0.
$key
[0] =>
$value
Array
(
[name] => Light
[x] => 5
[h] => 5
[y] => 5
[status] => on
)
So you need another loop for $value to obtain each value like thus
<script type="text/javascript">
var obj = new Array();
<?php
foreach($objects as $key => $value){
foreach($value as $key1 => $value1){
?>
obj.push('<?php echo $value1; ?>');
<?php } }?>
</script>
Instead of going through the hassle of looping through the array or even decoding it (unless there is a specific reason to do so), just use json_encode. JSON is JavaScript's native language, so it will understand it.
<?php
$data = json_decode(file_get_contents("URL"));
?><script type="text/javascript"><?php
// echo out JSON encoded $data or a string of '[]' (empty JS array) if it is a false value (error occured with json_decode)
?>var obj = <?= json_encode($data) | '[]' ?>;<?php
// In JavaScript "Light" is available as obj[0].name or it does not exist (empty array if an error occured with json_encode or json_decode)
?></script>
A few things to get you started:
JSON is "JavaScript Object Notation". Though it is used in many other languages, JavaScript understands it natively.
This means that once you've got a JSON string, you can get a JavaScript object out of that directly. If the JSON string represents a single object, you'll get a single JavaScript object. If it represents an array, you'll get a JavaScript array of JavaScript objects. If it is some nested structure, then you'll get just that. In a modern browser all you need on the JavaScript side is
JSON.parse(...) to do the magic.
To get the JSON into JavaScript, either:
Get it in JavaScript directly, using XMLHttpRequest or helpers such as jQuery's $.get. That will need you to understand some asynchronous programming, so maybe indeed one of the following is easier to start with:
Get it in PHP, parse it like you tried in your question, and then generate proper JavaScript to create a JavaScript object or array again. Note that PHP's json_decode gets you some associative array, which you then need to map to a JavaScript object.
Get it in PHP, do not parse it at all, and simply forward the JSON string to JavaScript and parse it there, using JSON.parse.
Get it in PHP, use Jim's simple solution to get it into JavaScript.
When generating JavaScript in PHP, you need to be careful with quotes, newlines and other special characters in string values. Like if the JSON is:
{"quote": "She said: 'Beware', and walked off"}
...then you cannot just concatenate text into obj.push('...') as that would create invalid JavaScript:
obj.push('She said: 'Beware', and walked off');
Above, JavaScript does not know what to do with the text after the second single quote, and throws Uncaught SyntaxError: missing ) after argument list. Likewise, newlines may be troublesome, like when unexpectedly getting a PHP error while generating the JavaScript (for reasons explained in Osama's answer), which will yield invalid JavaScript and throw Invalid or unexpected token:
obj.push('<br />
<b>Notice</b>: Array to string conversion
in <b>myPhp.php</b> on line <b>20</b><br /> Array');
In the JSON example above, you could use double quotes in obj.push("..."), to generate:
obj.push("She said: 'Beware', and walked off");
But in general you might not know what values you get, so you need to "escape" troublesome characters.
I don't know enough about PHP to know what's the best way to escape the strings. As (valid) JSON uses double quotes, it should already have escaped double quotes when needed. So, a JSON string might look like:
{"quote": "She said: \"Beware\", and walked off.\n\nWe'll remember her."}
Above, you need to take care of the backslashes that JSON already added for escaping. So PHP's addslashes might do, bus I did not test this:
<script type="text/javascript">
var obj = JSON.parse("<?= addslashes($data) ?>");
</script>
Otherwise, when first parsing $data into a PHP object using json_decode (or when not even doing that!), Jim's simple solution is certainly preferred.
Related
I'm trying to save a string which is encoded as json into another json string.
In particular, I have to be able to handle empty objects: "{}".
PHP:
$sVal = "{}";
$jsonString = "{\"Var2\":\"My first var\", \"Var2\":\"My second var\", \"MyBlankObject\":\"{}\"}"
...
Javascript:
var oMyJSON = JSON.parse('< ?= $jsonString;? >');
I get a JSON parse error saying an unexpected { was found.
I can see the code in Chrome's debugger.
The brackets are simply removed and in the client side (javascript ) code, the object is replaced with the word null. That's not valid JSON.
,"Properties":null,
This causes javascript to crash.
If I try to json_encode it on the server side (PHP) I get double quotes on each side of the brackets.
,"Properties":""{}"",
I get the same thing if I just add the double quotes: ""{}""
Of course, this causes javascript to crash too.
Once in the client and I have the JSON object intact, I need to be able to extract the 'string' held in the property: MyBlankObject and then decode that JSON into a seperate JSON object.
Everything I've tried fails. How can I accomplish this?
You can define the object using PHP notation, and let json_encode encode it for you.
$phpArray = [
'Var2' => 'My first var',
'Var2' => 'My second var',
'MyBlankObject' => new \stdClass
];
And then in the JavaScript:
var oMyJSON = JSON.parse('<?= json_encode($phpArray); ?>');
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;
I have a a function that returns an array that is structured like this
[[{"title":"Mr","first_name":"James","last_name":"Loo","date_of_birth":36356,"email":"test#test.com","phone_number":1234567890,"company":"CompanyOne"},{"title":"Mr","first_name":"Jonah","last_name":"Lee","date_of_birth":42629,"email":"test#test2.com","phone_number":1234567890,"company":"CompanyTwo"}],
[]]
Within the array are 2 arrays. The first one is a "entry not inserted" array and the second one is a "entry inserted" array.
However when I execute the code through this function
$result = $this->curl->execute();
$result_errors = array();
for($j=0;$j<sizeof($result);$j++){
$result_errors = $result[0];
}
if(sizeof($result_errors)>0){
echo json_encode($result_errors);
}
The result I get in the console is "[" only.
Am I missing something? I have read that I had to echo and json encode arrays but it doesn't seem to be coming out.
if $result is literally as you've printed above, then it's not a PHP array, just a string in JSON format. PHP can't interpret it until you decode it. Your for loop is a waste of time because you always assign the first index of $result to your $result_errors variable. In PHP if you try to fetch an index of a string, you simply get the character which is at that place in the string. The first character of $result is "[".
If you're trying to get the first array out of that response, you need to decode the JSON into a PHP array, select the first inner array, and then re-encode that back to JSON for output, like this:
$array = json_decode($result);
echo json_encode($array[0]);
That will give you the first array, containing the two objects. If that's not the output you're after, then please clarify.
I am not sure you will get what you want but the problem is the assignment to $result_errors. That var should be an array but when you make the assignment $result_errors = $result[0]; your change it from an array to whatever value is at $result[0]; Try this
for($j=0;$j<sizeof($result);$j++){
$result_errors[] = $result[0];
}
My question to you is: Since $result is apparently an array (as indicated by the use of $result[0]) then why not simply do this?
echo json_encode($result);
A suggestion: Instead of sizeof use count.
if(count($result_errors) > 0)
{
echo json_encode($result_errors);
}
count is less likely to be misunderstood by others. It has a totally different meaning in other programming languages.
Oh, and the answer from #ADyson is right to point out the need to decode the json string into a PHP array.
Im sending a array after converting it into JSON using
var json_arr = JSON.stringify(info);
and JSON is,
{"1":"111112221111","2":"1111122211","3":"11111222"}
I'm sending this JSON as value of a text box (In form field using post method).
And I'm printing it in a php file as
$this->log->write($data['infoArray']);
It prints as
{"1":"111112221111","2":"1111122211","3":"11111222"}
I tried
json_decode($data['infoArray'],true);
but it prints nothing (blank)
so when I'm trying to iterate through it as,
foreach ( $data['infoArray'] as $key => $value) {
$this->log->write("key :".$key);
$this->log->write("value :".$value);
}
it throws warning
PHP Warning: Invalid argument supplied for foreach()
So my questions are,
why "" are getting replaced by ".
how can I iterate through JSON so I can access key and value in it.
I don't know what does your log() method exactly do so I can't really tell you why.
Use html_entity_decode() before json_decode()-ing the value of $data['infoArray']
Try this:
$decoded = json_decode( html_entity_decode( $data['infoArray'] ) );
foreach ( $decoded as $key => $value) {
$this->log->write("key :".$key);
$this->log->write("value :".$value);
}
1.why "" are getting replaced by ".
Actually it's " and it's html format for displaying quotation mark. I think JSON wants to keep quots from being mixed with other key values in you JSON array so it replaced them by "
2.how can I iterate through JSON so I can access key and value in it.
Try json_decode()
So for the warning try to decode html special charaters first, then use JSON decode then use it in foreach:
$json_decoded = htmlspecialchars_decode(json_decode($data['infoArray']))
foreach ( $json_decoded as $key => $value) { ...
infoArray is a json string not an php array (you will have to use json_decode php function first to convert the posted json string to php array).
The " is added by the log function (i guess it is printed in some html), so double quotes are escaped by default (by the function) to "
Since JSON is posted as value of textbox the escaping is probably done there and the " are replaced there before postinbg to php. Use html_entity_decode before using json_decode. Although passing json data as part of textfields seems awkward in the first place
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.