How to output PHP inside JS/jQuery that generates HTML? [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 months ago.
Improve this question
I have to run a PHP action that is inside HTML which is inside a JS script. The current code does an error because the function that renders HTML breaks the syntax. I am getting Uncaught SyntaxError: Unexpected token '='
Here is my code example:
<script type="text/javascript">
(function($) {
$('.menu-main').on('click', function() {
var page = window.location.href;
var mobile = $('.menu-item-mobile');
var search = '<div class="wpml-language-switcher">'<?php do_action('wpml_add_language_selector'); ?>'</div>';
setTimeout(function() {
if(mobile.find('form').length == 1) return;
mobile.html(search);
}, 50); //delay time
});
})(jQuery);
</script>
Here is the output with failed structure in line 8 (Uncaught SyntaxError: Unexpected token '='):
<script type="text/javascript">
(function($) {
$('.av-burger-menu-main').on('click', function() {
var page = window.location.href;
var mobile = $('.menu-item-search-mobile');
var search = '<div class="wpml-floating-language-switcher">'
<div
class="wpml-ls-statics-shortcode_actions wpml-ls wpml-ls-legacy-dropdown js-wpml-ls-legacy-dropdown" id="lang_sel">
<ul>
<li tabindex="0" class="wpml-ls-slot-shortcode_actions wpml-ls-item wpml-ls-item-lv wpml-ls-current-language wpml-ls-first-item wpml-ls-item-legacy-dropdown">
<a href="#" class="js-wpml-ls-item-toggle wpml-ls-item-toggle lang_sel_sel icl-lv">
<img
class="wpml-ls-flag iclflag"
src="https://sampledomain.com/wp-content/plugins/sitepress-multilingual-cms/res/flags/lv.png"
alt=""
width=18
height=12
/><span class="wpml-ls-native icl_lang_sel_native">LV</span></a>
<ul class="wpml-ls-sub-menu">
<li class="icl-en wpml-ls-slot-shortcode_actions wpml-ls-item wpml-ls-item-en">
<a href="https://sampledomain.com/en/" class="wpml-ls-link">
<img
class="wpml-ls-flag iclflag"
src="https://sampledomain.com/wp-content/plugins/sitepress-multilingual-cms/res/flags/en.png"
alt=""
width=18
height=12
/><span class="wpml-ls-native icl_lang_sel_native" lang="en">EN</span></a>
</li>
<li class="icl-ru wpml-ls-slot-shortcode_actions wpml-ls-item wpml-ls-item-ru wpml-ls-last-item">
<a href="https://sampledomain.com/ru/" class="wpml-ls-link">
<img
class="wpml-ls-flag iclflag"
src="https://sampledomain.com/wp-content/plugins/sitepress-multilingual-cms/res/flags/ru.png"
alt=""
width=18
height=12
/><span class="wpml-ls-native icl_lang_sel_native" lang="ru">RU</span></a>
</li>
</ul>
</li>
</ul>
</div>
'</div>';
setTimeout(function() {
if(mobile.find('form').length == 1) return;
mobile.html(search);
}, 50); //delay time
});
})(jQuery);
</script>
Is there anything possible to avoid the syntax error?

If I were you I'd put the PHP contents into a template tag and grab the contents with jQuery. For example...
<script type="text/template" id="template-wpml_add_language_selector">
<?php do_action('wpml_add_language_selector'); ?>
</script>
<script type="text/javascript">
(function($) {
$('.menu-main').on('click', function() {
var templateContents = $('#template-wpml_add_language_selector').html();
var page = window.location.href;
var mobile = $('.menu-item-mobile');
var search = '<div class="wpml-language-switcher">' + templateContents + '</div>';
setTimeout(function() {
if(mobile.find('form').length == 1) return;
mobile.html(search);
}, 50); //delay time
});
})(jQuery);
</script>

Related

Apache Velocity and adding JavaScript

Please forgive me as I've never used Apache Velocity before but I have to figure this out!
I'm using an adobe recommendation template for products and I'm now adding a star rating system into it as noted in the image below:
However, as you can see the logic i have added (In JS) is only being executed the first time. and obviously not running through the loop, since it is in Velocity.
My question to the community is; how do i go about making this work?
I've tried for a day now to no avail, so ANY help would be greatly appreciated.
Please see the code below! (And thanks!)
[The #foreach loops is the velocity, and everything between the script tags is my appended code]
<div class="line">
<h2>More for You</h2>
#set($count=1)
#foreach($e in $entities)
#if($e.id != "" && $count < $entities.size() && $count <=18)
<li>
<script type="text/javascript">
var myString = $e.rating;
if (myString >= 5) { myString = 5;}
var myRegexp2 = /\d(?!.*\d)/;
var match2 = myRegexp2.exec(myString);
var starIMG = "<img src='http://kirklands.ugc.bazaarvoice.com/3768-en_us/" + match + "_" + match2 + "/5/rating.gif' alt='' />";
var myRegexp3 = /\d/;
var match = myRegexp3.exec(myString);
function myFunction() {
return(match);
}
</script>
<a class="productBlock" onclick="var s = s_gi(s_account);
s.linkTrackVars='events,eVar21';
s.linkTrackEvents='event16';
s.events='event16';
s.eVar21='';
s.tl(this,'o','Product Detail Cross-Sell');" href="$e.pageUrl?icid=hpFS ">
<img title="$e.name" alt="$e.name" src="$e.thumbnailUrl">
<h3>$e.name</h3>
<div id="starRating"><script>document.getElementById("starRating").innerHTML =
starIMG;</script></div>
<p>$$e.value</p>
</a>
</li>
#set($count = $count + 1)
#end
#end
</ul>
</div>
<div class="scroolBtn btnRight"><span class="btn" id="scrool-forward"></span></div>
</div>
jQuery(function () {
jQuery('#scrool').scrollbox({
direction: 'h',
switchItems: 3,
distance: 450,
autoPlay:false
});
jQuery('#scrool-backward').click(function () {
jQuery('#scrool').trigger('backward');
});
jQuery('#scrool-forward').click(function () {
jQuery('#scrool').trigger('forward');
});
});
I have not used Velocity template scripts for years but wild guess is an escaping problem. Everything you include in a velocity template is actually run by Velocity engine, you must escape $variable literals.
http://velocity.apache.org/engine/devel/user-guide.html#escapingvalidvtlreferences
edit No wait, you mean you wanted to run javascript code at server side, each foreach item step should evaluate javascript code?

JQuery won't call on image click [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
So I've created a jquery call to check if an image in a series of images with the same account name: .account-img, are clicked.
I load the images through PHP like so:
<?php
foreach($accountsArray as &$acc) {
echo ('
<!--<div class="col-md-2 col-sm-6">-->
<img class="img-thumbnail account-img" src="https://twitter.com/'.$acc['screen_name'].'/profile_image?size=original" alt="Profile Image" id="img-'.$acc['screen_name'].'" />
<!--</div>-->
');
}
?>
Shorthand for the image is as follows:
<img class="img-thumbnail account-img" src="https://twitter.com/BBCNews/profile_image?size=original" alt="Profile Image" id="img-BBCNews" />
Here is the JQuery i use to call the image clicks:
$('.account-img').each(function() {
var id = $(this).attr('id').split('-');
var name = id[1];
$(this).on('click', function() {
alert(name);
});
});
EDIT:
It won't be a single element because of the PHP code i'm actually using. it will be multiple elements and i want to perform an action based on each individual image. But because my ID isn't known beforehand, I need to do it this way
You have to user click trigger for that as below code.... And for get current image click you use this inside click trigger....
$('.account-img').click(function(){
alert($(this).attr("id"));
});
There would be no reason to foreach the element if you're going to add a click handler on it. Removing the foreach would be enough.
$(document).ready(function () {
$('.account-img').on('click', function() {
var id = $(this).attr('id').split('-');
var name = id[1];
console.log(name);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="img-thumbnail account-img" src="https://twitter.com/BBCNews/profile_image?size=original" alt="Profile Image" id="img-BBCNews" />
try this:
$(document).ready(function(){
$('.account-img').each(function() {
var id = $('#img-BBCNews').attr('id').split('-');
var name = id[1];
$('#img-BBCNews').on('click', function() {
alert(name);
});
});
});

Change text size on visited links [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How to change text size of the link when people visits it?
It is possible to change link text size when like 1000 visitors from a different IP address clicks on it? Currently i have a page with a lot of links and I need to separate them with different text size so users can see the most important links. ( It's like keywoard function).
Here is some examples:
//SQL
CREATE TABLE keywords (
keyword_id int(11) NOT NULL AUTO_INCREMENT,
keyword varchar(200) NOT NULL,
keyword_count int(5) NOT NULL,
PRIMARY KEY(keyword_id)
)
//PHP
<?php
//Write your select query here
while($row = $result->fetch())
{
switch($row['count']) {
//Add more cases if you want
case 10:
echo "<span class='row-count-10'><a href='lol.php?keywordid=".$row['keyword_id']."'>".$row['keyword']."</a></span>";
break;
default:
echo "<span class='row-count-default'><a href='lol.php?keywordid=".$row['keyword_id']."'>".$row['keyword']."</a></span>";
}
}
?>
<?php
//lol.php
$keyword = $_GET['keywordid'];
//INSERT STATEMENT
?>
//style.css
.row-count-default {
font-size:10px;
}
.row-count-10 {
font-size:12px;
}
Parse visits on server side and pass metrics to view as JSON
Adjust links on page load with javascript "for loop"
See it here: FIDDLE
Javascript:
var json = JSON.parse('{"link_1":2,"link_2":3,"link_3":7,"link_4":2}');
var base_size = 12;
for (var link in json){
document.getElementById(link).setAttribute("style","font-size:" + (json[link] * base_size) + "px;");
//alert(json[link]);
}
HTML:
<a id="link_1">Link 1</a>
<a id="link_2">Link 2</a>
<a id="link_3">Link 3</a>
<a id="link_4">Link 4</a>
<a id="link_5">Link 1</a>

Need Help: Make the quiz random [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm having trouble making the questions random. If you could help, it would be awesome!
(If you have spear time; I've been given the task to mark correct answer with a green feather and wrong answers with red feather, for instance, if you get 3 correct and 2 wrong. It will show 3 green feathers and 2 red feathers as score.) Thank you!
<script type="text/javascript">
var questions = [
['firstcar.gif','0'],
['secondcar.gif','1'],
['thirdcar.gif','2'],
['firstcar.gif','0'],
['secondcar.gif','1'],
['thirdcar.gif','2'] // Note: no comma after last entry
];
var qNo = 0;
var correct = 0;
var cnt = 0;
function NextQuestion(response) {
if ((qNo < questions.length) && (response == questions[qNo][1])) {
correct++;
}
document.getElementById('score').innerHTML = 'Correct ' + correct + ' of 6 questions';
qNo++;
if (qNo < questions.length) {
document.getElementById('Pic').src = questions[qNo][0];
cnt++;
}else{
alert('Quiz is done. You got ' + correct + ' points!');
}
}
onload = function() {
document.getElementById('Pic').src = questions[0][0];
}
</script>
</head>
<body>
<div align="center">
<h1>Which car is it?</h1>
<img src="" id="Pic" height="200" width="250">
<p>Is it
<button onclick="NextQuestion('0')">Red</button>
<button onclick="NextQuestion('1')">Black</button>
<button onclick="NextQuestion('2')">Yellow</button>
<p>Your score: <br>
<span id="score"></span>
</div>
</body>
</html>
Well, your questions are in an array. So what you should be researching is how to randomise the order of an array.
questions.sort(function() { return Math.floor(Math.random() * 2); });

How short can this script be and still achieve the same thing - display a message "loading.." followed by an extra period every 1 second for 7 seconds [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
<script>
var dot = ".";
var counter = 0;
var message = "Loading Page";
function writeLoadingMessage(){
if (counter > 6) return;
setTimeout('writeMessage();',1000);
}
function writeMessage(){
document.getElementById('loadingMessageSpan').innerHTML = message + dot;
message += dot
counter++
writeLoadingMessage();
}
</script>
<BODY>
<span style="font-weight:bold;" id="loadingMessageSpan"></span>
<SCRIPT>writeLoadingMessage();</SCRIPT>
</BODY>
(function(){var i=6,a=setInterval(function(){document.getElementById('loadingMessageSpan').innerHTML+=".";!i--&&clearInterval(a);},1E3)})()
You will need to have Loading already in your span tag. As a note it is pointless to worry about getting it this small though. Also, the page will will have to be already loaded.
If you want it shorter: http://jsfiddle.net/pimvdb/wBFSy/.
<script>
var counter = 0;
function writeMessage() {
document.getElementById('loadingMessageSpan').innerHTML += ".";
if(++counter < 7) {
setTimeout(writeMessage, 1000);
}
}
window.onload = writeMessage;
</script>
<body>
<span style="font-weight:bold;" id="loadingMessageSpan">Loading Page</span>
</body>
Minifying also helps :)
var a=0;function b(){document.getElementById("loadingMessageSpan").innerHTML+=".";++a<7&&setTimeout(b,1E3)}window.onload=b
1) User setInterval instead.
2) Just set the message once and append . to end
3) Put all the js at the bottom
<body>
<span style="font-weight:bold;" id="loadingMessageSpan">Loading Page</span>
<script type="text/javascript">
var counter = 0;
var id = setInterval(function(){
document.getElementById('loadingMessageSpan').innerHTML += ".";
if(++counter>6) {
clearInterval(id);
}
}, 1000);
</script>
</body>
If you really want it short you can go this route:
<BODY>
<span style="font-weight:bold;" id="loadingMessageSpan">Loading Page</span>
<script>
var counter = 0;
var interval = setInterval(function(){
document.getElementById('loadingMessageSpan').innerHTML += ".";
if(++counter > 6)
clearInterval(interval);
},1000)
</script>
</BODY>
http://jsfiddle.net/kc3fb/2/

Categories