MySQL/PHP Array to Javascript - php

So I want to store all of my MySQL results in an array I can manipulate with javascript/jQuery.
Here is my current code:
<?php
$sql = "SELECT * FROM potentials";
$result = mysql_query($sql) or die(mysql_error());
$potential = mysql_fetch_array($result);
echo json_encode($potential);
?>
And my Javascript:
<script type="text/javascript">
$(document).ready(function(){
var myArray = "<?php print(json_encode($potential)); ?>";
console.log(myArray)
)};
</script>
I keep getting "Unexpected number" or "unexpected identifier". Whats going on?

json_encode() returns an object using JSON notation. Strangely, you surrounded it with quotes. Try removing them :
<script type="text/javascript">
$(document).ready(function(){
var myArray = <?php print(json_encode($potential)); ?>;
console.log(myArray);
});
</script>
(and it's not an array, it's an object, so you might want to rename your variable ;) )

You are using json_encode() twice, however if you want to use it, you need to parse it. In jQuery this can be done via jQuery.parseJSON like this
var myArray = jQuery.parseJSON('<?php print json_encode($potential); ?>');
Also if you want all the results, you need to loop the query (e.g. with while) and then save it to an array
$array = array();
while ($row = mysql_fetch_array( mysql_query( $query ) )
{
$array[] = $row;
}

<script>
var data = '<?php echo $data; ?>';
var json = JSON.parse(data);
console.log(json[0]); //etc
</script>
Notice that var data = ... is SINGLE QUOTED, so you catch the echo from php as a String

Related

HTML, PHP, JavaScript -- How to make a button for each individual record in a database? Seems simple but doesn't work

I have an SQL database (I know for sure it includes remote access, if that's necessary to access a database through php). It definitely has at least one record in it, and I need to get each record and create a corresponding button that links to a php file, taking the first field for that record as a/n argument, variable, parameter, or whatever you call the whatever.php?variable=value.
For some reason, this code just gives me a blank page. Why?
<?php
$connection=mysqli_connect("myhost","myusername","mypassword","mydatabase");
$result=mysqli_query($connection, "SELECT * FROM myTable");
$resultArray=array();
while ($row = mysqli_fetch_array($result)) {
array_push($resultArray, $row['ID']);
}
$resultArrayImplode = implode(",", $resultArray);
?>
<script>
var resultArray = <?php echo $resultArrayImplode; ?>
arrayEntries = new Array();
arrayEntries = resultArray.split(",");
function CreateButtons(element, index, array) {
var button = document.createElement("input");
button.type = "button";
button.value = element;
button.onclick = function() {
document.location.href = "ButtonClicked.php?id=" + element;
}
document.body.appendChild(button);
}
arrayEntries.forEach(CreateButtons);
</script>
Thanks!
Your javascript assignment to resultArray is probably not syntactically correct due to quote characters, etc. Luckily, PHP's JSON functions automagically create good javascript for you.
Try this for the javascript output:
var arrayEntries = <?php echo json_encode($resultArray)?>;
Your problem is $resultArrayImplode; is a string, so
var resultArray = <?php echo $resultArrayImplode; ?>
renders as:
var resultArray = 1,2,3,4,5
Which is a syntax error.
What you can do is use JSON. JSON syntax is JavaScript syntax, so all you need to do is:
var arrayEntries = <?php echo json_encode($resultArray); ?>;
This should render as something like:
var arrayEntries = [1,2,3,4,5];
Which is perfect JavaScript syntax. Then the rest of your code should work.
I just don't see why do you need to use javascript for this, cant you just do the following :
<?PHP
foreach($resultArray as $result)
{
?>
Im a button click me</div>
<?PHP
}
?>
in my opinion, i see no real need for you to use javascript for this.

Javascript Convert PHP Json into a javascript array

In php I used json_encode(...) and then got the value in Javascript, looks as the following:
["float","float","float","float"] // PS: This is a string...
And I would like to make this into a normal javascript array, like so:
Arr[0] // Will be float
Arr[1] // Will be float
Arr[2] // Will be float
Arr[3] // Will be float
How is this possible?
It sounds like you're retrieving a JSON string in JavaScript (perhaps via AJAX?). If you need to make this into an actual array value, you'd probably want to use JSON.parse().
var retrievedJSON = '["float","float","float","float"]'; // normally from AJAX
var myArray = JSON.parse(retrievedJSON);
If you're actually writing out a value into the page, rather than using AJAX, then you should be able to simply echo the output of json_encode directly, without quoting; JSON itself is valid JavaScript.
var myArray = <?php echo json_encode($myPhpArray); ?>;
var myArray = <?= json_encode($myPhpArray); ?>;
Pretty simple. ;-)
Example:
<?php
$myPhpArray = array('foo', 'bar', 'baz');
?>
<script type="text/javascript">
var myJsArray = <?= json_encode($myPhpArray); ?>;
</script>
Should output (view-source):
<script type="javascript">
var myJsArray = ["foo","bar","baz"];
</script>
Example
I reccomend using jquery. The php file should look as such ...
//location.php
<?php
$change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
echo json_encode($change);
?>
Then the jquery script ...
<script>
$.get("location.php", function(data){
var duce = jQuery.parseJSON(data);
var art1 = duce.key1;
var art2 = duce.key2;
var art3 = duce.key3;
});
</script>

javascript/php single quote

i'm trying to this:
<?php $php_array = array ('var1' => "l'ape"); ?>
<script type="text/javascript">
var my_javascript_object = jQuery.parseJSON('<?php echo json_encode($php_array); ?>');
</script>
I got this error "Uncaught SyntaxError: Unexpected identifier".
The problem is the single quote in the value of var1 in $php_array.
This doesn't work
<?php $php_array = array ('var1' => "l\'ape"); ?>
You don't need to parse your json with JSON.parse in this case. Just use it as an object literal instead of a Javascript string:
var my_javascript_object = <?php echo json_encode($php_array); ?>;
The problem is that you try to put the JSON in a JavaScript string.
Do this instead:
var my_js_obj = <?php echo json_encode($php_array); ?>;
A JSON string is a valid JavaScript expression which you can simply put directly in your JS code.
If you really wanted to create a string containing JSON (you don't!), you'd do it like this:
var my_json_string = <?php echo json_encode(json_encode($php_array)); ?>;
var my_js_obj = $.parseJSON(my_json_string);

Passing a php array into javascript using JSON

I have a multidimensional array, here:
$noticeDate = json_encode( $noticesDates );
and I want to pass the array into javascript:
var unavailableDates[] = $noticeDate;
Both variables are in the same php file so there is little point using $.getJSON, which basically looks for the variable in an external file. However, how do I pass the object into the javascript array in the same script.
Cheers
You cant directly assign php variables to js, but you can use something like that:
<script>
var unavailableDates = jQuery.parseJSON('<?php echo json_encode($noticeDates) ?>');
</script>
use this
var array = JSON.parse("<?php echo json_encode($noticesDates) ?>");
Try this one:
$.pareseJSON()
here is example:
var json = "<?php echo json_encode($noticesDates); ?>";
jsArray = jQuery.parseJSON(json);

how to pass array string in JavaScript function from PHP end as a argument?

I am getting the error missing ) after argument list in my Firebug console.
emissing ) after argument http://a8.sphotos.ak.fbcdn.net/hphotos-ak-snc7/s720x720/393131_320846714645076_100001592501599_911297_470580896_n.jpg
My question is how to pass $char_data variable in JavaScript function as a argument
Define php variable:
<?php
$chart_data = "['NBA',1],['NFL',2],['MLB',3],['NHL',4]";
$div = "graph";
?
Call JavaScript function with define argument
<script>
dynamicChartArray('<?php echo $div;?>','<?php echo $chartdata;?>')
</script>
A function of JavaScript
<script>
function dynamicChartArray(div,chartdata){
var myData = new Array(chartdata);
var myChart = new JSChart(div, 'pie');
alert(chartdata+div);
}
<script>
Rather than creating an array out of a string in javascript, why not just just get the PHP to output it as an array to start with?
Just add an extra set of [] which javascript reads as an array.
$chart_data = "[['NBA',1],['NFL',2],['MLB',3],['NHL',4]]";
then ditch the quotes on the output (which are responsible for causing the error messages)
dynamicChartArray('<?php echo $div;?>', <?php echo $chartdata;?>);
and then myData can just equal chart data (since its already an array)
var myData = chartdata;
'<?php echo $chartdata;?>'
This is going to echo '['NBA',1],['NFL',2],['MLB',3],['NHL',4]'. Note how there are single quotes inside the single quotes.
new Array(chartdata)
This will just make an array, with one element, the string "['NBA',1],['NFL',2],['MLB',3],['NHL',4]".
Try doing dynamicChartArray('<?php echo $div;?>',[<?php echo $chartdata;?>])
This will make chartdata an array of arrays.
Instead of
$chart_data = "['NBA',1],['NFL',2],['MLB',3],['NHL',4]";
Use
$chart_data = "[\"NBA\",1],[\"NFL\",2],[\"MLB\",3],[\"NHL\",4]";
Change your call to this:
dynamicChartArray('<?php echo $div;?>',[<?php echo $chartdata;?>])
And function to this:
function dynamicChartArray(div,chartdata){
var myData = chartdata;
var myChart = new JSChart(div, 'pie');
alert(chartdata+div);
}
change this:
dynamicChartArray('<?php echo $div;?>','<?php echo $chartdata;?>')
to this:
dynamicChartArray('<?php echo $div;?>', [<?php echo $chart_data;?>]);
and see if it works
You dont need var myData = new Array(chartdata);.
chartdata is already an array.
Take a look at json_encode.
$chart_data = json_encode(array(array('NBA',1),array('NFL',2)));
which will produce a json string ready to echo into your script
string(21) "[["NBA",1],["NFL",2]]"
You should have a look at the output. I bet it is:
dynamicChartArray('graph','['NBA',1],['NFL',2],['MLB',3],['NHL',4]')
and you can already see that you have problems with the quotes.
Instead of creating a string, I suggest to create an array and use json_encode:
$chart_data = array(
array('NBA',1),
array('NFL',2),
array('MLB',3),
array('NHL',4)
);
and
dynamicChartArray('<?php echo $div;?>', <?php echo json_encode($chartdata); ?>)
JSON happens to be valid JavaScript as well and it gives you more possibilities to process the data on the server side.

Categories