How can assign javascript array to php array [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
javascript array converted to a php array?
I have an array in javascript, Now i need to assign javascript array to php array
i am beginner to scripting language,
Can anyone please help me
Thanks in advance.
<script type = text/javascript >
var jsArray = [];
var jsDescArray = [];
for (var i = 0; i <= <?php echo $t_num ?>; i++) {
jsArray.push( "<?php echo $url ?>="+thread[i].id );
jsDescArray.push( thread[i].title );
}
<?php
$str=json_decode('jsArray');
$str1[] = json_decode( 'jsDescArray', true );
?>
</script>

First off, Javascript is evaluated on the client-side, long after the PHP code has been scanned and dealt with on the server-side. Thus, this type of code simply cannot work.
Secondly, there's really no reason for this. Because you are filling an array in Javascript prior to assignment, you should really just pass the variables ($url) directly into $str and $str1[]. If this is something that must be dealt with on the client-side, call and retrieve data from a .php file with AJAX to transfer your Javascript arrays over.
Reference: https://developer.mozilla.org/en-US/docs/AJAX

PHP is run on the server, and the result is sent to the browser. Only then can the JavaScript be run.
To send stuff from JavaScript back to the server, you need to use AJAX or similar. You might want to reconsider your approach to problem-solving, but it really depends on the context of what you are trying to do here.

You could use JSON.stringify(array) to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']); in your PHP script to retrieve it.
see url
Pass Javascript Array -> PHP

Related

How to format js object to php array?

So I found some answers on how to do this, but none of them actually worked, i.e. json_decode(). This is what I did:
I created js object/array
Then I passed it to php file via Ext.Ajax.Request as JSON.stringify(js object)
Now in my php I see the result of that string as follows: ["James;","George;"]
I want to get it as an php array like (James, George). Any easy way to do this or I have to remove unnecessary parts manually?
OK, I was looking at this problem for a while and finally got the answer.
Inside php, I needed to add json_decode(stripslashes($scenarios)), where $scenarios = ["James;","George;"].
Code: ($scenarios is sent from js file via Ajax using JSON.stringify(js object))
<?php
$scenarios = empty($_GET['scenarios']) ? false : $_GET['scenarios'];
// more code for validation
$arr = json_decode(stripslashes($scenarios));
?>
Now $arr will become regular php array.
Use html_entity_decode function

echo values of an array into jQuery

So I am using FLOT to generate some bar graphs and it uses some javascript arrays to allow for the data. I have a query that spits out the correct labels and values as so:
while ($row = mysql_fetch_array($chart_stats)){
printf("Race is: %s Percentage: %s", $row['Race'],$row['Percentage'] ."<br/>");
}
My question is can I get the values of my array from php into the array of Javascript (if that makes sense)
var d1 =[0, 72]; //instead of static value maybe var d1 = [0,<?printf($row['Percentage'])?>];
var d2 =[1,3];
var d3 = [2,40];
Thanks in advance!
Yes, you can echo stuff from PHP wherever you like. When putting it into a block of JavaScript, though, you have to be careful that:
The resulting output is ALWAYS valid code
There is no way for user-generated input to be placed into code and run
The second one is simple: never put anything you got from $_POST into a <script> tag.
As for the first, json_encode is a big help. With it, you can output almost any kind of PHP variable as a valid JavaScript one.

What's IE6/7 safe way to pass json_encoded data from PHP into jQuery/Javascript?

I have several situations where I need to pass multi-dimensional PHP arrays into Javascript/jQuery. The PHP function json_encode() seems to do this rather well. I've seen some examples that use $.parseJSON, but I'm not sure if this is for IE6 compatibility or some other issue. Can anyone elaborate if this is the correct format to use in JavaScript. Assume this is javascript/jQuery as part of a PHP view.
var sections = <?php echo json_encode($sections); ?>;
Or, perhaps this would be better?
var sections = <?php if (!empty($sections)) { echo json_encode($sections); } else { echo "new Array()"; } ?>;
Or, do I need $.parseJSON? It seems to throw an error.
var sections = $.parseJSON(<?php echo json_encode($sections); ?>);
Does anyone know of any IE6 issues I should be aware of? If I should use parseJSON(), is it used with single or double quotes?
Thanks in advance,
Jeff Walters
I don't know anything about IE, but as long as you aren't dealing with JSON strings in JavaScript you will not need any parseJSON function. Just putting them out into the script text should be fine.

JSON concept with javascript & PHP

I need someone to shed some light on this subject.
When a person do an AJAX call, that call a php script which echo out json_encode stuff, so that the javascript can mess around with it. Note: Assuming we set the header to json in the php script.
The data that the javascript receive from the php script, do we have to parse it using eval or json's library? Edit: Is it because it treats the data recieved from the php file as text and not as javascript?
Can we use the javascript dot-notation on the data that the php script returned? Or does this data have to some how be converted to a javascript object before we can use dot-notation?
Thank you in advance.
JSON is merely a string, which happens to conform to Javascript's syntax for objects (hence the abbreviation: JavaScript Object Notation.)
To convert it to a Javascript object, you can use the eval function, but for greater security, it's recommended to use the JSON object included in modern browsers, or a function provided by your Javascript library of choice:
var json = '{"thing":1, "thang":"two"}';
var obj1 = eval('('+json+')'); // easier, less secure
var obj2 = JSON.parse(json); // secure, but doesn't work everywhere
var obj3 = jQuery.parseJSON(json); // secure, works everywhere
Many libraries will also handle the conversion for you as part of the Ajax request. Here's how jQuery does it:
jQuery.get('http://domain.com/path/to/request', function(obj)
{
// string is automatically converted to an object,
// usable as array or with dot notation
alert(obj.thing);
alert(obj['thang']);
},
'json'); // indicates that we are requesting json and not html
You can always use a library like jQuery, Mootools, Prototype, etc. for the decoding JSON text to Javascript variables..
JSON is something like serialize from PHP :) It's a way to transform string to object and back :)

What's the best way to pass a PHP variable to Javascript? [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I currently echo certain variables in hidden input fields and read them out with Javascript whenever I need them.
Me and a colleague are now thinking of generating an extra Javascript file with PHP which only contains all variables for Javascript. This way the variables already exist and there is no extra code in the HTML.
What are good ways to pass variables from PHP to Javascript? And how does our solution sound?
General Data Passing
A commonly used exchange format for JavaScript is JSON, using json_encode. A PHP file like this:
<?php
$data = array("test" => "var", "intvalue" => 1);
echo json_encode($data);
?>
then returns a JavaScript object literal like this:
{
"test" : "var",
"intvalue" : 1
}
You can directly echo it into a JavaScript variable on your page, e.g.:
var data = <?php echo json_encode($data)?>;
...or request it via Ajax (e.g. using jQuery's getJSON).
Outputting to attributes on tags
If you just need to output a string to an attribute on a tag, use htmlspecialchars. Assuming a variable:
<?php
$nifty = "I'm the nifty attribute value with both \"double\" and 'single' quotes in it.";
?>
...you can output it like this:
<div data-nifty-attr="<?php echo htmlspecialchars($nifty)?>">...</div>
...or if you use short tags:
<div data-nifty-attr="<?= htmlspecialchars($nifty)?>">...</div>
<?php
$my_php_var = array(..... big, complex structure.....);
?>
<script type="text/javascript">
my_js_var = <?=json_encode ($my_php_var)?>;
</script>
I use to echo them all together at the head of the HTML. Seems clean enough for my needs :)
There are 3 ways you could do it:
Echo them directly into the javascript source:
<?echo "var user = '$user';";?>. Works, but it's messy.
Pass them in via an ajax request. This is the closest you can come to native variable passing, but the downside is it takes an extra HTTP request.
What you're doing, which is passing them by generating hidden form fields and then reading them.

Categories