How to call a custom JavaScript alert box from php - javascript

I have the following code.
echo '<script language="javascript">';
echo 'alert("This is a popup box")';
echo '</script>';
This works fine as intended. However, I would like to use a custom and aesthetically pleasing pop-up box. So I went online and saw some nice JS libraries such as Alertify, BootBox and a few others. I included the JS scripts (JQuery,Boostrap, library scripts) and their CSS files on the top of the PHP file. Now I use the same method as previously.
echo '<script language="javascript">';
echo ' alertify.alert("This is the default alert!")';
echo '</script>';
For some reason this never works, I get the following error. Can anyone tell what I may be doing wrong, or what is the correct way to achieve this?

You need to wait for the DOM to load all the files (in this case your external script) - try this:
echo '<script language="javascript">';
echo 'document.addEventListener("DOMContentLoaded", function() {';
echo ' alertify.alert("This is the default alert!")';
echo '});';
echo '</script>';

You can as well ensure you are loading the CSS and JavaScript files in the following Order. I never have issue following this order.
I.) CSS First
BootStrap CSS
Other Vendor CSS
Your custom CSS
II.) JavaScript second
jQuery Js
BootStrap Js
Other Vendor Js
Your Custom Js

Related

Adding widget to WordPress frontpage

I created a website in WordPress (Website: Link) using this theme.
I would like to know, how can I add a [timeline-express] widget after the image slider?
(I tried to modify idyllic-functions.php, using:
...
</div> <!-- end .main-slider -->';
echo $idyllic_category_sliders_display;
echo add_filter( 'widget_text', 'timeline-express');
...
,but the site crashes.)
Open this file: idyllic/inc/front-page/front-page-features.php and add this following line on line 34:
<?php echo do_shortcode('[timeline-express]'); ?>
Just above this line:
<div class="our-feature-box <?php echo esc_attr($feature_box_class); ?>">
So, your updated code will be also follows:
<?php echo do_shortcode('[timeline-express]'); ?>
<div class="our-feature-box <?php echo esc_attr($feature_box_class); ?>">
Note that, it's always a good practice to create a child theme, copy file/template to the child theme directory, and then modify your codes. Otherwise, you will lose your modified codes once the theme is updated.
PS: please try to follow what #tacoshy mentioned in his comment while asking questions in stackoverflow.

How to reuse same mixed code snippets by both PHP and JS? Best practice?

I'm just starting to learn JavaScript and PHP and am having troubles with this seemingly simple problem - how do I code reusable HTML snippets so they can be used both for JS and PHP?
Here's a case example - I have a simple .php page like this:
<body> <?php
foreach( $members_array as $member ) {
$id = $member->id;
$name = $member->name;
$img = $member->get_img();
include( 'single-member.php' );
}
foreach( $other_members_array as $member ) {
$id = $member->id;
$name = $member->name; ?>
<button type="button" onclick="addExtraMember" data-user-id="<?= $id? >">ADD <?= $name ?></button> <?php
}
</body>
Where for each member in the array a html code is dynamically generated with the variables. The 'single-member.php' is this:
<div id="<?= $id ?>">
<img src="<?= $img ?>">
<p><?= $name ?></p>
</div>
Then when the page finishes loading all the members are listed. The user of the page can click on one of the $other_members_array buttons that calls a JavaScript function. This JavaScript function should add the same code as 'single-member.php' after the last 'single-member.php' element to keep with visual consistency and in case I need to change the structure and styling of the snippet it's only in one file. I was googling this all afternoon today and here are my basic solutions:
rename the file to .html then load() and replace the attributes and text fields in JS
via .php page include one extra 'single-member.php' with empty values, a unique id and without displaying it so JS could grab it from the HTML DOM for re-use (in case the $members_array is empty)
don't load the members via PHP, add them all with JS when the page finishes loading using a reworked 'single-member.html' snippet without the PHP variables. So when a button is pressed JS function can use the 'single-member.html' again
I have a feeling this is a common problem - reusing elements and snippets between JS and PHP so I was wondering what the best practice is?
Also am I missing some more elegant library or solution?

including html tag in a php code, specifically dealing with href function inside a php block

enter the html code once a condition is satisfied but then i aim to use php values and html tags together.
tried tag etc and got most of the part in running just unable to deal with href beacuse it is referencing to some values.
not sure where to use "" or ``.
<?php.....
echo `Yes`;
?>
"yes" should work as a hyperlink but at the moment the php values are not processed that`s why no result.
You are using wrong sequence of quote
<?php
...
?>
<?php
echo '<a href="limitdatabase.php?Dropdown=' .
$_GET['Dropdown'].
';&search='.
$search_name .
';&wise='.
$_GET['wise'].
';">Yes</a>';
?>
and you should use single quote and not backtics for string
You are using incorrect concatenation. Whenever you want to add any PHP variable then you need to close the braces and need to start after PHP variable as below:
<?php
echo 'Yes';
?>
Also you should wrap Dropdown and wise in braces as it will not work directly in get as you have used. Hope it helps you!
You can use combination of html with php inside:
<a href="limitdatabase.php?Dropdown=<?PHP echo $_GET[Dropdown] . "&search="
. $search_name . "&wise=" . $_GET[wise]; ?>">Yes</a>
Also, you can input whole link in string:
<?php
$mylink = "limitdatabase.php?Dropdown=" . $_GET[Dropdown] . "&search=" . $search_name . "&wise=" . $_GET[wise];
?>
YES

wordpress custom html widget with PHP

I'm trying to add a php code inside a custom HTML widget but the site in showing this like plain text.
Any idea why is this happening?
PHP CODE:
<?php
$param = uniqid();
echo "<script language='javascript'>";
echo "alert('message successfully sent ' . $param)";
echo "</script>";
?>
HTML:
HOW I SEE THE PAGE:
Same problem happenned to me today!!, resolved it by adding the following code to the Wordpress theme function.php file.
add_filter('widget_text','execute_php',100);
function execute_php($html){
if(strpos($html,"<"."?php")!==false){
ob_start();
eval("?".">".$html);
$html=ob_get_contents();
ob_end_clean();
}
return $html;
}
To enable shortcodes in the Text and Custom HTML widget just add this code to your theme functions.php :
add_filter('widget_text','do_shortcode',10);

How would I call a java script function using php if statement with $_SESSION

Hi I am creating a website with a login section this is working I am using HTML and PHP. What I am trying to do is one of my pages has a html button I want this to be disabled for certain users. at the moment this is what I have got.
this is the part that I use for the login details.
<?php
session_start();
$_SESSION["username"];
$_SESSION["password"];
$_SESSION["access"];
?>
I have got if statments that I am currently using which are
if($_SESSION["access"] == "Administrator"){
echo $Admin;
}
what I am trying to do is call a javascript function within a PHP if statement what i have got so far is
<?php
if($_SESSION["access"] == "Consumer")
{
echo '<script type="text/javascript">
Disable();
</script>';
}
if($_SESSION["access"] == "Administrator")
{
echo '<script type="text/javascript">
Enable();
</script>';
}
?>
the javascript functions that i am trying to call are
<script type="text/javascript">
function Enable() {
SubmitButton.disabled = false;
}
function Disable() {
SubmitButton.disabled = true;
}
</script>
I have also tryed
if($_SESSION["access"] == "Consumer")
{
echo "<script> Disable(); </script>";
}
Im just wondering if I have typed something in wrong or if I have forgotten to put something in.
any help would be much appreciated.
Looking at your code you have couple of issues:
Mixing your PHP logic and pure HTML is (usually) not a good idea.
Instead I would suggest you move your access checking logic fully on the server side and display the button accordingly (disabled or enabled) based on the user's access.
Example:
<?php if($_SESSION['access']): // Only show the button for users with access ?>
<button type="submit" value="Submit" <?php echo ($_SESSION['access'] != 'Administrator' ? 'disabled' : ''); // Button disabled for everyone but administrators ?> />
<?php endif; ?>
And let me point out the obvious (as mentioned by the other answers), that's not 100% bulletproof. The user can still manually submit the button even if he is not an administrator by editing the page's HTML on the fly. That's just a UI fix. The real check should be done on the server side once the button is submitted (e.g. is the user logged in, does he have a cookie on his computer that identifies him as an administrator, does he have a session cookie set, etc).
Calling JS in random places, e.g. in the header can have unexpected consequences.
You better wait for the page to be loaded fully before calling any JS functions. You can do that via jQuery easily, but make sure you include the jQuery library before that in your header like so.
Afterwards you can call any JS after the page is loaded by placing them within the following block:
$(function(){
// Place your JS calls here, e.g. call to Enable()
});
String concatenation in PHP is done with a dot . and strings can be multiline
This code which you used is just plain wrong.
echo '<script type="text/javascript">'
, 'Enable();'
, '</script>';
You should use something like:
echo '<script type="text/javascript">'
.'Enable();'
. '</script>';
or better:
echo '<script type="text/javascript">
Enable();
</script>';
PHP doesn't use , sign for joining. Use ..
But otherwise it should work, except that you should define SubmitButton in advance of using it.
<?php
echo "<script type='text/javascript'>";
// if the id of your element is "submitButton"
echo "var submitButton = document.getElementById('submitButton');";
echo " function disable(){ submitButton.disabled=true; }";
echo "</script>";
?>
After that you can use it as you did..
<script type='text/javascript'>
disable();
</script>
Just be advised that denying access to some elements/functionality on your webpage with JavaScript alone is not a good practice - JavaScript is executed locally on the user's computer and therefore the user can modify it to gain an advantage.
Well, the problem may be that you're trying to call the javascript function before the HTML is ready (or finally rendered), so the browser, when executes the function doesn't find the button.
You could solve this placing your javascript code at the end of your page, or using jQuery and doing:
$(document).ready(function() {
<%php if ($_SESSION['access'] == 'xxxxx') {%>
Enable();
<%php } else { %>
Disable();
<%php } %>
});
Anyway, ALWAYS check user permissions on the server side, because someone could enable the button using Firebug or something else...

Categories

Resources