March 19, 2012

how to pass array string in javascript function from php end as a argument

Question by Samad

Hey Guys i have a little issue of JavaScript and i don’t know how to solve this Query that why i put this Question in stackoverflow also helps are definitely appreciated

I am getting the error missing ) after argument list in my Firebug console.

emissing ) after argument

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 javascrpit

<script>
function dynamicChartArray(div,chartdata){
var myData = new Array(chartdata);
var myChart = new JSChart(div, 'pie');
alert(chartdata+div);
}
<script>

Answer by Carl

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;

Answer by Starx

You dont need var myData = new Array(chartdata);.

chartdata is already an array.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!