I'm having trouble accessing an array created in php, to use in a javascript block.
I know about
<?php echo json_encode($myArray); ?>
but I'm not getting any results out of it.
I have a 'index.html' file where I try to access the array through javascript.
The html page exists out of a drop down menu. When the user chooses an item in that drop down menu, the chosen item is used as an argument to retrieve data from a database.
The 'ajax.js' file contains the code to execute the 'retrieve.php' file which constructs the array ('$myArray') from database content. So the array is retrieved through an ajax call.
Can I 'echo' to the javascript code from my php file:
echo 'dataArray = ' . json_encode($data_array) . ';';
and use that javascript variable?
In other words, how can I execute my javascript code using that new 'dataArray' variable?
To get the bigger picture: I'm trying to use that array for use in a 'Google Chart', for which I need to use javascript to display the chart.
I can query all data and put it in a php array, but I'm not succeeding in transfering it properly to my html page with javascript and reload the chart.
Edit: I use an ajax call to no to reload the entire page.
Instead of " echo 'dataArray = ' . json_encode($data_array) . ';'; ", you should just write this-
"echo json_encode($data_array)"
And then interpret it in the client using JSON.parse(response) where response the response you received from the server (the json)
I found that the best way to do this is like so:
Client code:
<script>
var phpdata = <?=json_encode($jsData)?>;
</script>
Server code:
$jsData = '';
$jsData->first = $first;
$jsData->second = $second_array;
Client side usage:
alert(phpdata.second[1]);
EDIT:
To get an array from php using AJAX, use jQuery http://api.jquery.com/jQuery.getJSON/
Client side:
var stored_array;
$.getJSON(url, function(data){
stored_array = data;
// run any other code you wish to run after getting the array.
});
Server side:
print(json_encode($array));
this will get a json encoded variable and store it for your use.
Yes you can use this array of php by assigning the above json_encode function
You can use it as associative array if the array is associative or object used in php and if no-associative you can use it as normal array.
Related
In the following code the value item.rmid is provided by jQuery. The value is fetched from database, displayed in item.rmid and has to be stored in Yii::app()->SESSION["rid"] but it's not working.
In view I have the following code:
$("#pct").html('');
$.each(<?php echo $ar; ?>, function (i, item) {
$("#pct").append('
<div class="title">
fss"
<?php Yii::app()->SESSION["rid"]=' + item.rmid + ' ; ?>"
<?php echo Yii::app()->SESSION["rid"];?>
</div>')
}
What am I doing wrong?
UPD
when i var_dump($ar);
following is what i get
string '[{"pimg":"12.jpg","pid":"3","createdate":"2014-01-15 12:12:47","rid":"25"},{"pimg":"WP9.JPG","pid":"1","createdate":"2014-01-15 12:14:23","rid":"26"},{"pimg":"n2.jpg","pid":"4","createdate":"2014-01-16 11:01:27","rid":"54"}]
but the am unable to assign the rid value ......... know i got it i have multiple rid and am assign it to one Yii::app()->SESSION["rid"] which cant store all value at each iteration...
how do i pass it in the querystring but the valueto be hidden
You can't update stuff on the server via javascript without AJAX.
Use ajax to send a request to the server and update the session value using
Yii::app()->session['var'] = $_POST['received_value'];
Read up about ajax here.
The main thing to note is that PHP part of the code is already finished working when your browser runs your javascript. What your code doing is just assigning the string ' + item.rmid + ' to some PHP variable. It's just a constant string which is not connected to your javascript at all. After that your browser gets something like the following javascript:
$("#pct").html('');
$.each(some_array_from_php, function (i, item) {
$("#pct").append('
<div class="title">
fss""
+ item.rmid +
</div>')
}
Notice how it gets "preprocessed" by PHP. It's not even good javascript really, because you can't use multiline string literals in javascript.
What you can do is to push some value from javascript to your server. So you need to feed javascript code to your browser first, get your value available in javascript and then somehow make another HTTP request passing the value as a GET parameter or something. There is a technology for this purpose, it's called AJAX. Check this out.
But from your code example it looks like you already have all the values on the server (in $ar variable, in JSON format), so you can just assign session variable on PHP and use javascript only for client-side visualization.
First you need to decode JSON:
$decoded = json_decode($ar);
Now $decoded is just an array of PHP objects, so you can do something like:
Yii::app()->session["rid"] = $decoded[0]->rid;
Above we are storing the "rid" of the first object to session. If you want to store all of them just loop through $encoded while pushing values to session like this:
foreach ($decoded as $obj) {
Yii::app()->session["rids"][] = $obj->rid;
}
I have a question about using data pulled from the database in javascript.
In my controller I have this:
$this->view->projects = $projectsarray;
I send the array to my view. There I will loop through my array and show the titles. Now I need to get that array in javascript because I want to create a highchart with the data...
Does anyone knows how I could do this easily?
EDIT:
I now have this in my controller: (overviewcontroller)
public function getprojectdataAction($id){
}
In my javascript file:
var id = 1;
$.post('/overview/getprojectdata/',{id:id},function(data){
alert("test");
});
But I get the error that the resource can't be found:
POST http://www.namesite.com/overview/getprojectdata/ 404 (Not Found)
What am I doing wrong?
I assume $this->view->projects is array or object
in your view file
<script>
var projects = <?php echo json_encode($this->projects);?>;
console.log(projects);
</script>
then watch your firebug ...
you can do this by converting array to JSON you can send a ajax request to same controller
and return echo json_encode($array); then you can use directly with responce by decoding it...
$.post('controller/action',{id:id},function(data){
var arrayJson=JSON.parse(data);
});
you can use arrayJson as data array...
you can use json_encode in the php part of the code to generate a javascript object out of your array. For example:
$php = array("myAttrib" => "hallo");
echo json_encode($php);
and in javascript you can use
alert (output.myAttrib);
, where output refers to echo json_encode(php). This code would open a box showing "hallo". Your question seems to be quite similar to how to use json_encode. For creating of a highchart also this post Highcharts data series issue with ajax/json and PHP could be of interest for you.
The code looks like this:
PHP file
<?php
...
$arrayName = ['ArrayValue_0', ..., 'ArrayValue_n'];
...
php?>
JavaScript
$('.elementClass').each(function(index, id) {
$(id).html('<?php echo $arrayName[index - 1]?>');
});
But you can't just insert a JavaScript variable like that into php tags so index is never received.
I know this can be done via AJAX but is there any other way? Thanks in advance.
Additional info:
I've been told to do this in PHP so there's no posibility of switching the array to a JS file.
You can define arrayName variable in JS and initialize it with the value from the server:
var arrayName = <?php echo json_encode($arrayName); ?>;
$(".elementClass").each(function(index, id) {
$(id).html(arrayName[index-1]);
});
What you're trying to do will not work. For example this:
$(id).html('<?php echo $arrayName[index - 1]?>');
The above will never, ever work, because PHP is run on a server, not on your user's browser.
What you need to do is send the variable somehow to the server. You have a plethora of options:
Use a form and read a $_POST variable
Append it to a URL and read a $_GET variable
Use AJAX and asynchronously send that variable to the server
Return the whole array from PHP to your Javascript code
etc. etc.
Remember, PHP runs on the server, which renders the page, which then in turn is read by your browser where you run Javascript. You can't paste PHP code into the page and expect it to be parsed by PHP!
You need to get back to the server if you wish to get info from it (PhP runs on the server), so either you create a javascript variable on-the-fly when loading the page with the complete content of your PhP array , either you use ajax to get back to the server without refreshing the whole page.
I used ajax to call a php to get me some values stored in my DB.
I then echo these values in my php so that i can use the responseText property to get these retrieved values (which i want to store in a JS array) for further referral.
Here's where i get stuck. I do manage to do this when I have to retrieve just 1 row from the DB (I did this by separating the fields using a ',' and subsequently using the split() function in JS to parse the string). However when my DB returns more than 1 row then I reach a deadend as this method of mine doesn't seem to work. Kindly advice the easiest way to overcome this hurdle.
use
var jsArray = {};
$.each(response, function(i, item) {
jsArray[i] = item;
});
the above JQuery loop is equivalent to PHP loop:
foreach($response as $i => $item) {
$jsArray[$i] = $item;
}
You can convert the PHP array of multiple DB rows to json using json_encode on server side and parse JSON on the client side using javascript reading help from here. A more code oriented answer needs some code in question to work with.
This is a part of the code in a 'process.php' file:
echo "<script type='text/javascript'> percYes = ".$yes."</script>"
echo "<script type='text/javascript'> percNo = ".$no."</script>"
This 'process.php' file runs in the background (using jQuery/ajax) when the user clicks a butto. The 'echoed' html above replaces the contents of a div. So essentially what I'm trying to do is update some Javascript variables using a background php call, the above solution does not seem to work though, i.e. the script is not being ran once it is placed in the div.
A bonus problem involves using these updated Javascript variables to update a graph. I have a workng javascript graphing function, but the problem is getting the new graph to replace the old one (or just update it, if that's possible).
Thanks.
If all you are trying to do is update some JS vars, you may be better off having your process.php file returning a json string:
$array = ('percYes' => $yes, 'percNo' => $no);
echo json_encode($array);
This will give you a json string that can be evaluated and used in a callback for your JS ajax call.
So if you have a var 'percYes' and 'percNo' in an accessible scope, your callback could look something like this:
function(jsonstr) {
obj = eval(jsonstr);
percYes = obj.percYes;
percNo = obj.percNo;
}
I hope this helps.