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.
Related
So I've got a data table that is updated with two different sets of buttons. The jquery is thus;
$('body').on('click', "button", function () {
var $but_name = $(this).attr("name");
var $but_id = $(this).attr("id");
if($but_name==="sky_week") {
$("#adv_stats").load("index.php #adv_stats", {this_week:$but_id});
} else if($but_name==="ASC") {
$("#adv_stats").load("index.php #adv_stats", {up_down_type:"ASC",sort_type:$but_id});
} else if($but_name==="DESC") {
$("#adv_stats").load("index.php #adv_stats", {up_down_type:"DESC",sort_type:$but_id});
}
});
It literally just grabs the id of the button clicked and passes what was clicked to the load to refresh the data table.
(On an unrelated note, I'm new to jquery but I've got my load pointing at itself. So index.php is the page the code is on and I've just got it pointing at a div lower down to update that. It works - and shouldn't get stuck on an infinite loop because it's only triggered on clicks - but I feel like it's wrong and bad coding. Can someone confirm or deny this?)
The issue I have is that when you click the ASC or DESC buttons, it doesn't pull the week through because that's on a different button. I think it's because of the PHP at the top of the page that pulls it;
$this_week = $_POST['this_week'] ?? '202118';
$up_down = $_POST['up_down_type'] ?? 'ASC';
$sort = $_POST['sort_type'] ?? 'nt_login';
$breakdown = get_adv_breakdown($this_week, $sort, $up_down);
And it's because of the '?? '202118' bit, which is defaulting to 202118 as the week instead of the currently selected week.
How do I get it to update the ASC values and keep the currently selected week? I feel like I need to somehow store the week somewhere else, but this is hitting the limit of my jquery knowledge.
Here's a visual of the final page, showing the two different sets of buttons;
https://i.stack.imgur.com/UU8Kd.png
I've added the html that generates the buttons;
<td align="center">Advisor<button name="ASC" id="nt_login"><i class="arrow up"></i></button><button name="DESC" id="nt_login"><i class="arrow down"></button></td>
etc
etc
And a little loop that adds the last 12 weeks;
<div id="week-buttons">
<p align="center"><?php foreach($no_weeks as $week) { ?>
<button name="sky_week" class="sky-primary-button w-button" id='<?php echo h($week['Week']); ?>' onclick="this.blur();">
<?php echo h($week['Week']); ?>
</button>
<?php } ?></p>
</div>
It looks like you are reloading your page whenever you do a sort. In order to preserve the value of $this_week you will need to pass that as a $_POST value to your page when you fire .load()
It should be as simple as doing something like this:
$('body').on('click', "button", function () {
var $but_name = $(this).attr("name");
var $but_id = $(this).attr("id");
if($but_name==="sky_week") {
$("#adv_stats").load("index.php #adv_stats", {this_week:$but_id}); // this seems to be an error?
} else if($but_name==="ASC") {
$("#adv_stats").load("index.php #adv_stats", {up_down_type:"ASC",sort_type:$but_id, this_week: $this_week});
} else if($but_name==="DESC") {
$("#adv_stats").load("index.php #adv_stats", {up_down_type:"DESC",sort_type:$but_id, this_week: $this_week});
}
});
I am trying to get this code to work but cannot figure out how to make it work correctly. I think I am close though. This code works fine on my page:
var entryID = $(this).attr('id');
if ("<?php echo $locations[2]['floor']; ?>" == 'firstFloor' ) {
$("#drawTable").attr("style", "background:url(\'images/firstFloor.jpg\') 50% / 100% no-repeat;");
}
else if ("<?php echo $locations[2]['floor']; ?>" == 'secondFloor' ) {
$("#drawTable").attr("style", "background:url(\'images/secondFloor.jpg\') 50% / 100% no-repeat;");
}
I am trying to make the array changeable by using the entryID instead of just a number like '2'. I do not think that I am concatenating correctly below. If you can help It would be much appreciated! Thank you
var entryID = $(this).attr('id');
if ("<?php echo $locations . "[";?>" +entryID+ "<?php echo "]['floor']"; ?>" == 'firstFloor' ) {
$("#drawTable").attr("style", "background:url(\'images/firstFloor.jpg\') 50% / 100% no-repeat;");
}
else if ("<?php echo $locations . "[";?>" +entryID+ "<?php echo "]['floor']"; ?>" == 'secondFloor' ) {
$("#drawTable").attr("style", "background:url(\'images/secondFloor.jpg\') 50% / 100% no-repeat;");
}
Then thing is you can't do that as PHP already ran on server and javascript has started to work way later after DOM ready. So, that is not possible such way. Instead you can store1 the array in a js variable like:
var entryID = $(this).attr('id');
var locations = <?php echo json_encode($locations); ?>; // i suppose this could be array.
var floor = locations[entryID]['floor']; // <----target the floor here
if (floor === 'firstFloor') {
$("#drawTable").css("background", "('images/firstFloor.jpg') 50% 100% no-repeat;");
} else if (floor === 'secondFloor') {
$("#drawTable").css("background", "url('images/secondFloor.jpg') 50% 100% no-repeat;");
}
and Instead of attr such way better to use css or event better addClass.
1. - The js has to be written on php page.
You cant access php array through javascript. for this you should convert php array to javascript array and assign it in javascript variable after that you can access that array. Like this
<script type="text/javascript">
//Assign php generated json to JavaScript variable
var tempArray = <?php echo json_encode($locations); ?>;
//You will be able to access the properties as
alert(tempArray[0].Key);
</script>
I have the following PHP that returns records from a my MYSQL table. These records are displayed as LINKS. See code below...
<div class="slide1" id="u1026">
<?php while ($row = mysql_fetch_array($query_rental)) {
echo "<a class='fancybox fancybox.iframe' id='rental' value={$row['layout']} href=\"brochures\items-rental.php?id={$row['client_name']}\"></a>";
}?>
</div>
What I would like, is for the HREF link to change to
\"brochures\items-rental-layout2.php?id={$row['client_name']}\
If VALUE contains the text "layout2". I know that I can change HREF using jquery code
$(document).ready(function () {
$("#event").attr("href", "http://the.new.url")
});
I'm just not sure how to do that depending if the VALUE contains text "layout2". Any help is much appreciated. Thanks
You can just do it straight in the PHP code:
while ($row = mysql_fetch_array($query_rental)) {
$layoutFlag = $row['layout'] == 'layout2' ? '-layout2' : '';
echo "<a class='fancybox fancybox.iframe' id='rental' value=\"{$row['layout']}\" href=\"brochures\items-rental{$layoutFlag}.php?id={$row['client_name']}\"></a>";
}
You could also do it with Javascript:
$(function () {
// I'm assuming you are going to turn it into a rental class, otherwise change the selector to whatever.
$("a.rental").each(function() {
var rentalItem = $(this);
if (rentalItem.attr('value') === 'layout2') {
// You can choose what to replace, as long as you know it will replace EXACTLY what you want it to. I'm just going with Regex's ^ (start-of-line) operator to make sure that what we are replacing is at the start of the line...
rentalItem.attr('href', rentalItem.attr('href').replace(/^brochures\\items\-rental/, 'brochures\\items-rental-layout2'));
});
});
As you can see, just doing it in PHP is so much easier.
Also as a side note, you are creating multiple elements with the same id. Maybe you meant class='fancybox fancybox.iframe rental'?
And as a second side note, I suggest using the data- prefix for holding custom data. In layout's case, use data-layout='layout-whatever'. You can then use .attr('data-layout') to get the layout attribute (it's easier to understand what that code is doing too!).
You can either run the IF statement on the PHP loop
while ($row = mysql_fetch_array($query_rental)) {
echo "<a class='fancybox fancybox.iframe' id='rental' value={$row['layout']} href=\"brochures\items-rental".($row['layout'] == 'layout2' ? '-layout2' : '').".php?id={$row['client_name']}\"></a>";
}
Or by jQuery
$( "a.fancybox" ).each(function( index ) {
if($(this).val() == "layout2") {
oldHref = $(this).attr('href');
newHref = oldHref.replace('items-rental.php', 'items-rental-layout2.php')
$(this).attr('href', newHref);
}
});
all your links have the same ID which can cause some issues when you wuold want to work with them with jQuery.
If you have more a tags with the fancybox class, try adding a unique class to these tags and update the each loop
I have the following script. It's making divs with the username on it, works fine until the href part, the php page opens with user=$user (the variable doesn't take it's value)
For example $user='george' in the div id and inside getElementById, but in href user=$user? why?
Thanks in advance,
<script>
$(document).ready(function(){
for(i = 0; i < 1; i++) {
$('body').append('<div id="div'+'<?php echo $user; ?>'+'"/>'); //$user='george'
document.getElementById('div'+'<?php echo $user; ?>'+'').innerHTML=
'<?php echo $user; //$user='george'
echo '<a href="account_show_to_members.php?user=$user"> //$user=$user WRONG
Visit!</a>'; ?> ';
}
});
</script>
The problem is that php wont process inline variables in a string with single quotes, nor escaped characters like \n. The first place you should start is changing this:
echo '<a href="account_show_to_members.php?user=$user"> //$user=$user WRONG
Visit!</a>';
to this:
echo "<a href='account_show_to_members.php?user=$user'>Visit!</a>";
definitely look into some formatting standards though, this code is kind of a mess.
EDIT: just for the sake of avoiding confusion, here's how it should look altogether:
<script>
$(document).ready(function(){
for(i = 0; i < 1; i++) {
$('body').append('<div id="div<?php echo $user; ?>"/>');
document.getElementById('div<?php echo $user; ?>').innerHTML = '<?php echo $user." Visit!"; ?>';
}
});
</script>
This can probably be written directly to the dom too, without passing it through javascript. Saves a lot of overhead and complication. Not trying to be a jerk, just giving friendly advice.
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.