Not sure why jQuery isn't getting the variable information - php

The values don't seem to be coming out and showing up on the page. It should be creating divs that pop up with the google_color and the background set to the hex value.
The app is suppose to take pixel image data and match it to my swatch library known as formatted_colors.js, which is an array. The array looks like this:
var colors = [];
colors["000000"] = "black"; colors["100000"] = "black"; colors["200000"] = "black";
Maybe I'm not suppose to use the .each function? Although it is a loop.
Here is a snippet:
<div class="rounded_color" hex="<?php echo $css_color ?>" xy="<?php echo $x.$y ?>"></div>
<div id="<?php echo $x.$y ?>"></div>
<script type="text/javascript" src="jquery-1.6.2.js"></script>
<script src="formatted_colors.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
//iterate through pixels and match rounded color to array in formatted_colors.js
$(document).ready(function() {
$(".rounded_color").each(function(){
var google_color = getColor($(this).attr("hex")); // finds a match of "hex" value in formatted_colors.js and return name to google_color
$('#'+$(this).attr("hex")).html(google_color); // set the div's html to name which is google_color
alert('#'+$(this).attr("id")); //testing if value is there, but shows #undefined
$('#'+$(this).attr("hex")).css('background-color:', google_color);
})
// get name of color function from formatted_colors.js
function getColor(target_color){
if (colors[target_color] == undefined) { // not found
return "no match";
} else {
return colors[target_color];
}
} // end getColor function
}) // end ready function
</script>
Sorry, I'm new to this so I'm not sure what to do exactly now.
Here is my entire code: http://pastebin.com/HEB3TWZP
Thanks in advance!

You don't need to concatenate #. this is the current element in the iteration.
Also you might want to do something like var $this = $(this); Cleans up your code and you aren't recreating the jQuery object over and over again within the same iteration.

Related

acf fields in a jquery array

I create acf fields to upload logo image.
I need to get all url logo and push them in a jQuery array like this :
var logos = ["http://www.mylogo.com/img1.jpg", "http://www.mylogo.com/img2.jpg", "http://www.mylogo.com/img3.jpg"];
My ACF field :
$wall_references = get_field('wall_references');
I wrote that :
<script type="text/javascript" language="javascript">
var logos = new Array();
<?php foreach($wall_references as $wall_reference){ ?>
logos.push('<?php echo $wall_reference['ref_logo']['url']; ?>');
<?php } ?>
</script>
That's print something like this in my document :
<script type="text/javascript" language="javascript">
var logos = new Array();
logos.push('http://www.mylogo.com/img1.jpg');
logos.push('http://www.mylogo.com/img2.jpg');
logos.push('http://www.mylogo.com/img3.jpg');
</script>
How to push each php URL in my array please ?
I don't want to print my array in the console log, but directly in my document like this :
var logos = ["http://www.mylogo.com/img1.jpg", "http://www.mylogo.com/img2.jpg", "http://www.mylogo.com/img3.jpg"];
I am seeing one small quote mistake here, Use double quotes around instead single quotes.
logos.push("<?php echo $wall_reference['ref_logo']['url']; ?>");
What exactly is the difficulty?
If you console.log the logos Array you have exactly what you're looking for!

how to get the value of an php array in jQuery

i have a PHP code that will obtain the total images of a certain website via CURL, and put it inside an PHP loop.
$z=1;
for ($i=0;$i<=sizeof($images_array);$i++) {
....<img src = "$images_array[$i]" id="$z"> ..
$z++;
}
a user can then scan through the array with a prev/next button and the current image being shown will be displayed in my $('$current_image').val(1);
$.post("curl_fetch.php?url="+ extracted_url, {
}, function(response){
$('#loader').html($(response).fadeIn('slow'));
$('#current_image').val(1); // insert loop value in .val()
when i click a button, i want to get the value of the array, and not the loop value
$(function() {
$(document).on('click','.submit', function () {
var img = $('#current_image').val(); //get the array value, not the loop value
alert(img);
});});
now, how do i properly get the array value in my $('#current_image').val(1); in Jquery.
Your question is a little confusing but it sounds like you want to fetch a list of images using curl and then be able to page through them one by one using jQuery. One way to do this would be to build a javascript array of the image URLs and then just update the value of the img src using that array.
<!-- load the page with the first image -->
<img src="<?php echo $images_array[0]; ?>" id="visible_img"></img>
<button id="previous"><< previous</button>
<button id="next">next >></button>
<!-- setup a javascript array of images and listen for clicks -->
<script type="text/javascript">
var curIdx = 0;
var imageUrls = ["<?php echo implode('","', $images_array); ?>"];
// display the previous image (if there is one)
$("#previous").click(function() {
if (curIdx > 0) {
curIdx--;
$("#visible_img").attr("src", imageUrls[curIdx]);
}
});
// display the next image (if there is one)
$("#next").click(function() {
if (curIdx < imageUrls.length - 1) {
curIdx++;
$("#visible_img").attr("src", imageUrls[curIdx]);
}
});
</script>

Extract SRC's from selected images, comma separated

I'm using a Wordpress plugin where I can only type attachment urls (comma separated) in an input box. I need to alter the code so I can click an image and it will extract the src to put it in the input box.
I made it possible with only one image.
First, I echo'd all the images from my media library. And then I did this:
<img class="media-image" src="<?php echo $images[$i]; ?>"/>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('.media-image').click(function(){
var thisValue = jQuery(this).attr('src');
var thisTarget = jQuery('#target');
thisTarget.val(thisValue);
return false;
});
});
</script>
<input id="target" type="text"></input>
What this does: Whenever I click an image, the src will be put in the input text box. When I click another image, the value will be changed accordingly.
But how can I achieve this with multiple images? So, if I click 3 images, I want all the src's to be comma separated in the input field. Whenever I click a selected image again, I want it to be deselected (i.e. I want the src to be removed from the input).
Track the clicked/de-clicked images in an array and join it to form a string value for your input. Something like:
var imgs_tracker = [], field = jQuery('#target');
$('body').on('click', '.media-image', function() {
var src = $(this).attr('src'), already_in = imgs_tracker.indexOf(src);
already_in == -1 ? imgs_tracker.push(src) : imgs_tracker.splice(already_in, 1);
field.val(imgs_tracker.join(', '));
});
Note also I delegate the click event - much more efficient than binding it to each and every item.
<img class="media-image" src="<?php echo $images[$i]; ?>"/>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('.media-image').click(function(){
var thisValue = jQuery(this).attr('src');
var thisTarget = jQuery('#target');
thisTarget.val(thisTarget.val() + "," + thisValue);
return false;
});
});
</script>
<input id="target" type="text"></input>
Select the previous value and append to it.
$(function () {
var images = $(".media-image");
images.on("click", function () {
var img = $(this),
selected = !!img.data("selected");
img.data("selected", !selected);
var foo = images.filter(function () {
return !!$(this).data("selected");
}).map(function (_, el) {
return this.src;
}).get();
$("#target").val(foo.join());
});
});
fiddle

change input button style using javascript on click

I wanted to change the style of the button I'm using every time I clicked that button and together change it's text. Problem is I wanted to do it using and external javascript which I'm not that familiar with it's syntax. To elaborate what I wanted to do is to have a button having a text displaying like: Very Good, Good, Moderate, Failed. Each of the text has it's own assigned gradient color using CSS let's say a gradient of Green for Very Good, Yellow for Good, Orange for Moderate and Red for failed. Tried searching for it but I only landed on an irrelevant posts. What I think is that I need to make a button with on click and everytime I click the javascript will add int values from 0 and reset back to 0 after it reaches 3. then I think I can use case for the css class assigning like this.style="failed" Well I don't know if this is possible.
UPDATE:
After doing some research I've managed to do something about the changing texts (using javascript alone) but not yet the class part since I think the class is a keyword in javascript. here's my script so far:
function buttonChange(){
var button = document.getElementById("stats");
switch (button.value)
{
case "Very Good":
button.value="Good";
break;
case "Good":
button.value="Moderate";
break;
case "Moderate":
button.value="Failed";
break;
default:
button.value="Very Good";
}
}
now the problem is the style. :)
Using jQuery your code could look something like this:
var values = new Array('Very Good', 'Good', 'Moderate', 'Failed');
var colors = new Array('lime', 'yellow', 'orange', 'red');
$('#rate').click(function() {
// current index is stored in data attribute
var idx = $(this).data('value') + 1;
// last value was selected -> go back to first one
if (idx >= values.length) {
idx = 0;
}
// update data attribute with current index
$(this).data('value', idx);
// update button text
$(this).val(values[idx]);
// update button background color
$(this).css('background-color', colors[idx]);
});​
See this FIDDLE.
have a look at this:
Change an element's class with JavaScript
I think that your CSS should have all the styles for gradients and stuff like this:
.VeryGood {//gradient for very good
}
.Good {//gradient for good
}
.Moderate {//gradient for moderate
}
.Failed { //gradient for failed
}
and then, use this javascript and html :
<script type="text/javascript">
var i = 1; //change to 0 if element dosen't need to have any class by default
var classArray = new Array();
classArray[0] = 'VeryGood';
classArray[1] = 'Good';
classArray[2] = 'Moderate';
classArray[3] = 'Failed';
function changeClass()
{
document.getElementById("MyElement").className = classArray[i];
i++;
if(i>=3){
i=0;
}
}
</script>
...
<button onclick="changeClass()">My Button</button>
now, the array key i increases every time the button is clicked, so by default, you can have your element's class as VeryGood, and every time the button is clicked, it advances to next class, so after VeryGood comes Good then Moderate then Failed, ithe it resets itself to VeryGood. hope this is what you are looking for :)
Here is a jQuery solution to cycle through the button text and the background colour for the four states:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var states = ['Very Good', 'Good', 'Moderate', 'Failed'];
var colors = ['green', 'Yellow', 'orange', 'red'];
var index = 0;
$('body').on('click', '#button', function(){
index = ++index%4;
$("#button").html(states[index]);
$("#button").css('background-color',colors[index]);
});
});
</script>
</head>
<body>
<button id="button" style="background-color:green"; type="button">Very Good</button>
</body>
</html>
Note the modulus (%) operator which simplifies the circular increment of 'index' from 0 to 3.

How do I use externalInterface to allow Flash to call javascript to update a value on the screen?

I have a Flash movie that is embeded in a PHP page. The PHP page displays a value to the user (the number of images they have uploaded). When the user uploads a new image I want the value on the PHP page to reflect the change without refreshing the page.
This value is retrieved from database using MySQL. So heres what Ive done so far -
On the PHP page where I want to show the value I have a div
<div id="content_info"><script type="text/javascript" src="getInfo.php?group= <?php echo($groupid); ?> "></script></div>
This calls an external PHP file that queries the database and outputs the result like this
Header("content-type: application/x-javascript");
//do the query with PHP and get $number and then output
echo "document.write(\" (".$number.")\")";
When the page loads for the first time the correct number shows in the div and so all works fine. The next step is to call something to update the contents of this div when the value changes. So I will set up externalInterface in flash to call a javascript function to do this.
This is where Im stuck, I want to be able to do something like this -
function ReplaceContentInContainer(id) {
var container = document.getElementById(id);
container.innerHTML = getInfo.php?type=new&group= <?php echo($groupid) ?>;
}
and call this by
ReplaceContentInContainer(content_info)
I realise this isnt going to work but can anyone show me how to get this result?
many thanks
group= <?php echo($groupid); ?> will be executed only when PHP creates the page. You should store that value inside a variable in the javascript. See if this works.
<div id="scriptDiv">
<script type="text/javascript">
<!-- store the group id -->
var groupID = <?php echo($groupid); ?>;
function getGroupID()
{
return groupID;
}
function updateValue(value)
{
document.getElementById("content_info").innerHTML = value;
}
</script>
<div id="content_info">
<!-- for initial value -->
<script type="text/javascript"
src="getInfo.php?group= <?php echo($groupid); ?> ">
</script>
</div>
</div>
Now you can use flash's URLLoader:
var ldr:URLLoader = new URLLoader();
var gid:String = ExternalInterface.call("getGroupID");
var req:URLRequest = new URLRequest("getInfo.php");
req.data = {type:"new", group:gid};
ldr.addEventListener(Event.COMPLETE, onLoad);
ldr.addEventListener(IOErrorEvent.IO_ERROR, onError);
ldr.load(req);
private function onLoad(e:Event):void
{
var data:String = URLLoader(e.target).data;
ExternalInterface.call("updateValue", data);
}
private function onError(e:IOErrorEvent):void
{
trace("ioError");
}

Categories