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.
Related
I have the following PHP that returns records from a my MYSQL table. These records are displayed as LINKS. See code below...
<div class="slide1" id="u1026">
<?php while ($row = mysql_fetch_array($query_rental)) {
echo "<a class='fancybox fancybox.iframe' id='rental' value={$row['layout']} href=\"brochures\items-rental.php?id={$row['client_name']}\"></a>";
}?>
</div>
What I would like, is for the HREF link to change to
\"brochures\items-rental-layout2.php?id={$row['client_name']}\
If VALUE contains the text "layout2". I know that I can change HREF using jquery code
$(document).ready(function () {
$("#event").attr("href", "http://the.new.url")
});
I'm just not sure how to do that depending if the VALUE contains text "layout2". Any help is much appreciated. Thanks
You can just do it straight in the PHP code:
while ($row = mysql_fetch_array($query_rental)) {
$layoutFlag = $row['layout'] == 'layout2' ? '-layout2' : '';
echo "<a class='fancybox fancybox.iframe' id='rental' value=\"{$row['layout']}\" href=\"brochures\items-rental{$layoutFlag}.php?id={$row['client_name']}\"></a>";
}
You could also do it with Javascript:
$(function () {
// I'm assuming you are going to turn it into a rental class, otherwise change the selector to whatever.
$("a.rental").each(function() {
var rentalItem = $(this);
if (rentalItem.attr('value') === 'layout2') {
// You can choose what to replace, as long as you know it will replace EXACTLY what you want it to. I'm just going with Regex's ^ (start-of-line) operator to make sure that what we are replacing is at the start of the line...
rentalItem.attr('href', rentalItem.attr('href').replace(/^brochures\\items\-rental/, 'brochures\\items-rental-layout2'));
});
});
As you can see, just doing it in PHP is so much easier.
Also as a side note, you are creating multiple elements with the same id. Maybe you meant class='fancybox fancybox.iframe rental'?
And as a second side note, I suggest using the data- prefix for holding custom data. In layout's case, use data-layout='layout-whatever'. You can then use .attr('data-layout') to get the layout attribute (it's easier to understand what that code is doing too!).
You can either run the IF statement on the PHP loop
while ($row = mysql_fetch_array($query_rental)) {
echo "<a class='fancybox fancybox.iframe' id='rental' value={$row['layout']} href=\"brochures\items-rental".($row['layout'] == 'layout2' ? '-layout2' : '').".php?id={$row['client_name']}\"></a>";
}
Or by jQuery
$( "a.fancybox" ).each(function( index ) {
if($(this).val() == "layout2") {
oldHref = $(this).attr('href');
newHref = oldHref.replace('items-rental.php', 'items-rental-layout2.php')
$(this).attr('href', newHref);
}
});
all your links have the same ID which can cause some issues when you wuold want to work with them with jQuery.
If you have more a tags with the fancybox class, try adding a unique class to these tags and update the each loop
how to pass a variable to jquery with php ?
i have to call the jquery from html this is what is confusing me:
jquery:
$(document).ready(function() {
$('#pre-info').click(function() {
$('#hide').slideToggle("fast");
});
});
now i want a $i after #pre-info and after #hide.
im calling the jqueryScript like this :
thank you.
Okay, here is more code :
<?php
$i =0;
//Make some querys nd stuff
foreach ($all as $one) {
//Here the event 1 is createt but the pre info gets increased with each event listet
echo "<div class='EVENT'><div id='pre-info$i'>";
// get som other tables nd stuff
echo"</div><div id='hide$i' style='display:none;'>";
//now this part is hidden until i click on the pre-info
//hidden Stuff
$i++;
}
?>
<script type="text/javascript">
$(document).ready(function() {
$('.pre-info').click(function() {
var hiddenid=$(this).data('hiddenid');
$('#'+hiddenid).slideToggle();
});
});
</script>
it does still not work, did i miss anything?
for me it looks like pre-info in this javascript needs a reference ( $i) as well ?
maybe i just dont understand the jquery completly..
Ok so you have several hidden divs and for each one you also have a listener to toggle their visibility. The original list comes from php which in turn gets the data from a query.
You could use data attributes to link pre-infos to hidden elements:
$i =0;
foreach ($all as $one) {
echo "<div class='pre-info' data-hiddenid='hide$i'>click me</div>";
echo "<div id='hide$i' style='display:none;'> hidden stuff </div>";
$i++;
}
then you just need one listener on jQuery
jQuery(document).ready(function() {
jQuery('.pre-info').click(function() {
var hiddenid=jQuery(this).data('hiddenid');
jQuery('#'+hiddenid).slideToggle();
});
});
Hope it helps (edit, I wrapped the listener in the document ready event)
By the way, it seems to me you're reinventing the wheel. You could use jQuery UI's accordions or Bootstrap collapsibles with nice, crossbrowser transitions.
If the JS is in .php file, you can just use:
$(document).ready(function() {
$('#pre-info<?php echo $x; ?>').click(function() {
$('#hide<?php echo $x; ?>').slideToggle("fast");
});
});
Your question does not contain enough information to give you more detailed answer, I'm afraid.
you could embed the php variable you require into a hidden html attribute or a data attribute
Hidden Element HTML
<input type="hidden" id="someId" name="someName" value="<?php echo $someVariable?>"/>
Javascript
var someVar = $('#someId').val()
Data HTML
<div id="someId" data-some-var="<?php echo $someVariable?>"></div>
Javascript
var someVar = $("#someId").data("some-var")
Note that if you use data you must include the keyword "data" before whatever you decide to name the attribute
I am generating divs in PHP, from an array, thus:
echo "<div id='parentdiv'>";
for($counter = 0; $counter < count($list); $counter++){
echo "<div>".$list['important_info']."</div>";
}
echo "</div>";//parentdiv
I want to add some click functionality to each div independently, i.e. the action performed on clicking depends on the div, and more importantly the index of the array, $list;
I want to give each div an id based on it's index in the PHP array.
So I could do
echo "<div id='"."divindex_".$counter."'>".$list['important_info']."</div>";
where "divindex_" is just used to prevent the id form beginning with a numeric value.
Then, I think in jQuery I can write click functions for each div.
However the problem is the $list size is variable, so I don't know how many divs there are.
So what I'm thinking is something like,
$("#parentdiv div").click(function(){
var id = split($(this).attr('id').split("_")[1];//get the php index from the id
//do something with the id, e.g. ajax or whatever
});
Is there a better way to do this? If you think what I'm doing is strange and not a very good idea, then I understand. But I don't know how to do this any other way. Any help appreciated.
Simply use:
$("#parentdiv div").click(function(){
var id = $(this).index(); //index of div, 0 based
var val = $(this).text(); //content of div, if you need it
});
No need to add unique IDs :) .
Demo:
http://jsfiddle.net/q9TaJ/
Docs:
http://api.jquery.com/index/
First, make sure to properly escape your outputs:
echo '<div id="parentdiv">';
for ($counter = 0; $counter < count($list); $counter++){
echo sprintf('<div data-id="%d">%s</div>',
$counter,
htmlspecialchars($list['important_info'])
);
}
echo '</div>';//parentdiv
I'm also using a special attribute called data-id which you can easily access in jQuery with this code:
$('#parentdiv > div').on('click', function() {
var id = $(this).data('id');
});
you can pass your variables as html attributes. Then bind the click event to a single class.
<div class="divs" data-id="myid"></div>
in jquery
$('.divs').click(function(){
console.log($(this).data('id));
});
I´m trying to build a shopping cart in jQuery and PHP but cannot read values from form list.
When trying to get value from the form that is submitted i only get values from
the first form in the list view.
Please look at behaviour here:
http://www.adlertz.se/index.php?op=prodlist&katID=9&sidemenu=menushop
Click buy on ex. the middle, you get value from first.
Please help me with this, i have benn looking for solution for three days.
Probably a simple problem but i cant find the answer anywhere :| !!!.
Many thanks in advance!
function prodlist(){
$katID = $_GET['katID'];
$sql = mysql_query("SELECT * FROM shop_prod WHERE kategoriID=$katID");
while ($rad=mysql_fetch_array($sql)) {
echo "<div class=\"shop_prod_list\">";
echo "<div class=\"shop_prod_list_tmb\"><img src=\"shop/images/prod_images_tmb/".$rad['prodID'].".png\" alt=\"\"></div>";
echo "<form id=\"addcartform\" class=\"addcartform\" method=\"post\">";
echo "<input type=\"hidden\" name=\"prodID\" id=\"prodID\" value=\"".$rad['prodID']."\" />";
echo "<input type=\"submit\" class=\"shop_prod_list_kundvagn\" value=\"\" id=\"addcart\"/>";
echo "</form>";
echo "</div>";
}
echo "<div id=\"search_results\"></div>";
}
$(document).ready(function(){
$(".addcartform").click(function(e){
e.preventDefault();
addcart();
});
});
function addcart(){
var prodID=(this).document.getElementById('prodID').value; <-(Reads value but only the first)
$.post("functions/cart.php", {prodID : prodID}, function(data){
if (data.length>0){
$("#search_results").show();
$("#search_results").html(data);
}
})
}
<?php
include "db_config.php";
include "db_connect.php";
$prodID = strip_tags(substr($_POST['prodID'],0, 100));
$prodID = mysql_escape_string($prodID);
echo $prodID ." is added.";
?>
Use class instead of id
echo "<input type=\"hidden\" name=\"prodID\" class=\"prodID\" value=\"".$rad['prodID']."\" />";
Send the element which was clicked to your function
$(".addcartform").click(function(e){
e.preventDefault();
addcart(this); //this line
});
Then use that element to find the input with your class
function addcart(element){
var prodID = $(element).find('.prodID').val(); //Get val of clicked item
$.post("functions/cart.php", {prodID : prodID}, function(data){
if (data.length>0){
$("#search_results").show();
$("#search_results").html(data);
}
})
Although i would use only one button, without a form like this.
Php:
echo "<button name='prodID' class='shop_prod_list_kundvagn addcart' data-prodid='".$rad['prodID']."' value='Add' />";
Javascript:
$(".addcart").click(function(e){
e.preventDefault();
var prodID = $(this).data('prodid');
$.post("functions/cart.php", {prodID : prodID}, function(data){
if (data.length>0){
$("#search_results").show();
$("#search_results").html(data);
}
});
});
The code you use to pick out the value is not correct.
In theory you are supposed to have unique id's - so thats your first issue to resolve.
Secondly you need to find a better way to locate the value you are interested in.
My suggestion would be to add a button within each form and call it 'submit'.
On this button you add a data attribute that contains the product id.
With an onclick handler on this button you'll be able to get the data attribute directly.
Example which is not tested:
<button data-prodid="XYZ" onlcick="handleclick()">submit</button>
Javascript:
$(this).data('prodid')
Please note that you should not have duplicate IDs on the same page.
In this case, all three of your products have the id of "prodID". So in your JavaScript, when you getElementById, you will always get the first ID with that name.
There are many solutions for this. For example, you could add the product ID to the ID of the button, like 'id="addcart_' . $rad['prodID'] . '"'
You'd then parse that ID upon form submit to determine which product was selected.
I found another solution here: http://api.jquery.com/serialize/ - to pass hidden values.
But your solution is much simpler :)
I have a bunch of image names that is being retrieved from my data base and is in a while loop. In this loop I have a small form with the image names. This form is being use for another purpose. what I want is to get the field information with the item name to a javascript.
Example :
while($row = mysql_fetch_array($query)) {
$itemname = $row['name'];
echo "< input type='hidden' name='$itemname' value='$itemname'>
<img src='source' onclick='getname()' width='100%' height='100%' />";
}
I believe the reason why every image I click on is only giving me the first information from the database is because my id is being duplicated. My question is how can I get the field information to javascript without using the getElementById?
Use the following altered PHP:
$i = 0;
while($row = mysql_fetch_array($query)) {
$itemname = $row['name'];
echo "<input type='hidden' name='".$itemname."[]' id='input$i' value='$itemname' />";
echo "<img src='source' onclick=\"getname('input$i')\" width='100%' height='100%' />";
$i++;
}
Then you can retrieve the input value in Javascript:
function getname(id) {
var theinput = $('#'+id).val(); // jQuery example
// do something
(I also changed the input name to be an array, of couse you could name it what you want, maybe $itemname$i could be an idea, it depends how and if you want to process your form, however the name should be unique or array for good practice)
Here is a working example of HTML/JS: http://jsfiddle.net/fuHSv/1/
How about using some jQuery 1.8.2 like the following:
$(document).ready(function() {
var inputs = $('input').on('click', function() {
var name = $(this).attr('name');
var val = $(this).val();
// do stuff
});
});
See api.jquery.com for more.