I am using $_SESSION to pass back a value in the event of page redirect.
As jquery cannot access $_SESSION I decided to use PHP to output the value to a hidden div and remove that div once the value had been picked up. I expect that there is a neater way to do this but I don't know how else to expose the $_SESSION variable to jquery.
<?php
$pass_Back = $session->get_Pass_Back();
$session->clear_Pass_Back();
?>
<?php
if (count($pass_Back) != 0){
echo "<input class=\"field_Input_Left\" id=\"schedule_Description\" type=\"text\" name=\"schedule_Description\" value=\"" . array_shift($pass_Back) . "\"/><br />";
echo "<div id=\"pass_Back\" style=\"visibilty: hidden;\" ></div>";
} else {
echo "<input class=\"field_Input_Left\" id=\"schedule_Description\" type=\"text\" name=\"schedule_Description\"/><br />";
}
?>
Once this was done I needed a method to let jquery know if and when this new element was added to the DOM. Hence I used the plugin livequery to match when the element added. This it does which is great.
But when I try to access the value in the div it states that it is undefined.
$("#pass_Back").livequery(function(){
if ($("#class_Name").val() != 0){
var class_Name = $("#class_Name").val();
get_Schedule_Data(class_Name);
} else {
var class_Name = "ALL";
get_Schedule_Data(class_Name);
}
$value = $(this).attr("value");
auto_Fill_Schedule($("#pass_Back").attr("value"));
// destroy pass back
$("#pass_Back").remove();
});
When reviewed in firebug I note that at the point that livequery finds the added element no html is displayed. The DOM is ready otherwise the livequery couldn't have functioned but is this why no value is found?
Any guideance gratefully received.
Don't use this:
$value = $(this).attr("value");
Do the following to get a value (for inputs in most of cases):
(assuming $(this)
is your input)
$value = $(this).val();
For div
cases, there is no value
, but you can get the html
or text
from inside as the value:
(assuming $(this)
is your div)
$value = $(this).html();
//or:
$value = $(this).text();
Just to know...
You can mix PHP with jQuery but take a look at my answer from this post for better understanding:
Is echoing Javascript code condtionally based on server-side logic considered harmful?
As long you're not outputting the entire $_SESSION array, or anything of importance, you're going to be ok:
<?php
$pass_Back = $session->get_Pass_Back();
$session->clear_Pass_Back();
if (count($pass_Back) != 0){
echo '<div id="passBack" type="text" value="'.implode(",", array_shift($pass_Back)).'" />';
}
?>
JS
$(function() {
if ($("#passBack").length) {
//element exists in DOM, get the value
var passBack_data = this.value;
//do something with the value
}
});
Just output the element and make sure it's a string, not an array ( I used implode()
), and on pageload see if it exists (has length), and get the value.