acf fields in a jquery array - php

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!

Related

Remove a portion of php variable output

I have following php:
$my_name = $my_site->getUserData("dfd_Name");
<?php echo $my_name?>
It outputs as following: Steve, Kim
I want to keep the format as it is. However there are times when I only need the first part (for example, "steve").
Is there a jquery way to remove everything after (including ",") the comma, so it will be "Steve" as the output.
EDIT
So, I am using the following php:
<a class="my_name_class" href="http://example.com/section1/section2/section3/<?php echo $my_name ?>" >
<?php echo esc_html($my_name) ; ?>
</a>
What would be the jQuery (or any other ways) to remove the second part (, kim) within the href?
In PHP,
<?php echo explode(',', $my_name)[0]?>
In jQuery,
First select that DOM part,
var thing = $('#anything').html();
and explode like,
var name = thing.split(',');
Your desired value,
name[0];
Place it in DOM like,
thing.html(name[0]);
Here is a quick solution in pure jQuery
HTML:
<span class="name">Steve, Kim</span>
JS:
$(function () {
$(".name").text($(".name").text().split(',')[0]);
});
To get the second part, change the above code to:
$(function () {
$(".name").text($(".name").text().split(',')[1]);
});
Include jQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
https://jsfiddle.net/myLnnd0e/
Showing second name: https://jsfiddle.net/myLnnd0e/1/
Fixed for URL: https://jsfiddle.net/myLnnd0e/3/
Solution for URL:
HTML:
http://example.com/section1/section2/section3/
JS:
$(function () {
$(".name-url").attr("href", ($(".name-url").attr("href") + $(".name-url").data("names").split(',')[1].trim())).append($(".name-url").data("names").split(',')[1].trim());
});
While this is a completely valid use of Javascript, it is always best to provide users with an alternate way to access this data, for usability issues and also in the case that Javascript is disabled.

Passing PHP variable in JS using div id

I have some pages. In these pages i want to show the error message.
Now i am showing these message through JavaScript.But the code is repeated so many times that's why i have decided to define this message as a constant in config file.
I accessed this constant STORE_OFFLINE_MSG in a div. And then I am using the html of this div , this function return the text of the div as defined in config file and passes it in the variable of JS
this is the code in my config file config.php:
define('STORE_OFFLINE_MSG','hello');
This is the sort of code of php file abc.php
<div class="storeOfflineMsg"><?php echo STORE_OFFLINE_MSG;?></div>
<script type="text/javascript">
var msg = $(".storeOfflineMsg").html();
$.prompt('<h3 Store unavailable</h3>'+msg);
</script>
but if i used this variable in other file only by using the div class then .html() returns NULL.
My second file xyz.php is as:
<script type="text/javascript">
var msg = $(".storeOfflineMsg").html();
$.prompt('Store unavailable</h3>'+msg);
</script>
Please suggest me what to do. and how can i get a php constant in the Java Script through div class.
You can store the variable directly in javascript variable.
<script type="text/javascript">
var msg = "<?php echo STORE_OFFLINE_MSG;?>";
If you want to pass data from PHP to Javascript try this:
echo the data out in the of your page within a script section.
<script type="text/javascript">
<?php
echo 'var offlineMsg = ' . STORE_OFFLINE_MSG . ';';
echo 'var onlineMsg = ' . STORE_OnLINE_MSG . ';';
?>
</script>
These Javascript variables will then be availabe globally to all other javascript code on the page. Much better than placing it in a hidden div.

Not sure why jQuery isn't getting the variable information

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.

Jquery inside foreach loop

I have this jquery code in a foreach loop. Basicaly the variable $perf gets a new value with every loop. How can I use jquery to display the different $perf value with each loop? Is it possible?
foreach ($perfs as $perf):
<script type="text/javascript">
$(document).ready(function(){
var performerName = $(".transparency").data('title');
var divcontent = $(".transparency").html();
if ( divcontent == ' ' ){
$(".transparency").html(''+performerName+'');
}
});
</script>
<div class="transparency" data-title="<? echo $perf; ?>"> </div>
endforeach;
You should do it like this:
<?
foreach ($perfs as $perf):
?>
<script type="text/javascript">
$(document).ready(function(){
var $perf = "<? echo $perf; ?>"; //Get from php
alert($perf); //Show it
//Here goes the rest of your script
var performerName = $(".transparency").data('title');
var divcontent = $(".transparency").html();
if ( divcontent == ' ' ){
$(".transparency").html(performerName);
}
});
</script>
<div class="transparency" data-title="<? echo $perf; ?>"> </div>
<?
endforeach;
?>
That's it. It works.
(I tried to modify your code at least as possible, cause I don't know if I can remove parts)
PS: There would be more 'elegant' solutions, do you want one? or this is enough?
Can you please describe what you are trying to do? I'm about 90% sure there is zero reason for any javascript, jQuery or otherwise.
Why not just do this?
<?php
foreach($perfs as $perf)
{
echo "<div class='transparency' data-title='$perf'>$perf</div>";
}
?>
Unless there is something more you are trying to do, you don't need javascript at all. And even if you do need javascript, take the function out of the loop and call it once each iteration. you dont need the exact same function defined multiple times.
I suggest you look into the relationship between server and client-side scripting. For starters - take a look at the HTML source generated by your PHP and see if thats anything close to what you want. Also, read up about ajax. It seems that you are trying to do combine PHP/javascript in such a way that it needs additional HTTP Requests (ajax calls)
It is impossible to have PHP and javascript interact directly without AJAX, and it is difficult to answer the question without more knowledge of what, exactly, you want to happen.
If you want a different transparacy div for each value of $perfs you can use:
<?php foreach ($perfs as $perf) { ?>
<div class="transparency" data-title="<?php echo $perf; ?>"> </div>
<?php } ?>
And they you can use the jquery .each() to iterate over the divs
$(".transparency").each( function() {
var performerName = $(this).data('title');
// do stuff //
});
If all you want is to pass the values in $perfs to you javascript function you can use
var perfs = <?php echo json_encode($perfs); ?>;
OK I think I see what you are trying to do now. You'll want something like this:
<script type="text/javascript">
$(document).ready(function(){
var perfs = <?php echo json_encode($perfs); ?>;
$.each( perfs, function( index, value ) {
$( ".transparency" ).append( value+'<br>' );
} );
} );
</script>
<div class="transparency"></div>
This will output each value of $perfs inside of the transparency div.
Using JQuery each and append.
You will never want to wrap an entire script in a foreach loop, as that will create a separate script for each element in the array. Using json_encode you will change the PHP array into a javascript object & you can do whatever you want to with it.
Remember javascript is only able to access elements written to the page using echo or something similar. Whatever you can see when you look at 'view page source' in your browser is all your script will be able to use.

ajax image as response in php

I want to display an image as a response to an ajax call using php.. Does anybody have the complete code for this?? Please help me out..
Thanks in advance..
Well I don't have the complete code to this, and if I did, I wouldn't give it to you.
You need to start off by creating an image using PHP's various image generation functions. To make it dynamic you could send it various parameters which are encoded in the url and can be fetched using the $_GET superglobal in php.
You would then set the src of an existing image placeholder element to the location of your dynamic image, then voila! Instant dynamic image.
You should use jQuery + JSON combination. You can convert php array into JSON format using json_encode.
index.php:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>
<a href='car.php' class='ajax'>Car Image</a>
<a href='bike.php' class='ajax'>Bike Image</a>
<div id="title">Title comes here</div>
<div id="image">Image comes here</div>
car.php:
<?php
$jsonArray['title'] = "Car";
$jsonArray['image'] = "<img src='images/car.jpeg'>";
echo json_encode($jsonArray);
?>
bike.php:
<?php
$jsonArray['title'] = "Bike";
$jsonArray['image'] = "<img src='images/bike.jpeg'>";
echo json_encode($jsonArray);
?>
ajax.js:
jQuery(document).ready(function(){
jQuery('.ajax').click(function(event) {
event.preventDefault();
jQuery.getJSON(this.href, function(snippets) {
for(var id in snippets) {
jQuery('#' + id).html(snippets[id]);
}
});
});
});

Categories