Firstly, I have search Stack Overflow for the answer, but I have not found a solution that works.
I am using an MVC framework (yii) to generate some views and throw them in an array. Each view is a card, and I have an array of cards ($deck) as well as an array of arrays of cards ($hands, the list of hands for each player). I'm simply trying to set a javascript variable on the front-end to store the hands created in PHP. My view has, it is worth noting, multiple lines. In fact, my current test view consists only of:
test
test
I therefore used json_encode, but it's giving me the following error when I use $.parseJSON():
Uncaught SyntaxError: Unexpected token t
I read elsewhere that it is required (for whatever reason) to use json_encode twice. I have tried this, but it does not help.
With a single json_encode, the output of echoing $hands (followed by an exit) looks pretty healthy:
[["test\ntest","test\ntest","test\ntest","test\ntest", etc...
But when I do not exit, I get a syntax error every time.
Edit: Here is a sample of my code. Note that $cards is an array of HTML normally, but in my simplified case which still errors, includes only the two lines of 'test' as mentioned above.
$deck = array();
foreach ($cards as $card) {
$deck[] = $this->renderPartial('/gamePieces/cardTest',
array('card'=>$card), true);
}
$hands = Cards::handOutCards($deck, $numCards , $numPlayers);
$hands = json_encode($hands);
echo $hands; exit;
With JavaScript, I am doing the following:
var hands = $.parseJSON('<?php echo json_encode($hands); ?>');
It errors on page load.
Any help would be appreciated!
Thanks,
ParagonRG
var hands = $.parseJSON('<?php echo json_encode($hands); ?>');
This will result in something like:
var hands = $.parseJSON('{"foobar":"baz'"}');
If there are ' characters in the encoded string, it'll break the Javascript syntax. Since you're directly outputting the JSON into Javacript, just do:
var hands = <?php echo json_encode($hands); ?>;
JSON is syntactically valid Javascript. You only need to parse it or eval it if you receive it as a string through AJAX for instance. If you're directly generating Javascript source code, just embed it directly.
Related
I am successfully executing a query on an SQL database.
$sql = "SELECT id, scdTempC, scdRH, ..., gt1pt0um, reading_time FROM Sensor order by reading_time desc limit 96";
Then, there is this and I don't know, at all, what it is doing.
$scdTempC = json_encode(array_reverse(array_column($sensor_data, 'scdTempC')), JSON_NUMERIC_CHECK);
$scdRH = json_encode(array_reverse(array_column($sensor_data, 'scdRH')), JSON_NUMERIC_CHECK);
It returns a set of 96 values for each column selected. Those go into a HighCharts chart for presentation in a browser.
Then, there is this and I have no idea, at all, what it is called or what it is doing:
var scdTempC = <?php echo $scdTempC; ?>;
var scdRH = <?php echo $scdRH; ?>;
var bmeBP = <?php echo $bmeBP; ?>;
And those vars feed into the HighCharts code:
series:
[{
marker: { symbol: 'dot' }, showInLegend: false,
name: 'SCD41 Temp', data: scdTempC
}],
Is there any way to get to the individual values and do arithmetic on them? Specifically, adjust centigrade temperature to Fahrenheit or Barometric pressure in hPa to inches of Mercury. Yes, I could add another column and feed in °F or inHG, but that seems wasteful if I can adjust the numbers on the fly. The result would need to look like what came from SQL and, as far as I know, that is a CSV string of numeric values. This is being done in a .PHP file. I don't know PHP yet. If this is too crazy or complicated, then just say so and I will go the other way with adding another column of data. Maybe it is SQL that I need, not PHP. Sorry, a bit lost and it shows!
It seems like I would use "foreach" and loop through the original list making up a new list with the same format (CSV?) and adjusted values. Is that even close?
I am a long-time programmer having worked with at least 12 languages but very new to PHP and SQL. Just started working with it inside an existing project a week ago and needing some pointers for modifying it. I have done a lot, already, but got stuck, here. Since I am jumping into the middle of this, it is difficult to even know what to search for. Search hints would be gladly accepted. THANKS for any help!!!
Mike
These lines appear to be the most important for you
$scdTempC = json_encode(array_reverse(array_column($sensor_data, 'scdTempC')), JSON_NUMERIC_CHECK);
$scdRH = json_encode(array_reverse(array_column($sensor_data, 'scdRH')), JSON_NUMERIC_CHECK);
Since you say that the numbers are feeding through to the HighCharts configuration, the above must be working fine.
What the above is doing, is that each line is converting one column of the database query results into a JSON array that can be used in the JavaScript.
Since you say you have little experience in PHP, but you do have experience in SQL, I recommend you stick to what you know and use the SQL for the arithmetic. That way you have one less problem to work on, and you can concentrate on just getting that data to the chart.
What you're asking to do is quite basic, and beyond the scope of a single answer here - the short answer is that you really need to read or watch a PHP tutorial, sorry! But since you say you've used 12 languages, you should find it easy to pick up - PHP is very much like most other C-like languages, so you should not have a problem catching on.
A clue: when you want to know what a PHP function does, just put it after "https://php.net/" in a browser. example: https://php.net/array_column
It’s important to recognize that there are 4 languages in play here: SQL, PHP, HTML, and Javascript.
In a script using best practices, you will see PHP on the top, doing all the logic and data collection/manipulation (SQL calls). Under that, you’ll see a PHP close tag (?>) followed by HTML with embedded Javascript. PHP looping, conditionals, and variable substitution are accomplished as seen here:
<?php
// work with user input
// get sql stuff
// work with sql results
$scdTempC = json_encode(array_reverse(array_column($sensor_data, 'scdTempC')), JSON_NUMERIC_CHECK);
$scdRH = json_encode(array_reverse(array_column($sensor_data, 'scdRH')), JSON_NUMERIC_CHECK);
// send output to browser
?>
<html>
… snip …
<!-- simple looping example; there are other ways to do it -->
<ul>
<?php foreach($rows as $row) { ?>
<li><?php echo $row; ?></li>
<?php } ?>
</ul>
… snip …
<!-- now starts javascript -->
<script>
// note the javascript is not running yet; we are filling in values from PHP
// The javascript will run in the browser after PHP serves it
var scdTempC = <?php echo $scdTempC; ?>;
var scdRH = <?php echo $scdRH; ?>;
var bmeBP = <?php echo $bmeBP; ?>
// more javascript
// your solution is down here somewhere. While iterating through the array,
// make a call to the appropriate javascript converter function to translate
function toFahrenheit(celsius)
{
return celsius * 9 / 5 + 32;
}
function toCelsius(fahrenheit)
{
return (fahrenheit - 32) * 5 / 9;
}
</script>
Here’s the important part for you: the javascript is not executed on the server, it’s executed in the browser after the php has finished and sent its output.
It appears that you are passing an array to javascript, which is then creating the desired output.
The solution then would be to create a function in javascript to convert to the desired unit of measure, as javascript is creating its output.
My advice is to concentrate on the javascript and solve the problem there.
Actually I want convert json array to string for that I used json_decode but it is returning nothing How to solve this?
Below is my array,
[{"Product":"Fantasy Brown","productimage":"images/fantasy-brown.jpg"},{"Product":"Bruno White","productimage":"images/bruno-white.jpg"},{"Product":"Barcunda Black","productimage":"images/barcunda-black.jpg"},{"Product":"Iceberg","productimage":"images/iceberg.jpg"},{"Product":"Mercury White","productimage":"images/mercury-white.jpg"},{"Product":"Desert Brown","productimage":"images/desert-brown.jpg"},{"Product":"Blue Venatino","productimage":"images/blue-venatino-marble.jpg"}]
the above array should be converted to string and also I want display product and productimage in string format from that array.
Below is my code,
$cart_items = "<script>document.write(localStorage.getItem('cart'));</script>";
echo "<pre>";
print_r($cart_items);
die;
$details = json_decode($cart_items);
// $x = $cart_items[];
echo $details;die;
You code wouldn't work. You're mixing client side and server side programming in a wrong way.
From the server point of view, $cart_items is only a string containing:
<script>document.write(localStorage.getItem('cart'));</script>
Nothing more.
It is your browser that parse the server output, i.e. the Javascript, to the JSON string. Since the conversion only happens on browser side, the server side (i.e. your PHP script) doesn't get it.
You need to reconsider your code logic. Maybe you need to have javascript that submit the localStorage content to server. Or maybe have your problem solved only with Javascript.
you all need to set json_decode() 'true' i.e
$details = json_decode($cart_items,true);
I have a form with fields and a text-area that allows any characters to be entered. I can't just submit the form, because the form is being recycled many times over, so the form values are being stored in associative arrays:
<form name='Theform'>
<input type="text" id="VISITOR_DETAILS_NAME" value="Joe">
<input type="text" id="VISITOR_DETAILS_SIZE" value="Large">
<textarea id='VISITOR_DETAILS_INFO'>
User can enter anything here including double " and single ' quotes
</textarea>
<input type="hidden" name="package" id="package" value="" />
</form>
The text-area value are stored in a JavaScript array along with the other form values:
myArray[0]['VISITOR_DETAILS_NAME'] = document.getElementById('VISITOR_DETAILS_NAME').value;
myArray[0]['VISITOR_DETAILS_SIZE'] = document.getElementById('VISITOR_DETAILS_SIZE').value;
myArray[0]['VISITOR_DETAILS_INFO'] = document.getElementById('VISITOR_DETAILS_INFO').value;
I end up with an array something like this:
{
VISITOR_DETAILS_NAME : "Joe",
VISITOR_DETAILS_SIZE : "Large",
VISITOR_DETAILS_INFO : "User can enter anything here including double " and single ' quotes"
};
I then pass this JavaScript array to the hidden form field using JSON.stringify and then POST this to PHP:
document.getElementById('package').value = JSON.stringify(myArray[0]);
Theform.submit();
(For now I'm just posting to an iframe to test that the JSON is passing the JavaScript arrays properly through POST).
When I get it on the PHP side - it seems good to go. It looks like the JSON.stringify has added the backslash to the double quote (\" ) - and now I want to store the values in MySQL. But I want to first test that I can send/reconstruct the JSON back to the javascript as an array - so I try this:
parent.myArray[0] = JSON.parse('<?php echo $_POST['package']; ?>');
I get an ERROR: SyntaxError: Expected token ')' OR SyntaxError: missing ) after argument list
This is strange to me - because when I try it without POSTING - It seems to work fine like this:
document.getElementById('package').value = JSON.stringify(myArray[0]);
now if I try to just pass back the stringified value back to the array
myArray[0] = JSON.parse(document.getElementById('package').value);
- it seems to work fine - no errors
QUESTIONS:
Why am I getting this error when trying to reconstruct the ARRAY from the
POSTED JSON.stringify() value?
Do I save this JSON.stringify() value in MySQL as is?
Or do I PHP json_decode() it first?
I want to grab the form data - handle it properly - store it in MySQL and then read it back into the form when I need it.
Thanks All :)
parent.myArray[0] = JSON.parse('<?php echo $_POST['package']; ?>');
Here you are are trying to convert a JSON text into an HTML representation of a JavaScript string representation of a JSON text, but you aren't doing anything to escape it for either.
If you have any ' characters in the JSON data, then they will terminate the JavaScript string.
If you have any " characters in the JSON data, then they will be represented as \", but \" is a JavaScript string representation of ". Since you don't do anything to escape the text you put in the JS string, the slash character will be consumed by the JavaScript parser and will be gone before it reached the JSON parser.
If you want to convert data for placing in a JavaScript string then you need to escape it.
However, JSON is a subset (almost) of JavaScript. So the process of converting a JSON text to a JavaScript string so it can be parsed into a JavaScript object is over-complicated. You can skip that can just go straight to:
<script>
var foo = <?php echo $json; ?>
</script>
However, since you are taking in the JSON from the client, echoing out directly will expose you to XSS attacks. In order to deal with this you should filter the data on the server.
This will:
Fail to parse any invalid JSON and so not output bad JSON (but it might output nothing, giving you a JSON syntax error, you should apply tests to see if the parse was successful and output a sensible default case if it fails).
Convert any </script> in the data to <\/script> making it safe to place in a script element (because that is how PHP's json_encode works
Such:
<!-- I don't do PHP, this is untested -->
<script>
var foo = <?php
$unsafe_json = $_POST['package'];
$data_structure = json_parse($unsafe_json);
$safe_json = json_encode($data_structure);
echo $safe_json;
?>;
</script>
Do I save this JSON.stringify() value in MySQL as is? Or do I PHP json_decode() it first?
That depends on what you intend to do with the data. In general when putting things into a database it is a good idea to extra the data from the data format and normalize it. That way you can run queries over it.
If you are only going to store the data and then retrieve it, you might be able to get away with not doing that and storing strings of JSON in the database. That loses you a lot of flexibility though and might bite you in the future.
Using http://objectmix.com/javascript/389546-reading-json-object-jquery.html as a starting point, I have been reading lots about JSON. Unfortunately I am a total beginner and can't get my head around the basics of creating JSON objects.
I have created a PHP page called getContact.php
<?php
"Contact": {
"ID" : "1",
"Name" : "Brett Samuel"
}
?>
And a javascript file with the following code:
$.getJSON('getContacts.php', function(data) {
var obj = (new Function("return " + data))();
alert(data.Contact.Name)
});
This page http://msdn.microsoft.com/en-us/library/bb299886.aspx suggests I have the basic approach correct. Can anyone tell me why this does not work? Absolutely nothing happens.
Thanks in advance.
Your PHP file contains JSON, which is not valid PHP, and will therefore error.
If you're working with PHP the easiest way to build JSON is to first prepare your data as an array (associative or indexed, as required) then simply convert it via json_encode(). (You can also decode JSON, with the corresponding json_decode().
[EDIT - in response to comment, just have a look at the PHP docs for json_encode() - it's very self explanatory. You take an array, pass it to json_encode(), and you get a JSON string.
$arr = array('one', 'two', 'three');
echo json_encode($arr); //JSON string
JSON is not a programming language, and it's certainly not executable as PHP. It's just a file format. If you want your web server to serve up a static JSON file, just drop it in the file system as filename.json, without any <?php tags. (Of course, as with HTML, you can also make it a .php file and just not have any PHP in it, other than something to set the Content-Type since the file suffix won't do it automatically. But that's wasteful.)
If you want to dynamically generate some JSON with PHP, then you have to write PHP code to print it out, e.g.:
<?= json_encode( array(
'Contact' => array('ID' => 1, 'Name' => 'Brett Samuel' )
) ); ?>
Also, note that a JSON document has to be a complete object; yours requires another set of curly braces around the whole thing (as output by the above snippet).
you need to use json_encode and json_decode
refer this json php manual
I've got an associative array in php that I want to stick into a hidden form input so that I can later get the values in javascript. Because of quoting issues, I need to urlencode the json, or htmlentity it. Once I have the object in javascript, though, what's the easiest way to get it back to plain ol' json?
OR is there a better way to approach this issue? AJAX seems like overkill here -- I'd rather pre-populate the data on the page, rather than setting up multiple requests. I suppose I could write the php object to the page inside a php-generated script tag, but that seems a bit messy, and I'm not certain that [scripts] will be parsed in every possible situation where this might be used.
If you stick the data within a field you could use decodeURIComponent to decode the value. Example:
decodeURIComponent("%5b'hello'%2c%20'world'%5d"); // ['hello', 'world']
Another approach might be to embed the JSON object in a <script> element in the PHP output. You could even go as far as to make the JSON object an argument to a function that stores it away somewhere.
<script>setupData(<?= toJSON(['hello', 'world']) ?>)</script>
When the page loads the setupData would be called with the literal ['hello', 'world'].
Oh. I guess I should have tested first. I'm using dojo, and this Just Works:
PHP:
$arr = array('nyc'=>'big apple', 'boss'=>'big banana', 'lion'=>'big cat');
$json = htmlentities(json_encode($arr));
echo '<input type="hidden" id="myHidden" value="' . $json . '" />';
Javascript:
var raw = dojo.byId('myHidden').value;
var arr = dojo.fromJson(raw);
for (var i in arr) {
console.log(i + " => " + arr[i]);
}
[sheepish grin]