JQuery Slider Value with PHP Generated Input - php

Below is my code I have everything working except dynamically linking the sliders to each input field. Here is my live page
<?php $dirname="panos/" ; $images=g lob($dirname. "*.jpg");
foreach($images as $image) {
$imageName=s ubstr($image, -14); echo '
<img src="resize.php?w=450&img='.$image. '" />
<input id="'.$imageName. '-slider"/>
<br />
<div style="width:450px" id="'.$imageName. '" class="slider"></div>
'; } ?>
<script>
$(function () {
$(".slider").each(function () {
$(this).slider({
value: 0,
min: 0,
max: 360,
step: 1,
stop: function (event, ui) {
var v = $(this).attr('id')
var n = $(this).slider('value')
$("#" + v + "-slider").val(n);
window.alert(v)
},
create: function (event, ui) {
var v = $(this).attr('name')
var n = $(this).slider('value')
$("#" + v + "-slider").val('0');
}
});
})
});
</script>

FIGURED IT OUT!!! The files that was getting pulled by the PHP had ".jpg" in the middle of it! And even tho it is a valid ID name it ended up messing up the jquery portion of it! I just did this
$imageNameLong = substr($image, -14);
$imageName = substr($imageNameLong,0 , -4);
and took off that ".jpg" and now it works flawlessly!!!

Related

Plupload: run uploader.php even with no image loaded

I'm using plupload to upload images in a form. When I press submit, the uploader.php does it job by uploading the images and processing the other form data using the multipart_params og pluploader.
However, I want to submit the form as well when no image is selected. When I submit with no image selected now, uploader.php simply doesn't run.
Is there a way to run uploader.php in all cases, even with no files selected?
Thanks.
This is the simplified code I'm working on:
<textarea id="textarea_input"></textarea>
<label id="browse" href="javascript:;">
<i class="fa fa-camera"></i> Add image
<span id="filelist"></span>
</label>
<a id="start-upload" href="javascript:;"">Add</a>
<span id="console"></span>
<script type="text/javascript">
var uploader = new plupload.Uploader({
browse_button: 'browse', // this can be an id of a DOM element or the DOM element itself
url: 'uploader.php',
multi_selection: false,
resize: {
width: 1500,
height: 1500,
quality: 30
},
filters: {
mime_types : [
{ title : "Image files", extensions : "jpg,gif,png,jpeg" }
],
max_file_size: "10mb",
prevent_duplicates: true
},
multipart_params : {
"textarea_input" : "value1" //predefine textarea_input here, uploader right before uploader.start()
}
});
uploader.init();
uploader.bind('FilesAdded', function(up, files) {
while (up.files.length > 1) { //custom: limit to 1 file upload.
up.removeFile(up.files[0]);
document.getElementById('filelist').innerHTML = '';
}
var html = '';
plupload.each(files, function(file) {
html += '<br /><span id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></span>';
});
document.getElementById('filelist').innerHTML += html;
});
uploader.bind('UploadProgress', function(up, file) {
document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
});
uploader.bind('Error', function(up, err) {
document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
});
uploader.bind('UploadComplete', function(up, files) {
window.location = "mobilelogbook.php?saved=2";
});
document.getElementById('start-upload').onclick = function() {
uploader.settings.multipart_params["textarea_input"] = document.getElementById("textarea_input").value;
uploader.start();
};
</script>
And the uploader.php:
<?php
if (empty($_FILES) || $_FILES["file"]["error"]) {
$fileName = '';
} else {
$fileName = $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], "images/logbook/$fileName");
}
if (isset($_POST['textarea_input'])) {
$log = $_POST['textarea_input'];
} else {
$log = '';
}
// SQL GOES HERE: ADDS THE TEXTAREA_INPUT AND FILENAME TO A TABLE.
die('{"OK": 1}');
?>

Passing a JSON array from PHP to JQuery is not working

I am having trouble accesssing a jquery array which is getting JSON data from a PHP script. If I hard coded the array in jquery it worked fine. I checked using cosole.log. Both nproducts and products array giving the same values. Please note that nproduct has hard coded values where are product is getting from a PHP script. Can someone put my in the right direction. Thanks
here is the PHP Code
while ($row = oci_fetch_array($result,OCI_ASSOC)) {
$shop[$row['WH_DESCRIPTION']] = array(
'pic' => $row['WH_PIC'],
'price' => $row['WH_PRICE']
);
}
echo json_encode($shop);
here is the jquery. If I use nproduct then productsRendering function works fine but if I use product then it print containsValue for name and pic and undefined for price. It seems that the product array does not have any values in the productRendering function where as getJSON is returning values.
<script type="text/javascript">
var cart = (function ($) {
var productsOffset = 3, products = [],
nproducts = {
'Black T-shirt': {
pic: 'black-controller.png',
price: 15
},
'Green T-shirt': {
pic: 'green-kentucky.png',
price: 18
},
'Brown T-shirt': {
pic: 'brown-computer.png',
price: 25
}
};
$.getJSON('shop.php', function(data) {
products = data;
console.log(data); //showing values here
console.log(products); //showing values here
console.log(nproducts); //showing values here
});
function render() {
productsRendering();
};
function productsRendering() {
var catalog = $('#catalog'),
imageContainer = $('</div>'),
image, product, left = 0, top = 0, counter = 0;
console.log(products); //does not have values here
for (var name in products) {
product = products[name];
image = createProduct(name, product);
image.appendTo(catalog);
if (counter !== 0 && counter % 3 === 0) {
top += 147; // image.outerHeight() + productsOffset;
left = 0;
}
image.css({
left: left,
top: top
});
left += 127; // image.outerWidth() + productsOffset;
counter += 1;
}
$('.draggable-demo-product').jqxDragDrop({ dropTarget: $('#cart'), revert: true });
};
function createProduct(name, product) {
return $('<div class="draggable-demo-product jqx-rc-all">' +
'<div class="jqx-rc-t draggable-demo-product-header jqx-widget-header-' + theme + ' jqx-fill-state-normal-' + theme + '">' +
'<div class="draggable-demo-product-header-label"> ' + name + '</div></div>' +
'<div class="jqx-fill-state-normal-' + theme + ' draggable-demo-product-price">Price: <strong>$' + product.price + '</strong></div>' +
'<img src="images/t-shirts/' + product.pic + '" alt='
+ name + '" class="jqx-rc-b" />' +
'</div>');
};
function init() {
render();
};
return {
init: init
}
} ($));
$(document).ready(function () {
cart.init();
});
</script>
productsRendering() gets called before ajax request completes. Consider calling productsRendering() inside the ajax callback.
This is because the browser does not interpret the response body as JSON. Try setting Content-Type header in php before echoing response:
header('Content-Type', 'application/json');

jquery autocomplete with php foreach generated results

I have been trying for days to get jquery autocomplete to work the way I need it to.
so far I have this which works fine:
<script>
$(function() {
var availableTags = [<?php
$taglist = Array();
foreach ($users as $user)
if ($user->getAttribute('first_name') == ''){
$taglist[] = '"'.$user->getUserName().'"';
}else{
$taglist[] = '"'.$user->getAttribute('first_name').' '.$user->getAttribute('last_name').'"';
}
echo join(',', $taglist);
?>];
$("#searchmem").autocomplete({
source: availableTags,
minLength: 2,
select: function(event, ui) {
$("#searchmem").val(ui.item.label);
$("#submit").click();
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src='/files/avatars/1.jpg' />" + item.label + "</a>")
.appendTo(ul);
}
});
</script>
This will output the image /files/avatars/1.jpg next to the respective users username or full name.
The problem I'm having is trying to output the right users avatar. Each .jpg file corresponds with the username so I could have used $user->getUserID() in the src but this won't work because it's not inside the foreach $users as $user loop.
I have tried putting the whole autocomplete script inside the foreach which when tested did alert the right thing but autocomplete wouldn't work.
I have also tried creating two variables such as
availableTags1 = { label: .... $user->getUserName() etc... }
availableTags2 = { avatar: .... $user->getUserID() etc... }
availableTags = availableTags1 + availableTags2;
and
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src=' + item.avatar + ' />" + item.label + "</a>")
.appendTo(ul);
}
But again this didn't work. I'm completely lost! How can I get it to output the image alongside the relevant username? Help would be much appreciated.
In your case, you have to build an array like :
var availableTags = [
{label: '...', avatar: '...'},
{label: '...', avatar: '...'},
...
];
And use:
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src='" + item.avatar + "' />" + item.label + "</a>") // Note the additional double quotes
.appendTo(ul);
}
(see this example on jQuery UI for using custom data)
Then, for generating you array via PHP, you should use:
<?php
$taglist = Array();
foreach ($users as $user) {
$data = array();
if ($user->getAttribute('first_name') == ''){
$data["label"] = $user->getUserName();
} else {
$data["label"] = $user->getAttribute('first_name').' '.$user->getAttribute('last_name');
}
$data["avatar"] = $user->getUserID();
$taglist[] = $data;
}
?>
var availableTags = <?php echo json_encode($taglist); ?>;

Update hidden field - jquery

OK, going to try and explain this properly as I think thats why an answer is escaping me and some users are giving me negative replies as they think I have not tried with research to solve this problem.
I have a page where a user is presented with images within a slide viewer. Each item in the slide viewer is inside a LI element.
When a user chooses a slide, and the form is then submitted, I need the script to update a hidden field so I can take which slide they have chosen into a form. Either by updating onclick or when the form is submitted, it matters not when. The hidden field contains the URL of the image shown at that time.
So, the code I currently have is:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="/js/jquery.easing.1.3.js" type="text/javascript"></script>
<!-- this is the slideviewer code -->
<script src="/js/jquery.slideviewer.1.2.js" type="text/javascript"></script>
<!-- this is what I have been trying to update the hidden field -->
<script type="text/javascript">
$(document).ready(function(){
$( "#wl_add" ).submit( function ( event ) { /* form name and id = wl_add */
$('input[name="item_pic_url"]').val($('#mygalthree img').attr('src'));
} );
});
</script>
<!-- the div containing the slide viewer -->
<div id="mygalthree" class="svw"><ul>
<?PHP
foreach($html->find('img') as $e){ // from simple_html_dom
$image = $e->src;
echo '<li><img src="'.$image.'" width=300 alt="" /></li>';
}
// the hidden field to be updated - i am presuming needs to be after the loop which feeds the LI elements
echo '<input type="hidden" name="item_pic_url" value="'.$image.'" />';
?>
</ul></div>
Or, would it be easier to update the hidden field each time a slide is chosen? below you can see the code for the slideviewer - I would have thought I might be able to add
$('input[name="item_pic_url"]').val($('#mygalthree img').attr('src'));
when the user clicks? But I cannot find where to add this either and I have tried nearly every line! Slideviewer code:
jQuery(function(){
jQuery("div.svw").prepend("<img src='/images/spinner.gif' class='ldrgif' alt='loading...'/ >");
});
var j = 0;
var quantofamo = 0;
jQuery.fn.slideView = function(settings) {
settings = jQuery.extend({
easeFunc: "easeInOutExpo",
easeTime: 750,
uiBefore: false,
toolTip: false,
ttOpacity: 0.9
}, settings);
return this.each(function(){
var container = jQuery(this);
container.find("img.ldrgif").remove();
container.removeClass("svw").addClass("stripViewer");
var pictWidth = container.find("img").width();
var pictHeight = container.find("img").height();
var pictEls = container.find("li").size();
var stripViewerWidth = pictWidth*pictEls;
container.find("ul").css("width" , stripViewerWidth);
container.css("width" , pictWidth);
container.css("height" , pictHeight);
container.each(function(i) {
(!settings.uiBefore) ? jQuery(this).after("<div class='stripTransmitter' id='stripTransmitter" + (j) + "'><ul><\/ul><\/div>") : jQuery(this).before("<div class='stripTransmitter' id='stripTransmitter" + (j) + "'><ul><\/ul><\/div>");
jQuery(this).find("li").each(function(n) {
jQuery("div#stripTransmitter" + j + " ul").append("<li><a title='" + jQuery(this).find("img").attr("alt") + "' href='#'>"+(n+1)+"<\/a><\/li>");
});
jQuery("div#stripTransmitter" + j + " a").each(function(z) {
jQuery(this).bind("click", function(){
jQuery(this).addClass("current").parent().parent().find("a").not(jQuery(this)).removeClass("current"); // wow!
var cnt = -(pictWidth*z);
container.find("ul").animate({ left: cnt}, settings.easeTime, settings.easeFunc);
return false;
});
});
container.bind("click", function(e){
var ui = (!settings.uiBefore) ? jQuery(this).next().find("a.current") : jQuery(this).prev().find("a.current");
var bTotal = parseFloat(jQuery(this).css('borderLeftWidth').replace("px", "")) + parseFloat(jQuery(this).css('borderRightWidth').replace("px", ""));
var dOs = jQuery(this).offset();
var zeroLeft = (bTotal/2 + pictWidth) - (e.pageX - dOs.left);
if(zeroLeft >= pictWidth/2) {
var uiprev = ui.parent().prev().find("a");
(jQuery(uiprev).length != 0)? uiprev.trigger("click") : ui.parent().parent().find("a:last").trigger("click");
}
else {
var uinext = ui.parent().next().find("a");
(jQuery(uinext).length != 0)? uinext.trigger("click") : ui.parent().parent().find("a:first").trigger("click");
}
});
jQuery("div#stripTransmitter" + j).css("width" , pictWidth);
jQuery("div#stripTransmitter" + j + " a:first").addClass("current");
jQuery('body').append('<div class="tooltip" style="display:none;"><\/div>');
if(settings.toolTip){
var aref = jQuery("div#stripTransmitter" + j + " a");
aref.live('mousemove', function(e) {
var att = jQuery(this).attr('title');
posX=e.pageX+10;
posY=e.pageY+10;
jQuery('.tooltip').html(att).css({'position': 'absolute', 'top': posY+'px', 'left': posX+'px', 'display': 'block', 'opacity': settings.ttOpacity});
});
aref.live('mouseout', function() {
jQuery('.tooltip').hide();
});
}
});
j++;
});
};
I suggest the same as Josh V.K. but without that ludicrous positioning hack.
<label>
<img src="imagelocation.jpg" />
<input type="radio" name="coolName" value="image_1" style="display: none;" />
</label>
OK, this has been driving me insane, but it is now solved... In the actual slideviewer code, when a user chooses a number of an image, I added a simple onclick to write the value of the hidden field.
jQuery("div#stripTransmitter" + j + " ul").append("<li><a title='" + jQuery(this).find("img").attr("alt") + "' href='#' onClick=\"document.wl_add.item_pic_url.value='" + jQuery(this).find("img").attr("src") + "'\" >"+(n+1)+"<\/a><\/li>");
Thanks for suggestions.
What I would do, rather than updating a hidden field, is assign each image as a label for a radio button. Then when you submit the form it will submit the value of that radio button. You will need to position the radio button left:-9999 or something so that the actual button doesn't show up.
<label>
<img src="imagelocation.jpg" />
<input type="radio" name="coolName" value="image_1" style="margin-left:-99999px;>
</label>
When the click on the image, it will select that radio button and that value will be submitted with the form.

how to get result from mysql and display using jquery when radio button is clicked?

I would like to make a bus seating plan. I have seating plan chart using javascript function.I have two radio button named Bus_1 and Bus_2 queried from databases. When I clicked one of radio button, I would like to get available seats to show on the seating plan. Problem is I can't write how to carry radio value and to show database result on seating plan. Please help me.
<SCRIPT type="text/javascript">
$(function () {
var settings = { rowCssPrefix: 'row-', colCssPrefix: 'col-', seatWidth: 35, seatHeight: 35, seatCss: 'seat', selectedSeatCss: 'selectedSeat', selectingSeatCss: 'selectingSeat' };
var init = function (reservedSeat) {
var str = [], seatNo, className;
var shaSeat = [1,5,9,13,17,21,25,29,33,37,41,'#',2,6,10,14,18,22,26,30,34,38,42,'#','$','$','$','$','$','$','$','$','$','$',43,'#',3,7,11,15,19,23,27,31,35,39,44,'#',4,8,12,16,20,24,28,32,36,40,45];
var spr=0;
var spc=0;
for (i = 0; i<shaSeat.length; i++) {
if(shaSeat[i]=='#') {
spr++;
spc=0;
}
else if(shaSeat[i]=='$') {
spc++;
}
else {
seatNo = shaSeat[i];
className = settings.seatCss + ' ' + settings.rowCssPrefix + spr.toString() + ' ' + settings.colCssPrefix + spc.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) { className += ' ' + settings.selectedSeatCss; }
str.push('<li class="' + className + '"' +'style="top:' + (spr * settings.seatHeight).toString() + 'px;left:' + (spc * settings.seatWidth).toString() + 'px">' +'<a title="' + seatNo + '">' + seatNo + '</a>' +'</li>');
spc++;
}
}
$('#place').html(str.join(''));
}; //case I: Show from starting //init();
//Case II: If already booked
var bookedSeats = [2,3,4,5]; //**I don't know how to get query result in this array.This is problem for me **
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
// ---- kmh-----
var label = $('#busprice');
var sprice = label.attr('pi');
//---- kmh ----
// var sprice= $("form.ss pri");
if ($(this).hasClass(settings.selectedSeatCss)){ alert('This seat is already reserved'); }
else {
$(this).toggleClass(settings.selectingSeatCss);
//--- sha ---
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
var selSeat = document.getElementById("selectedseat");
selSeat.value = str.join(',');
//var amount = document.getElementById("price");
// amount.value = sprice*str.length;
document.getElementById('price').innerHTML = sprice*str.length;
return true;
}
});
$('#btnShow').click(function () {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.'+ settings.selectingSeatCss + ' a'), function (index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function () { // selected seat
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
alert(str.join(','));
})
});
</SCRIPT>
You can use the onclick to tell AJAX to get your information and then what to do with it using jQuery.
<input type="radio" name="radio" onclick="ajaxFunction()" />
function ajaxFunction()
{
$.ajax({
type: "POST",
url: "you_script_page.php",
data: "post_data=posted",
success: function(data) {
//YOUR JQUERY HERE
}
});
}
Data is not needed if you are not passing any variables.
I use jQuery's .load() function to grab in an external php page, with the output from the database on it.
//In your jQuery on the main page (better example below):
$('#divtoloadinto').load('ajax.php?bus=1');
// in the ajax.php page
<?php
if($_GET['bus']==1){
// query database here
$sql = "SELECT * FROM bus_seats WHERE bus = 1";
$qry = mysql_query($sql);
while ($row = mysql_fetch_assoc($qry)) {
// output the results in a div with echo
echo $row['seat_name_field'].'<br />';
// NOTE: .load() takes this HTML and loads it into the other page's div.
}
}
Then, just create a jQuery call like this for each time each radio button is clicked.
$('#radio1').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=1');
}
);
$('#radio2').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=2');
}
);

Categories