How to create jQuery if statements from php array? - php

I have array with both image colour and image id values.
I can echo this info, but I don't know how to get this into js file.
My js file is like this:
$(document).ready(function(){
var colour = false;
$('.options').click(function(){
colour = $(this).val();
console.log(colour);
if(colour == 'White'){
var imageid = 758;
}
else if(colour == 'Black') {
var imageid = 752;
}
else if(colour == 'Light Oak') {
var imageid = 755;
}
else if(colour == 'Rosewood') {
var imageid = 757;
}
else if(colour == 'Green') {
var imageid = 754;
}
else if(colour == 'Red') {
var imageid = 756;
}
else if(colour == 'Blue') {
var imageid = 753;
}
else {
var imageid = colour;
}
$('.options-input').val(imageid);
console.log(this);
$.post("index.php", { image_id: imageid }, function(results) {
$('body').html(results);
console.log(results);
});
console.log(url);
});
});
I am doing this manually at the moment and on click I can post imaged to my index.php
$_POST['image_id'];
Works from there.
Problem is that I want to create js statement dynamically depending on what values new array will have.

You can mix jQuery and php as suggested, but I prefer to avoid doing that. Instead, you can add some element to the DOM (or even an attribute of some other element) that has this data and fetch it later:
<?php echo '<span id="colour" hidden="hidden">Light Oak</span>'; ?>
if (colour == $("#colour").text()) {
// ...
}

Please do not use so many if statements! You could use the following for example:
// JavaScript / jQuery
var imageid,
colorObj = {
"White": 758,
"Black": 752,
"Light Oak": 755
};
if (colorObj[colour] !== undefined) {
imageid = colorObj[colour];
}
That easy! With PHP you could create your script like:
<?php
echo '<script type="text/javascript">var imageid,colorObj={';
$count = count($image);
for ($i = 1; $i <= $count; ++$i) {
echo '"' . $colour . '":' . $image[$i];
if ($i < $count) {
echo ',';
}
}
echo '};if(colorObj[colour]!==undefined){imageid=colorObj[colour]}</script>';

After you’ve changed your question I’d like to answer again. It seems like you want to deliver an image according to the color a user has selected from a element within the page. You haven’t posted your PHP script, but let me tell you that what you’re doing right now would be way better to be done via PHP.
$(document).ready(function () {
$('.options').click(function () {
var color = $(this).val();
if (color !== undefined && color !== null && color !== '') {
$.post('index.php', {color: color}, function (response) {
$('body').html(response);
});
}
});
});
And in your PHP file do the following:
<?php
if (isset($_POST['color']) && !empty($_POST['color'])) {
$colors = array(
'White' => 1234,
'Black' => 4321,
);
if (array_key_exists($_POST['color'], $colors)) {
echo $colors[$_POST['color']];
}
}

ugly method
<script>
<?php
foreach ($images as $index => $imageid) {
if ($index > 0) echo "else ";
echo "if (colour == '$colour') {\n";
echo " var imageid = $imageid;\n";
echo "}\n";
}
?>
</script>
less ugly method
<?php
switch($color) {
case 'White':
$imageid = 758;
break;
case 'Black':
$imageid = 752;
break;
case 'Light Oak':
$imageid = 755;
break;
}
echo "<script>var imageid = $imageid;</script>";
?>

Related

How to store post id in local storage from Single.php file

The following code in Single.php file is not working as expected. $post->ID and is_user_logged_in() are getting null values. If all works fine i can have the post id as array in local storage.
<script>
window.onload = function() {
var logged_in='<?php echo is_user_logged_in() ?>';
if (logged_in==false || logged_in==0) {
var myArray = JSON.parse(localStorage.getItem('articles') )|| [];
var article_postid='<?php echo $post->ID ?>';
//check already read? if not push into array
index = is_exist.call(myArray, article_postid);
if(!index){
myArray.push(article_postid);
localStorage.setItem('articles', JSON.stringify(myArray));
}
}
}
var is_exist = function(article_postid) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = article_postid !== article_postid;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(article_postid) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === article_postid) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, article_postid) > -1;
};
</script>
Please try this code.
Add this code to your activated theme's functions.php file and check.
function add_js_code_to_footer(){
if( is_singular( 'post' ) ){
global $post;
?>
<script>
window.onload = function() {
var logged_in='<?php echo is_user_logged_in() ?>';
if (logged_in==false || logged_in==0) {
var myArray = JSON.parse(localStorage.getItem('articles') )|| [];
var article_postid='<?php echo $post->ID ?>';
//check already read? if not push into array
index = is_exist.call(myArray, article_postid);
if(!index){
myArray.push(article_postid);
localStorage.setItem('articles', JSON.stringify(myArray));
}
}
}
var is_exist = function(article_postid) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = article_postid !== article_postid;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(article_postid) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === article_postid) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, article_postid) > -1;
};
</script>
<?php
}
}
add_action("wp_footer","add_js_code_to_footer");

YUI-2 Datatable : Dynamic column definition with Server side AJAX pagination sorting

I am using the below code to create a YUI datatable with dynamic data(columns). But am facing a issue in server side pagination. As of now it is working fine with client side pagination, but I need server side pagination, so that my page loading time will get reduced. Can you help me on this to fix the issue. Since I'm struggling in this area for past 2 days.Server side pagination with AJAX to render the data is my expectation.
Here is the code I Used
DataProvider.prototype = {
url:null,
data:null,
ds:null,
getData:function() {return this.data},
initialize:function(){
var str = generateRequest();
var newUrl = this.url+str;
YAHOO.util.Connect.asyncRequest('GET', newUrl, this);
},
success:function(response){
var responseVal = YAHOO.lang.JSON.parse(response.responseText);
var columnList = responseVal.columnList;
var sortedBy = responseVal.sortedBy;
this.data = responseVal.results;
if(this.data == '') {
$('#dynamicdata').html('<font style="color:red;"> No Data Found!</font>');
} else {
this.ds = new YAHOO.util.FunctionDataSource(function(){return this.dataProvider.getData()});
this.ds.responseSchema = {
resultsList:"results",
fields:columnList,
// Access to values in the server response
metaFields: {
totalRecords: "totalRecords",
startIndex: "startIndex"
}
}
this.ds.dataProvider = this;
// DataTable configuration
var myConfigs = {
paginator: new YAHOO.widget.Paginator({ rowsPerPage:20 }), // Enables pagination
width:"80%", height:"auto"
};
// FORMATTING CELL COLOUR BASED ON THEIR VALUES
var myCustomFormatter = function(elLiner, oRecord, oColumn, oData) {
var columnKey = oColumn.getKey();
var frmCurrentPeroid = $('#from').val();
//var frmCurrentPeroid = '2013-03-13';
var defaultLabels = ['Product type','Total 1','Total 2','Change'];
if (isDate(columnKey) && $.inArray(columnKey, defaultLabels) === -1) {
if(columnKey < frmCurrentPeroid) {
YAHOO.util.Dom.addClass(elLiner.parentNode,'orange');
elLiner.innerHTML = oData;
//alert('blue');
} else {
YAHOO.util.Dom.addClass(elLiner.parentNode,'blue');
elLiner.innerHTML = oData;
}
} else {
if(columnKey == 'Total 1') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'orange');
elLiner.innerHTML = oData;
//alert('blue');
}
else if(columnKey == 'Total 2') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'blue');
elLiner.innerHTML = oData;
//alert('blue');
}
else if(columnKey == 'Change') {
split_data = oData.toString().split('_');
var fieldData = null;
var fieldFormatter = null;
fieldData = split_data[0];
fieldFormatter = split_data[1];
if(fieldFormatter == 'green') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'green');
elLiner.innerHTML = fieldData;
}
if(fieldFormatter == 'red') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'red');
elLiner.innerHTML = fieldData;
}
}
else if(columnKey == 'Product Name') {
var filterStr = oData.substring(0,30);
elLiner.innerHTML = ''+filterStr+'';
//alert('blue');
}
else {
elLiner.innerHTML = oData;
}
}
};
// Add the custom formatter to the shortcuts
YAHOO.widget.DataTable.Formatter.myCustom = myCustomFormatter;
//YAHOO.widget.DataTable.formatLink = formatLink;
/* make call to initialize your table using the data set */
var myDataTable = new YAHOO.widget.DataTable("dynamicdata", columnList, this.ds, myConfigs);
}
}
}
Followed the code posted in this page
Click here
Thanks in Advance,
Raja
I haven't been doing YUI2 for quite some time so I am no longer able to help you directly. Perhaps this example can help: http://www.satyam.com.ar/yui/#ServerDriven . I do remember that there were big changes in 2.6 and this examples are marked 2.4, perhaps they no longer work.

Passing js variables to php using jquery

I'm trying to do a realllly simple post of a javascript variable to a php file.
Jquery bit in keyinput.php:
<script type="text/javascript">
var imgArray = [<?php echo implode(',', getImages($cat, $site)) ?>];
$(document).ready(function() {
var img = document.getElementById("showimg");
img.src = imgArray[<?php echo $imgid ?>];
var imgIndex = <?php echo $imgid ?>;
$(document).keydown(function (e) {
var key = e.which;
int rightarrow = 39;
int leftarrow = 37;
int random = 82;
if (key != rightarrow && key != leftarrow && key != random) {
return;
}
else {
//next image: right arrow
if (key == rightarrow)
{
imgIndex++;
if (imgIndex > imgArray.length-1)
{
imgIndex = 0;
}
img.src = imgArray[imgIndex];
}
//last image: left arrow
if (key == leftarrow)
{
if (imgIndex == 0)
{
imgIndex = imgArray.length;
}
img.src = imgArray[--imgIndex];
}
//random: r
if (key == random)
{
imgIndex = Math.floor((Math.random()*(imgArray.length-1))+1);
img.src = imgArray[imgIndex];
}
}
$.post('./templates/viewcomic.php', {variable: imgIndex});
});
});
</script>
<?php
function getImages($catParam, $siteParam) {
include './scripts/dbconnect.php';
if ($siteParam == 'artwork') {
$table = "artwork";
}
else {
$table = "comics";
}
if ($catParam != null) {
$catResult = $mysqli->query("SELECT id, title, path, thumb, catidFK FROM $table WHERE catidFK = $catParam");
}
else {
$catResult = $mysqli->query("SELECT id, title, path, thumb, catidFK FROM $table");
}
$img = array();
while($row = $catResult->fetch_assoc())
{
$img[] = "'" . $row['path'] . "'";
}
return $img;
}
?>
PHP bit in viewcomic.php:
include './scripts/keyinput.php';
$JSIndex = $_POST['variable'];
echo "Index = " . $JSIndex;
//$JSIndex should be equal to the javascript variable imgIndex... but it outputs nothing
Any thoughts would be extremely helpful! I'm trying to get my comics website to go live.
Thanks!
Your logic is wrong: at the moment you define your key variable, e is undefined. Then you attach your event handler inside an if statement that will always evaluate to false so that will never work.
The assignment to key should be inside your event handler and the conditional needs to go, you already have that inside your event handler.
Edit: you should also only do your ajax call if one of your action keys is pressed (put it inside the event handler) and do something with the result.
Edit 2: Checkout the manual on $.post, you should add a callback function to process the return value of your php script.
For example:
$.post(
'./templates/viewcomic.php',
{ variable: imgIndex },
function(data) { /* data contains what you have echoed out in your php script */
alert(data);
}
);

Put DIV ID into a PHP Variable

I am wanted to get the id's of all the divs on my page with the class archive and put them in a MySQL query to check and see if the ids are archived in the database.
So basically I am wondering how I can do this: $div = $(this).attr('id');
Then I would throw it into the loop to check:
$matches = mysql_query("SELECT * FROM content WHERE `div` = '$div'");
while ($post = mysql_fetch_assoc($matches))
{
if (mysql_num_rows($matches) > 0)
{
//DO THIS
}
}
UPDATE
I have this code for the AJAX now:
$('div.heriyah').each(function() {
var curID = $(this).attr('id');
$.post("admin/btnCheck.php", { div : curID }, function(data) {
if (data == "yes") {
$('#' + curID).html('<div class=\"add\"><div id=\"add_button_container\"><div id=\"add_button\" class=\"edit_links\"> + Add Element</div></div></div><div class=\"clear\"></div></div>');
} else {
$('#' + curID).html('<div class=\"add\"><div id=\"add_button_container\"><div id=\"add_button\" class=\"edit_links\"> + Set As Editable Region</div></div></div><div class=\"clear\"></div></div>');
}
});
});
And my PHP:
$matches = mysql_query("SELECT * FROM content WHERE `div` = '".$_POST['div']."'");
if (mysql_num_rows($matches) > 0)
{
echo "yes";
} else {
echo "no";
}
What am I doing wrong?
You cannot throw a javascript variable to PHP script like that. You have to send an ajax request to the page
$div = $(this).attr('id');
$.post("yourquerypage.php", { divid : $div }, function(data) {
// Something to do when the php runs successfully
});
Next, configure your query to get the variable from $_POST()
$matches = mysql_query("SELECT * FROM content WHERE `div` = '".$_POST['divid']."'");
And of course, you have to take measures for injection.
It's simple syntax error. Remove the condition after the else and you should be fine.
else (data == "yes") { // remove (data == "yes")
// snip
}

shuffle slider display

i have a problem on the slider of my site, though the slider works fine and good but i need it to be random or shuffle instead of displaying an ordered content..
i already have the code and it need some modification.
this is the line on the main file.php
<script type="text/javascript">
$(document).ready(function() {
$('#slider1').s3Slider({
timeOut: 8000
});
});
<div id="slider1">
<ul id="slider1Content">
<li class="slider1Image">
<img src="products/1.png" alt="1" />
<span class="left">
caption1
</span>
</li>
<li class="slider1Image">
<img src="products/2.png" alt="2" />
<span class="right">caption2
</span>
</li>
<li class="slider1Image">
<img src="products/3.png" alt="3" />
<span class="right">caption3.
</span>
</li></div>
this is the java script file
(function($){
$.fn.s3Slider = function(vars) {
var element = this;
var timeOut = (vars.timeOut != undefined) ? vars.timeOut : 4000;
var current = null;
var timeOutFn = null;
var faderStat = true;
var mOver = false;
var items = $("#" + element[0].id + "Content ." + element[0].id + "Image");
var itemsSpan = $("#" + element[0].id + "Content ." + element[0].id + "Image span");
items.each(function(i) {
$(items[i]).mouseover(function() {
mOver = true;
});
$(items[i]).mouseout(function() {
mOver = false;
fadeElement(true);
});
});
var fadeElement = function(isMouseOut) {
var thisTimeOut = (isMouseOut) ? (timeOut/2) : timeOut;
thisTimeOut = (faderStat) ? 10 : thisTimeOut;
if(items.length > 0) {
timeOutFn = setTimeout(makeSlider, thisTimeOut);
} else {
console.log("Poof..");
}
}
var makeSlider = function() {
current = (current != null) ? current : items[(items.length-1)];
var currNo = jQuery.inArray(current, items) + 1
currNo = (currNo == items.length) ? 0 : (currNo - 1);
var newMargin = $(element).width() * currNo;
if(faderStat == true)
{
if(!mOver) {
$(items[currNo]).fadeIn((timeOut/6), function() {
if($(itemsSpan[currNo]).css('bottom') == 0) {
$(itemsSpan[currNo]).slideUp((timeOut/6), function() {
faderStat = false;
current = items[currNo];
if(!mOver) {
fadeElement(false);
}
});
} else {
$(itemsSpan[currNo]).slideDown((timeOut/6), function() {
faderStat = false;
current = items[currNo];
if(!mOver) {
fadeElement(false);
}
});
}
});
}
} else {
if(!mOver) {
if($(itemsSpan[currNo]).css('bottom') == 0) {
$(itemsSpan[currNo]).slideDown((timeOut/6), function() {
$(items[currNo]).fadeOut((timeOut/6), function() {
faderStat = true;
current = items[(currNo+1)];
if(!mOver) {
fadeElement(false);
}
});
});
} else {
$(itemsSpan[currNo]).slideUp((timeOut/6), function() {
$(items[currNo]).fadeOut((timeOut/6), function() {
faderStat = true;
current = items[(currNo+1)];
if(!mOver) {
fadeElement(false);
}
});
});
}
}
}
}
makeSlider();
};})(jQuery);
i am struggling modifying this script for almost a week ... please help
Not sure if your still looking for a solution... I've just done this, but thought it would have been a better method to write the li tags out server side by calling them from a random array. That's if your using server side scriptiing - Below is what I did in php.
$arr = array("
Some text", "
Some text", "
Some text", );
$arrCnt = count($arr);
for ($i=0; $i<=$arrCnt; $i++)
{
$random = array_rand($arr);
echo "<li class='sliderImage'>";
echo $arr[$random];
echo "</li>\n";
if($i<$arrCnt-1)
unset($arr[$random]);
}
?>
Hope that helps.

Categories