Passing PHP array into external Javascript function as array - php

I'm doing something which I need to pass an array from my php to a function on an external javascript. I'm currently doing some test right now which looks like this:
<input type="text" onclick="show_error_message('<?php echo $array_sample ?>')" readonly="readonly">
and the javascript function is this one:
function show_error_message(test) {
alert(test)
}
my $array_sample contains data which is array("1","2","3"); but the return alert would be Array and whenever I change the $array_sample into $array_sample[0] when passing the parameters I got a data which is 1 as alert. I wonder how can I pass the whole array on this to be fetched also by an array in javascript. Well as you can see, I intended it to be a popup message for error handling which is why I need it to be dynamic.

Use json_encode
onclick='show_error_message(<?php echo json_encode($array_sample) ?>)'
or
onclick="show_error_message(<?php echo htmlspecialchars(json_encode($array_sample)) ?>)"
Notice the lack of quotes(') around the php code, this way an array literal is passed to show_error_message and not a string.

Encode PHP array to json data using json_encode() function.
And in Javascript use JSON.parse() to parse the Json string.

The below code shows how to pass php array to javascript:
<script type="text/javascript">
function mufunc(a)
{
var temp = new Array();
temp = a.split('~');
for(i=0;i<temp.length;i++)
{
alert(temp[i]);
}
}
</script>
<?php
$a = array('a','b','c');
$b = implode("~",$a);
?>
Click Here

Related

Pass array into GET URL using jQuery

I am trying to pass an array into a GET URL BUT it is coming as add_cart?ids=1,2,3,4,5 as opposed to sending it properly.
This is my jquery code where it adds the array to the URL and directs the user to the next page:
$(document).on("click", 'button.btn_checkout', function(){
var cart = <?php echo json_encode($carts); ?>;
window.location.href = "addcart.php?cart=" + cart;
});
And then on the addcart.php page I am unable to get these values.
Ideally on this page, I want the values in the form 1,2,3,4,5
This is the code for that page:
<?php
session_start();
$cart = isset($_GET['cart']) ? $_GET['cart'] : "";
$cart = explode(",", $_GET['cart']);
for($i = 0; $i<$cart.size; $i++){
echo $cart[$i];
}
?>
Where am I going wrong?
You are using the jQuery GET request a little wrongly. You will use
window.location.href
when you are trying to change the location of your current webpage.
Try this instead:
$(document).on("click", 'button.btn_checkout', function(){
var result = <?php echo json_encode($carts); ?>;
$.get( "addcart.php", { cart: result } );
});
I'm assuming by ARRAY you mean to include the braces {}?
If so, your problem is actually the php part. json_encode is creating a proper json object. Which then is being added onto the url AS the object itself, and NOT a string. You actually want it to be a string.
this line: var cart = <?php echo json_encode($carts); ?>; is the main issue.
convert it to something like: var cart = "<?php echo json_encode($carts); ?>";
Use $.param() function to convert params to get query string.
You are directly initialising Json to param but not converting to query string.
Above function will convert Json to query string
Try to use the javascript function JSON.stringify() to convert to json.
Note: Don't sent long data over a URL. There is a limit for sending data via url and it will end up in a corrupted data if exceeded the limit. For large data, use POST method.

Accessing smarty multidimensional array values using jquery

I have an array being passed from php which looks like:
$resultsArr[123]['A']='q';
$resultsArr[123]['B']='d';
$resultsArr[113]['C']='s';
$resultsArr[113]['A']='ss';
$resultsArr[113]['B']='sd';
$resultsArr[111]['C']='sds';
$resultsArr[111]['A']='vv';
$resultsArr[111]['B']='vv';
i need to access certain values frmo this array using jquery.
i am trying to access it like
keyVal = 123; //dynamically generated
var pri = '~$results['keyVal']['B']`'
but i am getting a blank value in variable 'pri'
How can this be solved?
Could you not convert it to a JSON Array and then use it directly in Javascript, rather than picking out individual elements of the array?
<script>
var myArray = <?php echo json_encode($resultsArr); ?>;
</script>
Then use jQuery each to read the array.
This would give you greater flexibility in the long term of what was available to javascript for reading and manipulation.
EDIT
You can read a specific element like so, this will alert "vv":
<script>
var myVar = myArray[111].A;
alert(myVar);
</script>
In php use :
$ResultsArr = json_encode($resultsArr);
$this->jsonResultsArr = $ResultsArr; //its seems u r using smarty.
In javascript
jsonResultsArr = "~$jsonResultsArr`";
requireValue = jsonResultsArr[111].A;

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.

How to pass an array of strings from PHP to Javascript using $.ajax()?

I have a PHP script that retrieves names (strings) from database. I would like to pass this array to Javascript using $.ajax().
I cannot understand how should I encode the array in PHP and then decode it in Javascript.
Could someone give an example code for this ?
Thanks a lot !!
<?php // test.php
$myArray = array(1, 2, 3);
echo json_encode($myArray);
?>
HTML File:
$(function() {
$.getJSON('http://localhost/test.php', function(data) {
$(data).each(function(key, value) {
// Will alert 1, 2 and 3
alert(value);
});
});
});
u can use json_encode
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
full example you can read at :
http://www.prodevtips.com/2008/08/15/jquery-json-with-php-json_encode-and-json_decode/
or
http://www.prodevtips.com/2009/12/09/multiple-select-lists-with-jquery-and-json/
<?php
echo json_encode(array('key' => 'value', 'cool' => 'ice'));
?>
json is a javascript object. So there is no need to "decode" it. However, it looks like you are using jquery. There is a nifty function for retrieving json data:
jQuery.getJSON(url, senddata, function(returndata){alert(returndata.cool);})
or
jQuery.getJSON(url, senddata, function(returndata){mybigfunction(returndata);})
mybigfunction(data)
{
myvar = data.cool;
alert(myvar);
}
http://api.jquery.com/jQuery.getJSON/
or you could also do it with $.ajax as you mentioned:
jQuery.ajax({
url: url,
dataType: 'json',
data: senddata,
success: function(data){mybigfunction(data)}
});
mybigfunction(data)
{
myvar = data.cool;
alert(myvar);
}
http://api.jquery.com/jQuery.ajax/
The "callback" is a function that gets called and passed the json data returned from the url.
You will 'ice' baby... ermm... sorry for the corn.
The getJSON method is rather short and handy. Have a look at the links for more details.
This is Php File Code
<?php
$array = array(1, 2, 3);
echo json_encode($array);
?>
Then you can parse $array in your $.ajax() like this
success: function (data) {
var x = JSON.parse(data);
console.log(x);
}
To do this, you'll just have to echo out a script into the PHP page that contains your data, which you can then access from any other Javascript on the page, including jQuery and .ajax().
Again, if you just want to pass it via an AJAX call, just use json_encode():
<?php
echo json_encode(
array(
'groupidlist'=>$groupids,
'groupnamelist'=>$groupnames,
'serverurl'=>$serverurl,
'uid'=>$curuser->getID()
)
);
?>
And then process it with the callback functions from .ajax() or, probably better, .getJSON(), which is built for just this use.
I promise I don't just spam my blog here, but I wrote a post on passing variables between Javascript and PHP, because I did it often enough that I came up with a simple/reliable/clean and reusable way to do so. If you're regularly passing data from PHP to Javascript and don't need AJAX, I'll paste the essentials here:
At the top of each external js file, I add comments as to which PHP variables are required, so I can keep track of what I need when I include it (this is optional, of course, but nice):
/* This script depends on the following variables in phpvars:
groupidlist
groupnamelist
serverurl
uid
*/
Then, in the PHP file, I pass the needed variables with a single line of Javascript, assigning a JSON Array with all the needed values. Examples in PHP, directly from my code:
<script type="text/javascript">
var phpvars = <?php
echo json_encode(
array(
'groupidlist'=>$groupids,
'groupnamelist'=>$groupnames,
'serverurl'=>$serverurl,
'uid'=>$curuser->getID()
)
);
?>;
</script>
Once that is set up, I can then simply access whatever PHP Variables I need in the Javascript through the phpvars array. For example, if I needed to set an image source using my serverurl, I could do as follows:
imgElement.src = phpvars.serverurl + '/images/example.png';
Because it uses JSON, there is no worrying about making sure that you don't screw anything up in your Javascript by trying to insert the PHP variables. The encoding/decoding of the variables is handled on both ends by built-in JSON functions, so it is very hard to break it, and brainless to pass variables - you pass them like you would any other PHP array. In my fiddling that led to this, I had problems with both of these, and this solution takes care of them nicely.

format JSON value with a php function and print result inside a div#id

So far, I have got the following:
$.getJSON('getinfo.php', { id:id }, parseInfo);
function parseInfo(data) {
   $('div#info').fadeOut("fast", function() {
$('div#info').html(data.desc);
}
}
I am able to print the results (data.desc) inside the div#info html tag, but before I do so, I want to format data.desc with my php function. So, basically I want to do something like this,
function parseInfo(data) {
$('div#info').fadeOut("fast", function() {
<?php
$formated = some_php_function(data.desc);
?>
$('div#info').html(<?php echo $formated ?>);
}
}
You won't be able to call a PHP function in the middle of a Javascript function. You'll have to format this value before you send it through as a JSON value, or you'll have to duplicate your PHP function in Javascript and use it client-side.
Like I say, why not do that formatting function within getinfo.php?
Another option would be to write a JavaScript function instead of a PHP one to format your variable. What sort of formatting do you need to do on it?

Categories