Passing php array for use in javascript using json_encode - php

I know this has been asked plenty of times before but still I have a problem after readaing all the other posts on the subject... Somewhere between my php code -and the javascript it is sitting in- my array is going awol.
In the attached code, I have an echo for debugging of the php. When I cut out the php section from the javascript and run it separately with the echo on, it shows me that it is building my json_encoded array correctly.
In the javascript immediately after the php end I assign the php to a javascript variable, so I can use it for further processing (plotting a graph). Putting in display statements, to display the content of the result of the php call to get the array into javascript, shows the array is empty.
If I cut and paste the output of the php echo and assign this literal to the javascript chartData array then everything works fine. Why is the javascript not getting the php array content?
Here's the code snip:
<script>
...some java script stuff;
<?php
// Define the mySQL db connection
$db = new PDO('mysql:host=localhost;dbname=remets;charset=UTF-8', 'remets', 'remets', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
// Define SQL query to fetch data from mySQL
$stmt = $db->query("SELECT WeekNumber,XAxisCategory,YAxisValue FROM Metric WHERE ReportID = 'Q3' ORDER BY WeekNumber,XAxisCategory ASC");
// declarations
$amData = array();
$amArray = array();
$ctrinner = 0;
$ctrouter = -1;
$prevweek = "9999";
// Fetch data from mySQL and put it in an array in the format we need
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if ($prevweek !== $row['WeekNumber']) {
$ctrouter++;
$ctrinner = 0;
$amData[$ctrouter]["week"] = "".$row['WeekNumber']; // Prepending (or appending) the empty string makes the json encoding think the week number is a string, which is MUST have for AmCharts
}
$ctrinner++;
$amData[$ctrouter][$row['XAxisCategory']] = $row['YAxisValue'];
$prevweek = $row['WeekNumber'];
}
// Using json_encode puts the data into an array format that we can use in a javascript
$amJSONArray = json_encode($amData);
// Echo is for debugging only.
// echo $amJSONArray;
?>
var chartData = <?php echo $amJSONArray;
?>;
...more javascript stuff;
</script>
#Mahdi: The output of the print_r is: Array ( [0] => Array ( [week] => 1301 [Accepted] => 30 [Failed] => 5 [Passed] => 20 [Planned] => 5 [Skipped] => 5 [Unknown] => 26 ) [1] => Array ( [week] => 1302 [Accepted] => 25 [Failed] => 2 [Passed] => 25 [Planned] => 2 [Skipped] => 3 [Unknown] => 20 ) [2] => Array ( [week] => 1303 [Accepted] => 26 [Failed] => 26 [Passed] => 29 [Planned] => 26 [Skipped] => 26 [Unknown] => 10 ) )
#Mahdi: This is the jscript code immediately after the php (It is commented out because I tried lots of different options that were recommended in other posts in this forum and others - none of them work. I can run the php code and that works fine. If I copy the output of the echo in the php code snip I posted earlier and simply assign that to chartData (ie: chartData = "";
my chart is produced fine. The problem is not with the charting tool but somehow the array content is just not visible to the javascript which is directly below it in the .js file.
Thanks for your time up til now.
//var chartData = "<?php print($amJSONArray); ?>"; // This just returns the literal in the speech marks
//var chartData = '<?php print($amJSONArray); ?>'; // This also returns the literal in the speech marks
//var chartData = "<?php echo($amJSONArray); ?>"; // This just returns the literal in the speech marks
//var chartData = '<?php echo($amJSONArray); ?>'; // This also returns the literal in the speech marks
//var chartData = <?php echo ($amJSONArray) ?>; // This returns empty
//var chartData = <?php echo $amJSONArray ?>; // This returns empty
//var chartData = (<?php echo $amJSONArray ?>); // This returns empty
//alert(chartData); // Returns empty - just showing the contents of the array if I do the json_encode within the php part
//alert(<?php echo $amJSONArray ?>); // Returns empty - just showing the contents of the array if I do the json_encode during the array fetch
UPDATE:
I think there's something fundamentally wrong going on at my side. I used a very simple example which should write "hello world" to the screen but it returns nothing at all. If I substitute the 'write' with an 'alert' then it still shows nothing in the alert popup. Does anyone know why this would not be working? The code is:
<?php
$testvar = "Hello World";
?>
<html>
<head>
<script type="text/javascript">
function hello()
{
// create JavaScript variable, fill it with Php variable
var testvar = "<? print $testvar; ?>";
// output to screen
document.write( testvar );
}
</script>
</head>
<!-- Call JavaScript function to display variable -->
<body onload="hello()" >
</body>
</html>

If you are able to access the data as a string, you can try using the built-in JSON.parse() to convert it into usable javascript.

Related

PHP not echoing variables when print_r does

I'm not sure exactly what is going on but when a user clicks a submit button on an html page and the php script runs I get the print out from the print_r statement, but if I print a variable out with the echo statement, the value isn't returned. I've just ported the webpage and code over to a new computer, would that have something to do with it? Here is my sample php code:
<?php
print_r($_POST);
$x = $_POST[minAcres];
echo $x;
?>
Everything was working fine until I moved the code. Any thoughts why this would be happening? Here is a screenshot of the output from the print_r command.
Here is an example I regress back to the original answer of needing just quotes around minAcres. As a proof of concept i filled in post array with the beginning few values from your screen shot. minAcres = 0. Output = '0'. Maybe your output has been formatted to not show the 0 but show blank/empty
<?php
$_POST = array(
'selectCountries' => array('Columbia'),
'startDate' => '2001-01-01',
'minAcres' => 0
);
print_r($_POST);
$x = $_POST['minAcres'];
echo $x;
?>
Output:
Array
(
[selectCountries] => Array
(
[0] => Columbia
)
[startDate] => 2001-01-01
[minAcres] => 0
)
0
Simple syntax error
$x = $_POST['minAcres'];
quotes needed around array's key.

PHP loses Square Brackets From Sent jQuery form data

I'm trying to save form information using jQuery by serializing as an array and adding it into an object. jQuery sends the information fine as such:
action:save
form_data[name]:
form_data[date-requested]:09/23/2014
form_data[purchase-order-requested]:yes
form_data[vendor]:sdf
form_data[item-description[]]:
form_data[item-number[]]:
form_data[cost[]]:
form_data[quantity[]]:
But, when I try to print_r the posted data it appears as this:
Array
(
[name] =>
[date-requested] => 09/23/2014
[purchase-order-requested] => yes
[vendor] => sdf
[item-description[] =>
[item-number[] =>
[cost[] =>
[quantity[] =>
)
What can I do with inputs that have brackets in them?
[EDIT]
Here would be the jQuery:
var form_data = form.serializeArray();
var obj = {};
for(var i = 0, l = form_data.length; i < l; i++) {
console.log(form_data[i].name);
var obj2 = {
value: '"' + form_data[i].value + '"',
label: $("label[for='" + form_data[i].name + "']").html()
};
obj[form_data[i].name] = obj2;
}
And the array is simply printed with print_r
[EDIT]
If you notice the first code block, this is the POST data from jQuery. It sends the objects fine with form_data[cost[]].
But in the second code block, which is what PHP received, and immediately print_r()'ed, it loses a bracket resulting in cost[

json returning string instead of object

i have
$age = implode(',', $wage); // which is object return: [1,4],[7,11],[15,11]
$ww = json_encode($age);
and then i retrieve it here
var age = JSON.parse(<?php echo json_encode($ww); ?>);
so if i make
alert(typeof(<?php echo $age; ?>)) // object
alert(typeof(age)) //string
in my case JSON.parse retuned as string.
how can i let json return as object?
EDIT:
var age = JSON.parse(<?php echo $ww; ?>); // didnt work , its something syntax error
implode returns a string, so it is only natural that json_encode encodes it as such. It does not recognize already JSON-like data passed as a string.
If you want to get an object, you have to pass an associative array to json_encode:
$foo = array(
1 => 4,
7 => 11,
15 => 11
);
echo json_encode($foo); // {1:4,7:11,15:11}
With so little info about what $wage looks like before it's imploded, it's hard to tell exactly what you want to get. How is that structure ([1,4],[7,11],[15,11]) an object? Is the first element of each tuple a key? That's what I assumed with my example, but it might be off.
var age = [<?php echo $age; ?>];
a. You get a syntax error because you need to enclose the string within quotes, like so:
var age = JSON.parse("<?php echo $ww; ?>");
b. Moreover, you don't need JSON.parse. You can simply echo the php var after it was already json_encoded in the server side:
var age = <?php echo $ww; ?>;
JSON.parse is there to convert a JavaScript string to an object. In the case of PHP string, once it is built as JSON, echoing it in the right place is equivalent to coding it yourself.

How to pass php array of arrays to Javascript

I have an array of arrays in PHP in this layout for example,
"Key1" => { "id" => 1, "name" => "MyName", "address" => "USA" }
"Key2" => { "id" => 2, "name" => "MyName2", "address" => "Australia" }
The data in the PHP array was taken from SQL Database. Now I want to be able to use this in JavaScript.
I searched the web and people are suggesting to use JSON using this code:
var js_var = JSON.parse("<?php echo json_encode($var); ?>");
I get this error in firefox when using firebug
missing ) after argument list [Break On This Error]
var js_var = JSON.parse("{"Key1":{"id":"1","name":"MyName","address":"USA"...
Error is in right after JSON.parse("{"Key1
In google chrome, firebug does not report any errors
var js_var = JSON.parse('<?php echo json_encode($var); ?>');
Or, even better:
var js_var = <?php echo json_encode($var); ?>;
... Since JSON is, by definition, valid JavaScript syntax for object declaration.
Why go through this bizarre json_encode into a string to only JSON.parse on the client side? Useless use of encoding, really.
Try var js_var = <?php echo json_encode($var); ?>;
Your error is being cause by the fact you are using double-quotation marks (") to wrap the JSON string. Due to the fact that the JSON string also contains double-quotations the parser is unable to determine when the string starts and ends correctly.
Change the line to this:
var js_var = JSON.parse('<?php echo json_encode($var); ?>');
That been said JSON or JavaScript Object Notation is already a subset of the JavaScript programming language and therefore can already be parsed by the JavaScript engine so does not necessarily need to be parsed by JSON.parse.
var js_var = <?php echo json_encode($var); ?>;
I would however only recommend this option if you are sure about the JSON you are outputting as an incorrect parsing by JSON.parse can be handled where as incorrect JSON injected directly will cause a parser error I believe.

How to get the POST values from serializeArray in PHP?

I am trying this new method I've seen serializeArray().
//with ajax
var data = $("#form :input").serializeArray();
post_var = {'action': 'process', 'data': data };
$.ajax({.....etc
So I get these key value pairs, but how do I access them with PHP?
I thought I needed to do this, but it won't work:
// in PHP script
$data = json_decode($_POST['data'], true);
var_dump($data);// will return NULL?
Thanks, Richard
Like Gumbo suggested, you are likely not processing the return value of json_decode.
Try
$data = json_decode($_POST['data'], true);
var_dump($data);
If $data does not contain the expected data, then var_dump($_POST); to see what the Ajax call did post to your script. Might be you are trying to access the JSON from the wrong key.
EDIT
Actually, you should make sure that you are really sending JSON in the first place :)
The jQuery docs for serialize state The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. Ready to be encoded is not JSON. Apparently, there is no Object2JSON function in jQuery so either use https://github.com/douglascrockford/JSON-js/blob/master/json2.js as a 3rd party lib or use http://api.jquery.com/serialize/ instead.
The OP could have actually still used serializeArray() instead of just serialize() by making the following changes:
//JS
var data = $("#form :input").serializeArray();
data = JSON.stringify(data);
post_var = {'action': 'process', 'data': data };
$.ajax({.....etc
// PHP
$data = json_decode(stripslashes($_POST['data']),true);
print_r($data); // this will print out the post data as an associative array
its possible by using the serialize array and json_decode()
// js
var dats = JSON.stringify($(this).serializeArray());
data: { values : dats } // ajax call
//PHP
$value = (json_decode(stripslashes($_REQUEST['values']), true));
the values are received as an array
each value can be retrieved using $value[0]['value'] each html component name is given as $value[0]['name']
print_r($value) //gives the following result
Array ( [0] => Array ( [name] => name [value] => Test ) [1] => Array ( [name] => exhibitor_id [value] => 36 ) [2] => Array ( [name] => email [value] => test#gmail.com ) [3] => Array ( [name] => phone [value] => 048028 ) [4] => Array ( [name] => titles [value] => Enquiry ) [5] => Array ( [name] => text [value] => test ) )
The JSON structure returned is not a string. You must use a plugin or third-party library to "stringify" it. See this for more info:
http://www.tutorialspoint.com/jquery/ajax-serializearray.htm
I have a very similar situation to this and I believe that Ty W has the correct answer. I'll include an example of my code, just in case there are enough differences to change the result, but it seems as though you can just use the posted values as you normally would in php.
// Javascript
$('#form-name').submit(function(evt){
var data = $(this).serializeArray();
$.ajax({ ...etc...
// PHP
echo $_POST['fieldName'];
This is a really simplified example, but I think the key point is that you don't want to use the json_decode() method as it probably produces unwanted output.
the javascript doesn't change the way that the values get posted does it? Shouldn't you be able to access the values via PHP as usual through $_POST['name_of_input_goes_here']
edit: you could always dump the contents of $_POST to see what you're receiving from the javascript form submission using print_r($_POST). That would give you some idea about what you'd need to do in PHP to access the data you need.
Maybe it will help those who are looking :)
You send data like this:
$.ajax({
url: 'url_name',
data: {
form_data: $('#form').serialize(),
},
dataType: 'json',
method: 'POST'
})
console.log($('#form').serialize()) //'f_ctrType=5&f_status=2&f_createdAt=2022/02/24&f_participants=1700'
Then on the server side use parse_str( $_POST['form_data'], $res).
Then the variable $res will contain the following:
Array
(
[f_ctrType] => 5
[f_status] => 2
[f_createdAt] => '2022/02/24'
[f_participants] => 1700
)
You can use this function in php to reverse serializeArray().
<?php
function serializeToArray($data){
foreach ($data as $d) {
if( substr($d["name"], -1) == "]" ){
$d["name"] = explode("[", str_replace("]", "", $d["name"]));
switch (sizeof($d["name"])) {
case 2:
$a[$d["name"][0]][$d["name"][1]] = $d["value"];
break;
case 3:
$a[$d["name"][0]][$d["name"][1]][$d["name"][2]] = $d["value"];
break;
case 4:
$a[$d["name"][0]][$d["name"][1]][$d["name"][2]][$d["name"][3]] = $d["value"];
break;
}
}else{
$a[$d["name"]] = $d["value"];
} // if
} // foreach
return $a;
}
?>

Categories