I'm wanting to echo some code based on whether the user is on a mobile device (less than 768px) or larger.
I have done the following:
<?php
if ( is_home() ) {
?>
<script type="text/javascript">
if ($(window).width() < 768) {
document.write("<?php echo my_shortcode("[mobile-slider]"); ?>");
} else {
document.write("<?php echo my_shortcode("[desktop-slider]"); ?>");
}
</script>
<?php
} else {
//do the stuff for the other pages
} ?>
But now when the homepage renders it displays "); } else { document.write(" then the homepage slider and then "); }. Any idea why?
JS error
SyntaxError: unterminated string literal
document.write('
HTML Output - Seems to be adding a line break which I think is breaking the script?
<script type="text/javascript">
if ($(window).width() < 768) {
document.write("
<!--slider-->
"<?php echo my_shortcode("[mobile-slider]"); ?>"
CHANGE TO
"<?php echo my_shortcode('[mobile-slider]'); ?>"
^ ^ // changed quotes here
or escape quotes
"<?php echo my_shortcode(\"[mobile-slider]\"); ?>"
try this:
document.write(<?php echo "\"[mobile-slider]\""; ?>);
Well your quotes are definately off, as others have mentioned, your inner quotes must be different from the outer ones, or escaped.
Is it possible for you to run your php function in the main document(outside of the javascript), then choose to show/hide/alter its contents with the javascript?
If that's not possible, try calling your function directly, instead of through the do_shortcode hook.
As a final alternative, you may need to use an ajax call here. I don't know that you're able to call shortcodes the way you're attempting to do here.
Related
I'd like to print this JS script.
<script src="<?php echo base_url('assets/inspinia/js/jquery-2.1.1.js'); ?>"></script>
<script src="<?php echo base_url('assets/jquery-ui/jquery-ui.js'); ?>"></script>
I write like this:
print("<script type=\'text/javascript\' src=\'".base_url('assets/inspinia/js/jquery-2.1.1.js')."\'></script>");
print("<script type=\'text/javascript\' src=\'".base_url('assets/jquery-ui/jquery-ui.js')."\'></script>");
and this:
echo "<script type=\'text/javascript\' src=\'".base_url('assets/inspinia/js/jquery-2.1.1.js')."\'></script>";
echo "<script type=\'text/javascript\' src=\'".base_url('assets/jquery-ui/jquery-ui.js')."\"></script>";
But, both method can't get the external JS file.
Note: The html in in a modal
To simplify, I will first give you an example with the url saved as a variable.
$url = base_url('assets/inspinia/js/jquery-2.1.1.js');
echo "<script src='$url'></script>";
You can keep it in the long form if you prefer, but you would need to leave the quotes and concatenate (similar to what you have been doing)
echo "<script src='" . base_url('assets/inspinia/js/jquery-2.1.1.js') . "'></script>";
For that reason, I always prefer to assign it to a variable first so that I can see the separation of "get value" and then "print string including that value"
Here is an example of using javascript in php echo:
<?php
echo '<script>Hello World!</script>';
?>
I'm a bit sorry to see what you mean, is that so?
echo "<script type='text/javascript'>
function getState(){
var cs = ".$state.";
return cs;
}
</script>";
Do you want to introduce JS files in PHP?
You can wrap yourself,and you can refer to YII2's wording, like this:
/**
* 定义按需加载JS方法
* #param $view View
* #param $jsfile
*/
public static
function addScript($view, $jsfile) {
$AssetManager = new AssetManager();
$jsfile = $AssetManager - > getPublishedUrl('#backend/modules/motorcade/assets').$jsfile;
$view - > registerJsFile($jsfile, [motorcadeUIAsset::className(), 'depends' => 'backend\modules\motorcade\assets\motorcadeUIAsset']);
}
Hope it helps you
Try this,
echo "<script src=" '. base_url('assets/inspinia/js/jquery-2.1.1.js') .' "></script>";
I would like to get next element:
<script>
function editMediaInfo(mediaID){
var x = document.getElementById(mediaID);
alert(x.nextElementSibling.id);
}
</script>
<?php
$x = 1;
echo "<ol>";
while($x <= 5)
{
echo "<li id={$x}> item {$x} </li>";
$x++;
?>
<button onclick="editMediaInfo('<?php echo $x; ?>')">Click</button>
<?php
}
echo "</ol>";
?>
When i click it gives me an alert without nothing. I would like to get the id of the next element.
It appears you are using an incorrect Javascript function. Use nextSibling function. Replace nextElementSibling with nextSibling. I provided a sample below.
<script>
function editMediaInfo(mediaID){
var x = document.getElementById(mediaID);
alert(x.nextSibling.id);
}
</script>
Where I found and tried the solution was here. I would recommend using this site for help on Javascript in the future.
Simply Use :
document.getElementById(mediaID).nextElementSibling.nextElementSibling.id
If I pass an hard coded numeric value from php to javascript, all works perfectly. But if i pass the numeric value from a variable, i get an error:
javascript file (gallery.js)
function goto_anchor(id)
{
var anchor = $("#anchor_" + id);
$('html,body').animate({
scrollTop: anchor.offset().top - 20
}, 1200);
}
php file
....
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script src="js/gallery.js" type="text/javascript"></script><?php
$get_cat = 4;
if (isset($get_cat)) { ?>
<script>
$(document).ready(function() {
goto_anchor(4); // this will work PERFECTLY!!!
goto_anchor(<?php echo $get_cat; ?>); // this will NOT work !!!
});
</script><?php
} ?>
I need to pass the $get_cat variable in my php, not the harcoded numeric value. How ??
Thanks
I have such kind of problems before, can not fill
javascriptfunction(<?php echo $phpvirable ?>)
inside javascript function that causes error; Instead , according to your code, can echo it to javascript virable first before using it;
echo '<script> var get_cat = '.$get_cat.'</script>';
into your php
<?php $get_cat = 4; ?>
surely, Your php $get_cat can be captured from such as $_REQUEST['cat'] dynamic value from form submit event towards this page. then u convert it to javascript virable to use in function.
<?php
if(isset($getcat)):
echo '<script> var get_cat = '.$getcat.'</script>';
endif;
?>
// javascript function read predefined javascript virable that confirm work.
// u also avoid using mixed php and javascript statements which looks messy
<script>
$(document).ready(function() {
goto_anchor(get_cat); // this will work then.
});
</script>
First problem
I want to use variable don_settings[don_btn_act] (=checkbox) to define a button action.
IF don_settings[don_btn_act] IS on
THEN -> load checkout
ELSE -> page reload
don_settings[don_btn_act] is definded and it is modified well, so i can turn it on or off. The problem is that I should use it in javascript.
What I have so far:
function reloadpage(){
<?php if(isset($don_config['don_btn_act']) && $don_config['don_btn_act'] =='on') { ?>
window.location.href = 'index.php?route=dcheckout/checkout';
<?php } else { ?>
window.location.reload();
<?php } ?>
}
It is always executing the window.location.reload() function.
Second problem
in the same way i have the variable don_settings[min_amount]. I use it to define the minimum amount of input.
it is defined in php like the previous varible.
But i should use it in javascript part of tpl file, too.
What I have so far:
function validation(){
if(jQuery('#opton').val() == ''){
alert("<?php echo $drop_empty_msg; ?>");
return false;
}
else if(jQuery('#don_amount').val() == '' || jQuery('#don_amount').val() == '0'){
alert("<?php echo $amount_empty; ?>");
jQuery('#don_amount').focus();
return false;
}
else{
return true;
}
}
i use
|| jQuery('#don_amount').val() <= "<?php $don_settings[min_amount]; ?>"
insteed of
|| jQuery('#don_amount').val() == '0'
but it returns false every time
Sorry, I couldn't understand your problem or your intensions. Try correcting your misspelling, your grammar and please take care of beautiful formatted code!
Nonetheless i have some recommendations for writing maintainable code.
Your problem (#1)
If your browser is always executing the window.location.reload(), the problem does not refer to your javascript. It is your server side code which fails. Your following condition seems to be false:
<?php if(isset($don_config['don_btn_act']) && $don_config['don_btn_act'] =='on') { ?>
Don't mix your javascript and php up
First of all, compute your necessary values/conditions:
(Preferably into a seperated file)
<?php
$condition = isset($don_config['don_btn_act']) && $don_config['don_btn_act'] =='on';
?>
Now, you can use it very comfortable and clearly:
function reloadpage() {
var condition = '<?php echo $condition; ?>';
if (condition)
window.location.href = 'index.php?route=dcheckout/checkout';
else
window.location.reload();
}
There are lots of big advantages not to mess up your code.
Also be careful ...
... while injecting code through php to the markup/javascript. Don't offer potential attackers new security holes!
i have referred to this two questions call php page under Javascript function and Go to URL after OK button in alert is pressed. i want to redirect to my index.php after an alert box is called. my alert box is in my else statement. below is my code:
processor.php
if (!empty($name) && !empty($email) && !empty($office_id) && !empty($title) && !empty($var_title) && !empty($var_story) && !empty($var_task) && !empty($var_power) && !empty($var_solve) && !empty($var_result)) {
(some imagecreatefromjpeg code here)
else{
echo '<script type="text/javascript">';
echo 'alert("review your answer")';
echo 'window.location= "index.php"';
echo '</script>';
}
it's not displ ying anything(no alert box and not redirecting). when i delet this part echo 'window.location= "index.php"'; it's showing the alert. but still not redirecting to index.php. hope you can help me with this. please dont mark as duplicate as i have made tose posts as reference. thank you so much for your help.
You're missing semi-colons after your javascript lines. Also, window.location should have .href or .replace etc to redirect - See this post for more information.
echo '<script type="text/javascript">';
echo 'alert("review your answer");';
echo 'window.location.href = "index.php";';
echo '</script>';
For clarity, try leaving PHP tags for this:
?>
<script type="text/javascript">
alert("review your answer");
window.location.href = "index.php";
</script>
<?php
NOTE: semi colons on seperate lines are optional, but encouraged - however as in the comments below, PHP won't break lines in the first example here but will in the second, so semi-colons are required in the first example.
if (window.confirm('Really go to another page?'))
{
alert('message');
window.location = '/some/url';
}
else
{
die();
}
window.location = mypage.href is a direct command for the browser to dump it's contents and start loading up some more. So for better clarification, here's what's happening in your PHP script:
echo '<script type="text/javascript">';
echo 'alert("review your answer");';
echo 'window.location = "index.php";';
echo '</script>';
1) prepare to accept a modification or addition to the current Javascript cache.
2) show the alert
3) dump everything in browser memory and get ready for some more (albeit an older method of loading a new URL
(AND NOTICE that there are no "\n" (new line) indicators between the lines and is therefore causing some havoc in the JS decoder.
Let me suggest that you do this another way..
echo '<script type="text/javascript">\n';
echo 'alert("review your answer");\n';
echo 'document.location.href = "index.php";\n';
echo '</script>\n';
1) prepare to accept a modification or addition to the current Javascript cache.
2) show the alert
3) dump everything in browser memory and get ready for some more (in a better fashion than before) And WOW - it all works because the JS decoder can see that each command is anow a new line.
Best of luck!
Like that, both of the sentences will be executed even before the page has finished loading.
Here is your error, you are missing a ';'
Change:
echo 'alert("review your answer")';
echo 'window.location= "index.php"';
To:
echo 'alert("review your answer");';
echo 'window.location= "index.php";';
Then a suggestion:
You really should trigger that logic after some event. So, for instance:
document.getElementById("myBtn").onclick=function(){
alert("review your answer");
window.location= "index.php";
};
Another suggestion, use jQuery
Working example in php.
First Alert then Redirect works.... Enjoy...
echo "<script>";
echo " alert('Import has successfully Done.');
window.location.href='".site_url('home')."';
</script>";
<head>
<script>
function myFunction() {
var x;
var r = confirm("Do you want to clear data?");
if (r == true) {
x = "Your Data is Cleared";
window.location.href = "firstpage.php";
}
else {
x = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = x;
}
</script>
</head>
<body>
<button onclick="myFunction()">Retest</button>
<p id="demo"></p>
</body>
</html>
This will redirect to new php page.