Can't assign jquery value to session variable in Yii - php

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;
}

Related

Access a PHP array element by using a JavaScript variable as index

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.

AJAX to JS variable exchange

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.

Access php array variable (from ajax call) in javascript

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.

Update JavaScript variables in background using PHP + jQuery

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.

jQuery / PHP mix up

I have the following jQuery function in my PHP:
echo '
function myFunction() {
return $.ajax({
type: "POST",
url: "mypage.php",
data: "name=John&location=Boston"
});
}
$.when(myFunction()).then(function(data) {
// handle data return
someOtherFunction(data);
// need to set "data" var into PHP SESSION
}, function(error) {
// handle ajax error.
});
';
After my AJAX does the majic it returns a value (data), which I pass into another function. In addition I need to be able to set that value into a PHP session:
$_SESSION['project'][data] = data;
How do I do that? The switching between PHP and JS confuses me for some reason...
That's impossible since the JS is now on the client side. You can't set PHP variables directly.
What you could do is set a cookie in JS using document.cookie, and then on the next page request PHP can get at it via $_COOKIE.
You could also just set the $_SESSION variable inside mypage.php - that may be significantly easier, if they both share the same session.
It's confusing because you're mixing the two, try to keep a distinct separation in your code. Instead of echoing your jQuery script, just close the php tag, that would also make syntax highlighting work.
As for setting session variables, you need to do it on the server side in your mypage.php, before writing the data to the output. That will happen before passing the data to the client side jQuery script for processing.
First of all you must be aware the javascript is a clientside language and PHP is serverside. Everything PHP does, it does when the page loaded and it stops after the page is loaded. Javascript takes over then.
What you could do is create mypage in a way that it also creates $_SESSION['project']['data'] as an associative array that you can use with PHP. What you're not trying to do is setting a javascript array into a PHP variable. Not that this is wrong by default, but since you're trying to SET the data using PHP my guess is you will also GET the data using PHP, thus a javascript array in that session would be useless.
So in mypage.php you've probably have something like:
echo json_encode($result);
Where $result is the array of data returned by the script. You could simply add one line above saying:
$_SESSION['project']['data'] = $result;
and have the data stored in the session to use on other pages.

Categories