Passing a Variable from PHP to Javascript for Image file - javascript

I have a gallery of images. When a user clicks on an image, the page scrolls and displays the image along with a Title, Description, and a "Go to" button. All works great except passing a variable for the Go To button. I need to pass the user ID to the JS script. Here is the partial PHP code:
<img src=<?php echo $image_finder?>
height=<?php echo $img_height?>
width=<?php echo $img_width?>
class="superbox-img"
data-img="<?php echo $image_finder?>"
title="<?php echo $artist_name?>"
alt="<?php echo $artist_about ?>"
location="<?php echo $artist_id?>" >
The PHP code is in a foreach loop. There may be a hundred images but I need to get the ID (in the location parameter) for the selected image.
At the bottom of the PHP page, I include the JS file and the following call to the JS file and function.
var pagefunction = function() {
$('.superbox').SuperBox();
};
loadScript("js/plugin/superbox/superbox.min.js", pagefunction);
In the JS file, I need to get the location parameter and pass into the HREF. I have marked where the variable need to go about 8 lines down after the main.php?location=(variable). Any help is appreciated. Thanks, Grant
function(a) {
a.fn.SuperBox = function() {
var b = a('<div class="superbox-show"></div>'),
c = a('<img src="" class="superbox-current-img">
<div id="imgInfoBox" class="superbox-imageinfo inline-block">
<h1>Image Title</h1>
<span><p><em>http://imagelink.com/thisimage.jpg</em></p>
<p class="superbox-img-description">Image description</p>
<p><a **href="main.php?location=' + location + '**" class="btn btn-primary btn-sm">Go to Artist</a>
Delete</p></span> </div>'),
d = a('<div class="superbox-close txt-color-white"><i class="fa fa-times fa-lg"></i></div>');
b.append(c).append(d);
a(".superbox-imageinfo");
return this.each(function() {
a(".superbox-list").click(function() {
$this = a(this);
var d = $this.find(".superbox-img"),
e = d.data("img"),
f = d.attr("alt") || "No description",
g = e,
h = d.attr("title") || "No Title";
l = d.attr("location") || "No Location";
c.attr("src", e), a(".superbox-list").removeClass("active"), $this.addClass("active"), c.find("em").text(g), c.find(">:first-child").text(h), c.find(".superbox-img-description").text(f), 0 == a(".superbox-current-img").css("opacity") && a(".superbox-current-img").animate({
opacity: 1
}), a(this).next().hasClass("superbox-show") ? (a(".superbox-list").removeClass("active"), b.toggle()) : (b.insertAfter(this).css("display", "block"), $this.addClass("active")), a("html, body").animate({
scrollTop: b.position().top - d.width()
}, "medium")
}), a(".superbox").on("click", ".superbox-close", function() {
a(".superbox-list").removeClass("active"), a(".superbox-current-img").animate({
opacity: 0
}, 200, function() {
a(".superbox-show").slideUp()
})
})
})
}
}(jQuery);

SEMICOLONS!
<img src=<?php echo $image_finder; ?> height=<?php echo $img_height; ?> width=<?php echo $img_width; ?> class="superbox-img" data-img="<?php echo $image_finder; ?>" title="<?php echo $artist_name; ?>" alt="<?php echo $artist_about; ?>" location="<?php echo $artist_id; ?>" >
EDIT
QUOTES!
<img src="<?php echo $image_finder; ?>" height="<?php echo $img_height; ?>" width="<?php echo $img_width; ?>" class="superbox-img" data-img="<?php echo $image_finder; ?>" title="<?php echo $artist_name; ?>" alt="<?php echo $artist_about; ?>" location="<?php echo $artist_id; ?>" >

Solution 1
Put your javascript code in the PHP page and echo the variable value, ie:
c = a('<img src="" class="superbox-current-img">
<div id="imgInfoBox" class="superbox-imageinfo inline-block">
<h1>Image Title</h1>
<span><p><em>http://imagelink.com/thisimage.jpg</em></p>
<p class="superbox-img-description">Image description</p>
<p>Go to Artist
Delete</p></span> </div>'),
d = a('<div class="superbox-close txt-color-white"><i class="fa fa-times fa-lg"></i></div>');
Solution 2:
In you JS file do something like
var MYAPP = MYAPP || (function(){
var _vars = {};
return {
init : function(variables) {
_vars = variables;
// ... you other code
},
superBox : function() {
//.. your other code
c = a('<img src="" class="superbox-current-img">
<div id="imgInfoBox" class="superbox-imageinfo inline-block">
<h1>Image Title</h1>
<span><p><em>http://imagelink.com/thisimage.jpg</em></p>
<p class="superbox-img-description">Image description</p>
<p>Go to Artist
Delete</p></span> </div>'),
d = a('<div class="superbox-close txt-color-white"><i class="fa fa-times fa-lg"></i></div>');
//.. your other code
}
};
}());
then in your php file:
<script type="text/javascript" src="myfile.js"></script>
<script type="text/javascript">
MYAPP.init({myVariable: "<?php echo urlencode($myVariable) ?>"});
MYAPP.superBox();
</script>

Related

How to get the value of the image when clickin

How to get the value of the image for us it on $_POST
$url_f = $crawler->filter('#content .galleries_overview .item')->each(function(crawler $node, $i) {
//echo $node->html();
$image = $node->filter('img')->attr('src');
$src = $node->filter('a')->attr('href');
$href = 'https://example.com/'. $src;
?>
<input type="image" name="submit_blue" value="<?php echo $href ?>" src="<?php echo $image ?>">
<?php
});
?>
you may use onclick
<input type="image" onclick="sendme('<?php echo $href ?>')" src="<?php echo $image ?>">
and add this to your page :
<form method="post" id="myform">
<input type="hidden" name="submit_blue" id="submit_blue" value="" >
</form>
<script>
function sendme(x) {
document.getElementById("submit_blue").value = x;
document.getElementById("myform").submit();
}
</script>
that is a javascript solution i use if i do not want to use jquery or something
By the way I don't like using URL as a value

Unset a single item form a php array embedded in a html site with JS button

My question is. I want to press that remove button at the end and remove my item form the session.
how can i do this?
js:
$('.remove button') .click (function() {
removeItem(This);
});
PHP and HTML:
<?php
foreach($_SESSION["cart"] as $item) {
$data = getProducts($pdo, $item);
if ($data["ColorName"] == NULL) {
$color = "";
} else {
$color = "Color: ".$data["ColorName"]."<br>";
}
if ($data["Size"] == "") {
$size = "";
} else {
$size = "Size: ".$data["Size"]."<br>";
}
print("<div class=\"basket-product\">
<div class=\"item\">
<div class=\"product-image\">
<img src=\"http://placehold.it/120x166\" alt=\"Placholder Image 2\" class=\"product-frame\">
</div>
<div class=\"product-details\">
<h1><strong><span class=\"item-quantity\">1</span> x ".$data["StockItemName"]."</strong></h1>
<p><strong>".$color." ".$size."</strong></p>
<p>Product Code - ".$data["StockItemID"]."</p>
</div>
</div>
<div class=\"price\">".$data["RecommendedRetailPrice"]."</div>
<div class=\"quantity\">
<input type=\"number\" value=\"1\" min=\"1\" class=\"quantity-field\">
</div>
<div class=\"subtotal\">". $data["RecommendedRetailPrice"] * 1 ."</div>
<div class=\"remove\">
<button>Remove</button>
</div>
</div>");
}
I tried using Unset in allot of places, but that doesn't seem to get working :')
:)
The solution is rather easy, but requires some explanation in order to be understood.
What you need here is to:
Create a new php file, which would fetch the post data (in this case ID of an element) and then simply unset the key (sub-array), which contains the cart item you want to remove.
You can use $key_to_remove = array_search($_POST['stock_item_id'], array_column($_SESSION["cart"], 'StockItemID')); and then simply unset it unset($_SESSION["cart"][$key_to_remove]);
Assign id="remove_<?php echo $data["StockItemID"]; ?>" to the <div class="basket-product"> and data-product-id="<?php echo $data["StockItemID"]; ?>" to the button, so you can identify it for item removal via javascript/jquery and you need that value extracted later for the item you want to remove from the corresponding session array (which is, in this case, $_SESSION["cart"]).
Create a callback function for removal on('click', function(){});
Inside that function extract that value data-product-id from the button you just clicked var stock_item_id=$(this).attr('data-product-id');
Inside the same function, after step 4, create an ajax call to the file from step 1 with the post data from step 4
On successful execution of an ajax call, delete the corresponding product row you have marked with id="remove_<?php echo $data["StockItemID"]; ?>" in step 2 with the following code $("#remove_"+stock_item_id).remove();
In the end, your code would look like this
YOUR INITIAL PHP AND HTML (With small corrections)
<?php
foreach($_SESSION["cart"] as $item) {
$data = getProducts($pdo, $item);
if ($data["ColorName"] == NULL) {
$color = "";
} else {
$color = "Color: ".$data["ColorName"]."<br>";
}
if ($data["Size"] == "") {
$size = "";
} else {
$size = "Size: ".$data["Size"]."<br>";
}
?>
<div class="basket-product">
<div class="item">
<div class="product-image">
<img src="http://placehold.it/120x166" alt="Placholder Image 2" class="product-frame">
</div>
<div class="product-details">
<h1>
<strong>
<span class="item-quantity">
1
</span>
x <?php echo $data["StockItemName"]; ?>
</strong>
</h1>
<p>
<strong>
<?php echo $color." ".$size; ?>
</strong>
</p>
<p>
Product Code - <?php echo $data["StockItemID"]; ?>
</p>
</div>
</div>
<div class="price">
<?php echo $data["RecommendedRetailPrice"]; ?>
</div>
<div class="quantity">
<input type="number" value="1" min="1" class="quantity-field">
</div>
<div class="subtotal">
<?php echo $data["RecommendedRetailPrice"]; ?> * 1
</div>
<div class="remove">
<button data-product-id="<?php echo $data["StockItemID"]; ?>">
Remove
</button>
</div>
</div>
<?php
}
?>
JS
$(document).ready(function(){
$('.remove button').on('click', function() {
var stock_item_id=$(this).attr('data-product-id');
$.ajax({
url: "new_php_file_created_to_remove_item_from_session_via_ajax.php",
data:
{stock_item_id : stock_item_id}
}).done(function() {
$("#remove_"+stock_item_id).remove();
});
});
});
NEW PHP FILE (new_php_file_created_to_remove_item_from_session_via_ajax.php)
<?php
$stock_item_id = $_POST['stock_item_id'];
$key_to_remove = array_search($_POST['stock_item_id'], array_column($_SESSION["cart"], 'StockItemID'));
unset($_SESSION["cart"][$key_to_remove]);
if(isset($_SESSION["cart"][$key_to_remove])) {
return false;
}
return true;
For the sake of readability and further maintenance and possible additions, I would strongly recommend you to separate php, html and js code into separate files, but that's only a suggestion. :)

On Click not working with JS

The code shown here is meant to take me to the next part of checkout process however I encounter the error that billing is not defined? I've tried to put a function and call that function via the onclick but this has no effect.
The code that isn't working shall be the bottom section of the code which is the JS along with the button just above
Below is the where you can see the button and the onclick callout
<div class="buttons-set form-buttons btn-only" id="billing-buttons-container">
<button type="button" class="btn" onclick="billing.save()"><span><span><?php echo $this->__('Continue') ?></span></span></button>
<span id="billing-please-wait" class="please-wait" style="display:none;">
<img src="<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif') ?>" alt="" class="v-middle" /> <?php echo $this->__('Loading next step...') ?>
</span>
</div>
<p class="required"><?php echo $this->__('* Required Fields') ?></p>
<?php echo $this->getBlockHtml('formkey') ?>
</form>
The JS below is not working correctly
<script type="text/javascript">
//<![CDATA[
var billing = new Billing('co-billing-form', '<?php echo $this->getUrl('checkout/onepage/getAddress') ?>address/', '<?php echo $this->getUrl('checkout/onepage/saveBilling') ?>');
var billingForm = new VarienForm('co-billing-form');
//billingForm.setElementsRelation('billing:country_id', 'billing:region', '<?php echo $this->getUrl('directory/json/childRegion') ?>', '<?php echo $this->__('Select State/Province...') ?>');
$('billing-address-select') && billing.newAddress(!$('billing-address-select').value);
var billingRegionUpdater = new RegionUpdater('billing:country_id', 'billing:region', 'billing:region_id', <?php echo $this->helper('directory')->getRegionJson() ?>, undefined, 'billing:postcode');
if ($('onepage-guest-register-button')) {
Event.observe($('onepage-guest-register-button'), 'click', function(event) {
var billingRememberMe = $('co-billing-form').select('#remember-me-box');
if (billingRememberMe.length > 0) {
if ($('login:guest') && $('login:guest').checked) {
billingRememberMe[0].hide();
} else if ($('login:register') && ($('login:register').checked || $('login:register').type == 'hidden')) {
billingRememberMe[0].show();
}
}
});
}
//]]>
</script>
jQuery was blocking another jQuery file and therefore it wasn't working correctly as intended, but since removing one of jQuery files it now works :D

Ajax comment system into a do-while loop

I have a comment system that is working fine. But now I wanna make it work into a loop, so it needs is add an id to identify as unique every "comment box", "submit buttom", so on. Due to there are many classes involved I got lost adding the index to the js function ... and actually everything.
This is my code:
<?php
$sql = mysql_query("SELECT * FROM tblopiniones_persopoli WHERE id_post = '$id_post' AND intActivo = '1' LIMIT 0,10") or die(mysql_error());
while($affcom = mysql_fetch_assoc($sql)){
$name = $affcom['intName'];
$email = $affcom['email'];
$comment = $affcom['strComment'];
$date = $affcom['date'];
// Get gravatar Image
// https://fr.gravatar.com/site/implement/images/php/
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
?>
<div class="cmt-cnt">
<img src="<?php echo $grav_url; ?>" />
<div class="thecom">
<h5><?php echo ObtenerNombreFull_Usuario($name); ?></h5><span data-utime="1371248446" class="com-dt"></span>
<br/>
<p>
<?php echo $comment; ?>
</p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<div class="new-com-bt" id="<?php echo $m; ?>">
<span id="">Escribe un comentario ...</span>
</div>
<div class="new-com-cnt">
<a name="coment_box" id="coment_box">
<input type="hidden" id="name-com" name="name-com" value="<?php echo $_SESSION['MM_IdUser']; ?>" />
<input type="hidden" id="mail-com" name="mail-com" value="<?php echo 'xxxxxxx#gmail.com'; ?>" />
<input type="hidden" id="pic-com" name="pic-com" value="<?php echo ObtenerNombreFoto_Usuario($_SESSION['MM_IdUser']); ?>" />
<textarea class="the-new-com" placeholder="Ingresa tu comentario"></textarea>
<div class="bt-add-com">Publicar comentario</div>
<div class="bt-cancel-com">Cancelar</div>
</a>
</div>
My Js code:
<script type="text/javascript">
$(function(){
//alert(event.timeStamp);
$('.new-com-bt').click(function(event){
$(this).hide();
$('.new-com-cnt').show();
$('#coment_box').focus();
});
/* when start writing the comment activate the "add" button */
$('.the-new-com').bind('input propertychange', function() {
$(".bt-add-com").css({opacity:0.6});
var checklength = $(this).val().length;
if(checklength){ $(".bt-add-com").css({opacity:1}); }
});
/* on clic on the cancel button */
$('.bt-cancel-com').click(function(){
$('.the-new-com').val('');
$('.new-com-cnt').fadeOut('fast', function(){
$('.new-com-bt').fadeIn('fast');
});
});
// on post comment click
$('.bt-add-com').click(function(){
var theCom = $('.the-new-com');
var theName = $('#name-com');
var theMail = $('#mail-com');
var thePic = $('#pic-com');
if( !theCom.val()){
alert('¡Por favor escribe un comentario!');
}else{
$.ajax({
type: "POST",
url: "add-comment.php",
data: 'act=add-com&id_post='+<?php echo $id_post; ?>+'&name='+theName.val()+'&email='+theMail.val()+'&comment='+theCom.val()+'&pic='+thePic.val(),
success: function(html){
theCom.val('');
/*theMail.val('');
theName.val('');*/
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
}
});
});
I'll highly appreciate any help with this lack of knowledge & expertise.
Many thanks in advance.

Codeigniter 2.1, jquery - ajax(post) disallowed key characters

Jquery function (it is working):
del_selected.on('click', function(e){
box.filter(':checked').each(function(){
selektovane_slike.push($(this).val());
$(this).parent().slideUp('fast');
});
data = JSON.stringify(box.serialize(), null, 2);
console.log(data);
$.post(del_url, data, function(){
}, JSON);
e.preventDefault();
});
This function gives this result:
"slike=apples.jpg&slike=50BestBandLogos.jpg&slike=Great-Logos-200x200.jpg"
And in PHP we have this:
function ypg_delete_img_selected()
{
print_r($_POST);
}
Response which I get is:
Disallowed Key Characters.
What is the problem?
HTML:
<div class="zuta_strana_trenutne_slike">
<p>All Images</p>
<?php $imgs = explode(',', $zts['image']);
foreach($imgs as $img) : ?>
<div class="zuta_strana_izmena_slika">
<img src="<?php echo IMG ?>zute_strane/thumbs/<?php echo $img ?>" title="<?php echo $zts['name'] ?>" />
<input type="checkbox" name="slike" value="<?php echo $img ?>" />
Obriši Sliku
</div>
<?php endforeach; ?>
<a class="zute_strane_izmena_selektuj_sve">Select All</a>
Delete Selected
</div>
You need to update your allowed characters in application/config/config.php:
$config['permitted_uri_chars'] = 'a-z 0-9~%\.\:_\+-,?&=';
obviously modify that to suit your needs.
Relate an id to each image on the server and deal with ids instead of arbitrary file names. The way you are currently doing this is going to lead to a lot of headaches.

Categories

Resources