Jquery inside foreach loop - php

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.

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.

PHP - If div has certain class then

My question is simple.
I have the following code:
<div class="last"
<?php
if hasClass(last){
echo " style='width:100%;' ";
}
?>
></div>
I know the if statement is wrong, but the idea is there. I want to know how can I check if this div has the .last class then echo something.
I've been searching around but didn't work anything (didn't find much though).
Best regards.
As already in the comments told it's possible with PHP with DOM parsers.
I'm gonna give you 2 very simple solutions which will save you a lot of work:
CSS:
<style>
.last {
width:100%;
}
</style>
jQuery:
<script type="text/javascript">
$(document).ready(function(){
if($('div').hasClass('last')){
$('div').css('width', '100%');
}
});
</script>
PHP runs on server, so it generates HTML. If you have that class="last" you don't need to check - it's part of the code....hard-coded.
But you can have some PHP variable and depending on it's place print out class and also style for that other element:
<?php
$print_last = true;
?>
...
<div <?php if ($print_last) echo 'class="last" ';
<?php
if ($print_last){
echo " style='width:100%;' ";
}
?>
></div>
But if you want to check on html element you have to do it on client side (browser) from JavaScript and jQuery can be helpful too.
It is possible to check that using PHP, however that couldn't be done easliy (you'll need to parse buffered HTML using DOM parser, then look up for divs, etc...).... Much better solution is to do that with Javascript/jQuery, using Document.getElementsByClassName() function.
Sample solution:
var elements = document.getElementsByClassName("last");
for(var i = 0; i < elements.length; i++)
{
var element = elements[i];
element.style.width = "100%";
}
#azhpo
Obviously the HTML being the front end language you have to pass the elements either through some submit button or via ajax request.
Using submit button: select the class name of div using either javascript
var className = document.getElementById("myDIV").className
document.getElementById("myHiddenField").value = className;
Now on clicking the submit button it would get submitted
Using ajax:
Again take the classname either through javascript / jquery
var className = jQuery("#myDiv").attr("class");
Now fire ajax query and send the class name to your script
jQuery.ajax({
url: 'file.php',
type: 'POST',
data: 'class='+className,
success: function(data){//do whatever you want},
error:function(){//do whatever you want}
});

get increasing variable from php to jquery

how to pass a variable to jquery with php ?
i have to call the jquery from html this is what is confusing me:
jquery:
$(document).ready(function() {
$('#pre-info').click(function() {
$('#hide').slideToggle("fast");
});
});
now i want a $i after #pre-info and after #hide.
im calling the jqueryScript like this :
thank you.
Okay, here is more code :
<?php
$i =0;
//Make some querys nd stuff
foreach ($all as $one) {
//Here the event 1 is createt but the pre info gets increased with each event listet
echo "<div class='EVENT'><div id='pre-info$i'>";
// get som other tables nd stuff
echo"</div><div id='hide$i' style='display:none;'>";
//now this part is hidden until i click on the pre-info
//hidden Stuff
$i++;
}
?>
<script type="text/javascript">
$(document).ready(function() {
$('.pre-info').click(function() {
var hiddenid=$(this).data('hiddenid');
$('#'+hiddenid).slideToggle();
});
});
</script>
it does still not work, did i miss anything?
for me it looks like pre-info in this javascript needs a reference ( $i) as well ?
maybe i just dont understand the jquery completly..
Ok so you have several hidden divs and for each one you also have a listener to toggle their visibility. The original list comes from php which in turn gets the data from a query.
You could use data attributes to link pre-infos to hidden elements:
$i =0;
foreach ($all as $one) {
echo "<div class='pre-info' data-hiddenid='hide$i'>click me</div>";
echo "<div id='hide$i' style='display:none;'> hidden stuff </div>";
$i++;
}
then you just need one listener on jQuery
jQuery(document).ready(function() {
jQuery('.pre-info').click(function() {
var hiddenid=jQuery(this).data('hiddenid');
jQuery('#'+hiddenid).slideToggle();
});
});
Hope it helps (edit, I wrapped the listener in the document ready event)
By the way, it seems to me you're reinventing the wheel. You could use jQuery UI's accordions or Bootstrap collapsibles with nice, crossbrowser transitions.
If the JS is in .php file, you can just use:
$(document).ready(function() {
$('#pre-info<?php echo $x; ?>').click(function() {
$('#hide<?php echo $x; ?>').slideToggle("fast");
});
});
Your question does not contain enough information to give you more detailed answer, I'm afraid.
you could embed the php variable you require into a hidden html attribute or a data attribute
Hidden Element HTML
<input type="hidden" id="someId" name="someName" value="<?php echo $someVariable?>"/>
Javascript
var someVar = $('#someId').val()
Data HTML
<div id="someId" data-some-var="<?php echo $someVariable?>"></div>
Javascript
var someVar = $("#someId").data("some-var")
Note that if you use data you must include the keyword "data" before whatever you decide to name the attribute

Javascript: dynamic var names with php?

Probably a dead simple and idiotic question (I'm totally new to javascript):
I have this code that loads a new post by clicking on a "next" or "back"-link. The clicks variable is used to scroll up and down in the sql-limit-statement (using the swapContent function), means you move backward or forward in the database by clicking the links. It works easy and perfectly:
<script type="text/javascript">
var clicks = -1;
function increase()
{
clicks++;
return false;
}
function decrease()
{
clicks--;
return false;
}
</script>
<div id="<?php echo $post['id'].'-multipost'; ?>">
<?php include('views/posts/_postmultipost.php'); ?>
</div>
<div id="<?php echo $post['id']; ?>-next" class="rightbutton" style="display:block;">
next
</div>
<div id="<?php echo $post['id']; ?>-back" class="leftbutton" style="display:none;">
back
</div>
The only problem: As you see I have several posts (post-IDs). But the javascript var "clicks" is always the same. How can I add the post-id into the javascript variable name "clicks", well, something like this :
var <?php echo $post['id']; ?>-clicks = -1;
Of course it doesn't work this way, but I have no clue how to manage it. Any advice? Sorry for this stupid question...
Thanks for your help!
UPDATE
Ok, got the solution: Bryan was right!!!
Changed the code to:
<script type="text/javascript">
var clicks = {};
clicks['<?php echo $post['id']; ?>'] = -1;
function increase()
{
clicks['<?php echo $post['id']; ?>']++;
return false;
}
</script>
The javascript in html stays as it is:
>
Clicks is now an object and will output the following in the swapContent-Function:
count: Array
(
[80] => 0
)
In php you would access the value like this:
foreach($count as $key=>$value) { $count = $value }
In javascript it seems to work a bit different like this:
for(x in clicks)
{
var clicks = clicks[x];
}
Seems to work perfectly now, thanks for your help!!
I'm not incredibly familiar with PHP, so I don't know about php echo. However, would using an object work?
var postClicks = {};
postClicks['<?php echo $post['id']; ?>'] = -1;
As far as I understand you are trying to get this:
var something-clicks = -1;
But in JS something-clicks is an expression - substraction of two variables.
Name tokens in JS cannot contain '-' in contrary with CSS.
You have a syntax error:
onmousedown="increase(); javascript:swapContent('next', clicks, '<?php echo $post['id']; ?>', '<?php echo $post['title']; ?>', '<?php echo $_SESSION['user']['id']; ?>');"
that javascript: is the problem. That property is expected to contain raw JS, and that token is invalid. the javascript used as a protocol is for use on the href property of an a tag.
Other than that, it looks alright. Just type clicks in the JS console of your browser to get the current value returned. Or add console.log('clicks:', clicks); to your function so that the result is logged out on each click.

using JS variable in PHP

how can use JS variable in PHP like this ?
<script>
x = document.getElementById(1).value;
var listOf = <?php echo $listOf[x]; ?>;
</script>
this doesn't work :(
And rightfully so. PHP is executed on the server, while JavaScript is executed in the client's browser. Those are two different contexts and the variables from one are not visible in the second.
You need to have your PHP script output a JavaScript version of the array and then use this one in your script. Something like this:
<?php
echo "listArray = new Array();\n";
foreach ($listArray as $key => $value) {
echo 'listArray[', $key, '] = ', $value, ";\n";
}
You can't use it directly like this.
You'll have to use AJAX to send the value from client side to server side and only then PHP can see it.
Using jQuery it can become really simple though:
x = document.getElementById(1).value;
$.get("mypage.php?x=" + x, function(result) {
alert("response from PHP: " + result);
});
And in the PHP read the x from querystring and send proper output.
it is not possible because both are different languages so you cant use javascript varible
in php inside javascript
This is not possible. PHP is executed serverside, even before its output reaches your browser. JS is executed clientside, in the browser. You can't do this, unless you call some other PHP script with this variable x.
You can't. JavaScript is run in your browser while PHP gets run on the server. The only way for JavaScript to communicate with PHP is by using AJAX (XMLHttpRequest), separating the JavaScript from the PHP.
like this
if you put php in any single or double quotes than it work
<script type='text/javascript'>
x = document.getElementById(1).value;
var listOf = "<?php echo $listOf[x]; ?>";
</script>
This will convert javascript variable to php variable.
<script>
function sud(){
javavar=document.getElementById("text").value;
document.getElementById("rslt").innerHTML="<?php
$phpvar='"+javavar+"';
echo $phpvar.$phpvar;?>";
}
function sud2(){
document.getElementById("rslt2").innerHTML="<?php
echo $phpvar;?>";
}
</script>
<body>
<div id="rslt">
</div>
<div id="rslt2">
</div>
<input type="text" id="text" />
<button onClick="sud()" >Convert</button>
<button onClick="sud2()">Once Again</button>
</body>
Demo: http://ibence.com/new.php

Categories