Combining PHP into a Javascript? - javascript

Basically I'm struggling adding PHP into
<a style="cursor:pointer;" onClick="location.href='https://www.example.com/go/'">LINK</a>
My code right now:
<a style="cursor:pointer;" onClick="location.href='https://www.example.com/go/
<?php $randomid = rand(361, 370);
echo '' . $randomid . '&name=john'; ?>
'">Link</a>
But the above doesn't work. When you click, nothing happens.
I have also tried this way:
<?php $randomid = rand(361, 370);
echo '<a style="cursor:pointer;" onClick="location.href='https://www.example.com/go/' . $randomid . '&name=john'">Link</a>'; ?>
But since the javascript contains '' they confict with PHP's html code ''.
How do I solve this?

So ... :) like this - you either use href or use a function onclick... not supposed to be together but this will work:
$randomid = rand(361, 370);?>
Link
From what I read in the comments you are looking for a js function... not an a href link eh?
So how about this:
<?php
$randomid = rand(361, 370);?>
<a onclick="myFunction('<?php echo $randomid;?>');" style="cursor:pointer;">Link</a>
<script type="text/javascript">
function myFunction(randomid){
window.location.assign("https://www.example.com/go/"+randomid+"&name=john");
}
</script>

Either you can use this one it's also working.
<?php
$randomid = rand(361, 370);
echo '<a style="cursor:pointer;" href="https://www.example.com/go/'.$randomid.'&name=john">Link</a>';
?>

Related

Displaying images using for loop on PHP

I am trying to display my images in a for loop in the form tag using PHP but it does not seem to work. I have also tried doing a return statement but nothing still appears.
<?php
$data = array("images/architecture-57e8d34a48_640.jpg",
"images/gateway-arch-57e2d64548_640.jpg",
"images/horseshoe-bend-57e6d6434f_640.jpg",
"images/lake-irene-57e6d24a4d_640.jpg",
"images/silhouette-57e8d5444e_640.jpg");
function displayCheckboxes(){
for ($i=0; $i<count($data); $i++) {
echo "<img src='".$data[$i] . "<br>";
}
}
?>
<body>
<main id ="main">
<form id="pics" action="process.php" method="get">
<label>Name: </label>
<?php echo displayCheckboxes();?>
</form>
</main>
</body>
Maybe Like This:
<?php
$data = array("images/architecture-57e8d34a48_640.jpg",
"images/gateway-arch-57e2d64548_640.jpg",
"images/horseshoe-bend-57e6d6434f_640.jpg",
"images/lake-irene-57e6d24a4d_640.jpg",
"images/silhouette-57e8d5444e_640.jpg");
function displayCheckboxes(){
global $data;
for ($i=0; $i<count($data); $i++) {
echo "<img src='".$data[$i]."'>" . "<br>";
}
}
displayCheckboxes();
?>
function displayCheckboxes($img_array){
foreach($img_array as $img) {
echo "<img src='".$img."'>'" . "<br>";
}
}
and
echo displayCheckboxes($data);
There is several errors with your function :
- $data is not inside the function
- .jpg is already in the image name.
this should work,call the function with $data
$data = array("images/architecture-57e8d34a48_640.jpg",
"images/gateway-arch-57e2d64548_640.jpg",
"images/horseshoe-bend-57e6d6434f_640.jpg",
"images/lake-irene-57e6d24a4d_640.jpg",
"images/silhouette-57e8d5444e_640.jpg");
/* Write your displayCheckboxes() function here */
displayCheckboxes($data);
function displayCheckboxes($data){
for ($i=0; $i<count($data); $i++) {
echo "<img src='".$data[$i]."'.jpg>'" . "<br>";
}
}
?>
<?php
$data = array(
"images/architecture-57e8d34a48_640.jpg",
"images/gateway-arch-57e2d64548_640.jpg",
"images/horseshoe-bend-57e6d6434f_640.jpg",
"images/lake-irene-57e6d24a4d_640.jpg",
"images/silhouette-57e8d5444e_640.jpg"
);
?>
<body>
<main id ="main">
<form id="pics" action="process.php" method="get">
<label>Name: </label>
<?php foreach($data as $image): ?>
<img src="<?= $image; ?>"></br>
<?php endforeach; ?>
</form>
</main>
</body>
This is an alternative way. Looks much cleaner and readable. And I actually don't think we need a function for printing HTML.
I would say NEVER put HTML inside PHP echo unless it is compulsory. The reason I am stating this is if you put HTML inside PHP, the code becomes easily messy. It becomes hard to understand the logic unless you are the one who coded. Particularly, if you are working with some designers or in future, they will have a hard time making even little changes.
Even I think using <?= than <?php echo is better.
You are trying to give an extension ".jpg" of the images that you previously gave to it in the path of images in the array "$data".
For exemple:We will take the first element in the array $data with index = 0 "$data[0]" (images/architecture-57e8d34a48_640.jpg):
In PHP looks like -> echo "<img src='".$data[0]."jpg'>" . "<br>";
,but in HTML looks like -> <img src='images/architecture-57e8d34a48_640.jpg.jpg'>
You shold have to delete the extension ".jpg" from your echo to seem like:
echo "<img src='".$data[$i]."'>" . "<br>";

javascript - don't add class for specific css class

I'm working with a template in Wordpress that someone else set up and I need to fix something.
There is a javascript function that adds a class to every css class that's called object-fit - the added class is called bg--image. This was to fix an error showing up in IE11 , where all the images where messed up.
The problem now is that there's a page where this function shouldn't apply even though the css class is also called object-fit.
I'm a little confused on how to work here. As I don't want to mess up the whole theme and my coding options are quite limited, it just makes a knot in my brain.
Is there any possibility I can add a javascript function to not apply the IE 11 function on this one specific class? the difference is that the one img where it shouldn't apply is a span, the other one is not.
Any ideas?
try {
if (ie_ver() == 11) {
var $img = $('.banner--small').find('img');
$('.banner--small').attr('style', 'background-image:url(' + $img.attr('src') + ')');
$('.banner--small').addClass('bg--image');
$img.addClass('hidden');
var $img2 = $('.object-fit').find('img');
$('.object-fit').attr('style', 'background-image:url(' + $img2.attr('src') + ')');
$('.object-fit').addClass('bg--image');
$img2.addClass('hidden');
$('.slick__inner').each(function() {
var $img3 = $(this).find('img');
$(this).attr('style', 'background-image:url(' + $img3.attr('src') + ')');
$(this).addClass('bg--image');
$img3.attr('style', 'display:none');
});
<div class="article--text">
<div class="container container--tiny spacing--huge">
<?php the_content(); ?>
</div>
<div class="container margin-bottom--huge">
<?php if (get_field('direktionen')) { ?>
<div class="flex flex--wrap flexgrid--gutter flexgrid--normal">
<?php foreach (get_field('direktionen') as $key => $child) { ?>
<div class="flex__item one-third lg-one-half xs-one-whole">
<a href="<?php echo $child['link']; ?>" class="link--direction text--center margin-bottom--medium" target="_blank">
<span class="object-fit"><img src="<?php echo $child['photo']['sizes']['medium']; ?>"
srcset="<?php echo $child['photo']['sizes']['mobile']; ?> 2x,<?php echo $child['photo']['sizes']['medium']; ?> 1x"
alt="<?php echo $child['name']; ?>" /></span>
<h3>
<?php echo $child['name']; ?>
</h3>
<p>
<?php echo $child['adresse']; ?>
</p>
</a>
</div>
<?php } ?>
</div>
<?php } else if ($children) { ?>
<div class="flex flex--wrap flexgrid--gutter flexgrid--normal">
<?php foreach ($children as $key => $child) { ?>
<div class="flex__item one-third lg-one-half xs-one-whole">
<a href="<?php echo get_permalink($child->ID); ?>" class="link--direction text--center margin-bottom--medium">
<span class="object-fit"><img src="<?php echo get_the_post_thumbnail_url($child->ID, 'medium'); ?>"
srcset="<?php echo get_the_post_thumbnail_url($child->ID, 'mobile'); ?> 2x,<?php echo get_the_post_thumbnail_url($child->ID, 'medium'); ?> 1x"
alt="<?php echo $child->post_title; ?>" /></span>
<h3>
<?php echo $child->post_title; ?>
</h3>
<p>
<?php echo get_field('adresse', $child->ID); ?>
</p>
</a>
</div>
<?php } ?>
</div>
<?php } ?>
</div>
</div>
Since this is a WordPress template, you have a couple of solutions.
Solution 1 - HTML & jQuery modification
If you can add an additional class to only this page's HTML, then applying the following updates to this page template should allow you to avoid having the .bg--image class added to just this page:
HTML
<span class="object-fit avoid-change">
jQuery
$('.object-fit').not( '.avoid-change' ).addClass('bg--image');
More info on jQuery's .not() method:
https://api.jquery.com/not/
Solution 2 - WordPress Conditional
Another option is to use a WordPress conditional to avoid running the entire script on this page.
You could use the following to prevent the script from loading in this template:
<?php if(! is_page_template( 'your-template-name.php' )){ ?>
// place your script or wp_enqueue_script() code here
<?php } ?>
You could also target an exact page by its page ID. In this example, your page ID would be 7.
<?php if(! is_page( '7' )){ ?>
// place your script or wp_enqueue_script() code here
<?php } ?>
More info on WordPress conditionals:
https://codex.wordpress.org/Conditional_Tags

Using a PHP variable as a variable in jQuery

I'm having a hard time understanding how to import a specific variable for use with jQuery.
Some links on a Wordpress theme are using
<?php if( get_post_meta($post->ID, "portfolio_link", true) ): ?>
<h1 class="portfolio-title">
<a target="_blank" href="<?php the_field('portfolio_link'); ?>">
<?php the_field('portfolio_title'); ?> <span class="sosa-icon">p</span>
</a>
</h1>
<!--get PDF if not empty-->
<?php else: ?>
<h1 class="portfolio-title"><?php the_field('portfolio_title'); ?></h1>
<?php endif; ?>
As you can see the href is set as
href="<?php the_field('portfolio_link'); ?>"
Now I have a jQuery script as follows
<script>
<?php if( get_post_meta($post->ID, "portfolio_link", true) ): ?>
<?php
$phpVar = 'http://www.google.com';
echo "var phpVariable = '{$phpVar}';";
?>
jQuery(".box").click(function() {
window.open(phpVariable);
});
<?php endif; ?>
</script>
This script currently works. It opens google in a new tab as a placeholder until I know how to make it open the same result as the href.
Now what I can't understand is how to set '$phpVar' to have the same effect as the 'href' I showed before instead of 'http://www.google.com';
Not sure just how the WordPress handling of this is, but given that the_field('portfolio_title'); returns a valid URL, you can simply assign the JavaScript variable the output of this variable.
var phpVariable = "<?php the_field('portfolio_link'); ?>";

Remove part of url in specific class

I am using a module for joomla called RokMiniEvents but there is a problem, once you use the navigation it adds a path to the events url: "/modules/mod_rokminievents3"..
Let's say the working url is this:
<a class="rme-title" href="/td/index.php/component/jevents/icalrepeat.detail/2014/07/22title=proto-seminario/0/-/-?rp_id=2&Itemid=0">Event name</a>
But once you use the Navigation it becomes:
<a class="rme-title" href="/td/modules/mod_rokminievents3/index.php/component/jevents/icalrepeat.detail/2014/07/22title=/0/-/-?rp_id=2&Itemid=0">Πρωτο Σεμιναριο</a>
I would like to use something like:
where a with class="rme-title" replace the /mod_rokminievents3 with nothing..
Is that possible with javascript or any other language ? I've seen a lot of answers here but without the class selection..
Select the elements and replace that part of the href with nothing using String.replace
$('a.rme-title').attr('href', function(_, href) {
return href.replace('/mod_rokminievents3','');
});
Hi I had same problem with this module, this is my solution:
In modules/mod_rokminievents3/tmpl open default_item.php
search the code:
<?php if (!$event->getLink()): ?>
<span class="rme-title"><?php echo $event->getTitle(); ?></span>
<?php else: ?>
<?php
$values = $event->getLink();
$internal = $values['internal'];
$link = $values['link'];
?>
<a class="rme-title<?php echo $internal ? '' : ' rme-external-link'; ?>" href="<?php echo $link ?>"><?php echo $event->getTitle(); ?></a>
<?php endif; ?>
finally get $link value and replace "modules/mod_rokminievents3/" by "" here is the final code:
<?php if (!$event->getLink()): ?>
<span class="rme-title"><?php echo $event->getTitle(); ?></span>
<?php else: ?>
<?php
$values = $event->getLink();
$internal = $values['internal'];
$link = $values['link'];
$link=str_replace ("modules/mod_rokminievents3/" ,"" , $link );
?>
<a class="rme-title<?php echo $internal ? '' : ' rme-external-link'; ?>" href="<?php echo $link ?>"><?php echo $event->getTitle(); ?></a>
<?php endif; ?>
This works for me.

how to pass the variables through a javascript function when it is written inside the php echo statement

how to pass the variables through a javascript function when it is written inside the php echo statement .
here my code
problem with quotes
echo '<a style="color:green" href="javascript:void(0)" onclick="javascript:chatWith('$u_code','$u_name')" >'.$u_name.'</a>';
The cleanest option by using \DOMDocument:
<?php
$dom = new DOMDocument;
$e = $dom->createElement('a', $u_name);
$a = $dom->appendChild($e);
$a->setAttribute('style', 'color: green;');
$a->setAttribute('href', 'javascript:void(0);');
$a->setAttribute('onclick', 'chatWith("' . $u_code . '","' . $u_name . '");');
echo $dom->saveHTML();
You need to escape those quotes:
echo '<a style="color:green" href="javascript:void(0)" onclick="javascript:chatWith(\''.$u_code.'\',\''.$u_name.'\')" >'.$u_name.'</a>';
You need to append your php variables with "." and escape quotes
echo '<a style="color:green" href="javascript:void(0)" onclick="javascript:chatWith(\''.$u_code.'\',\''.$u_name.'\')" >'.$u_name.'</a>';
echo '<a style="color:green" href="javascript:void(0)" onclick="javascript:chatWith('.$u_code.','.$u_name.')" >'.$u_name.'</a>';
Fix the quotes
echo '<a style="color:green" href="javascript:void(0)" onclick="javascript:chatWith(\''.$u_code.'\',\''.$u_name.'\')" >'.$u_name.'</a>';
echo "<a style=\"color:green\"
href=\"javascript:void(0)\"
onclick=\"javascript:chatWith('".$u_code."','".$u_name."')\"
>'.$u_name.'</a>";
Escape the quotes in your statement.
echo '<a style="color:green" href="javascript:void(0)" onclick="javascript:chatWith(\''.$u_code.'\',\''.$u_name.'\')" >'.$u_name.'</a>';
Sometimes, we should just close PHP, improves readability AND you don't get stuck in nested quotes.
?>
<a style="color: green"
href="javascript: void(0);"
onclick="javascript: chatWith('<?php echo $u_code; ?>','<?php echo $u_name; ?>');">
<?php echo $u_name; ?>
</a>
<?php
You can do this, which is cleaner
$link = '<a onclick="javascript:chatWith({ucode},{uname})" style="color:green" href="javascript:void(0)">{anchor}</a>';
$link = str_replace(
$q = "'";
array('{ucode}', '{uname}', '{anchor}'),
array($q.$u_code.$q, $q.$u_name.$q, $uname),
$link
);
echo $link;
use this
echo '<a style="color:green" href="javascript:void(0)" onclick="javascript:chatWith('.$u_code.','.$u_name.')" >'.$u_name.'</a>';
Your formatting seems to be off.
echo '<a style="color:green" href="javascript:void(0)" onclick="javascript:chatWith(\''.$u_code.'\',\''.$u_name.'\')" >'.$u_name.'</a>';
the . is used to append variables to a string in PHP, since you are using single quotes you'll have to escape the string every time you insert a variable.
Hope this helped.
&dash; Sid

Categories

Resources