How do I use php functions in javascript? - javascript

Situation:
I'm building a Wordpress Site. Menu becomes 'fixed' to the top of the page when scrolling down the page (http://deerfielddesigns.com.mlseo.net/). When i am logged into wordpress, the dashboard admin bar cover the menu. I wanted to create a different class for the menu when I am logged in as opposed to when I am logged out.
Code:
if ( direction === 'down' ) {
$('#main-header').addClass( 'et-fixed-header' );
} else {
$('#main-header').removeClass( 'et-fixed-header' );
}
I wanted to insert an "if ( is_user_logged_in() )" statement in there to change the class output but I don't really understand too much about javascript and if it plays nice with php. Does anyone have any insight as to what i need to do to make this work? Thanks all!

if this is not an AJAX driven login system, simply open your header.php file and perform the following
$the_class = is_user_logged_in() ? 'logged-in-class' : 'logged-out-class';
Then find your main-header and do what's required.
<header id="main-header" class="<?php echo $the_class;">
If it is an ajax driven login system, you'll need to understand how to work with wordpress' add_action, but that is an answer for an entirely different question.

Make an ajax request to the required php function whenever required. You may use ajax features of various JS libraries like jQuery, YUI etc. to do so.

PHP is a server side language (which quite likely is generating Javascript).
Javascript is in the browser.
The short answer is "You can't easily call PHP from JS".

The simple way to identify from you javascript if a user is logged in is to populate a javascript variable with their status. In your theme's header.php, add:
<script type="text/javascript">
var is_logged_in = <?php echo json_encode(is_user_logged_in()) ?>;
</script>
Then, in your javascript elsewhere, you can use:
if (is_logged_in) {
//....
}

If you write inline javascript in your php files you can do this:
<?php // some php code ?>
<script type="text/javascript">
<?php if ( is_user_logged_in() ) { ?>
// Place some javascript here
<?php } else { ?>
// Place some javascript here
<?php ?>
</script>
<?php // some php code ?>

Related

PHP on WordPress - If the link contains ID "124" run this .js file

I use WordPress on my local server.
To perform a redirect after a user has completed the contact form with the Plugin Contact Form 7 I want him to be redirected to a specific page.
I tried a plugin that I found but it doesn't work and the site crashes.
I would like that:
user goes to page with ID 2. Once the contact form has been completed, clicking send will call the file home-it.js.
User goes to page with ID 96. Once the contact form has been filled in, clicking on send will call the file home-de.js
etc.
I tried this PHP code but it didn't work:
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url,'2') !== false) {
?> <script type="text/javascript" src="home-it.js"></script> <?php
} elseif (strpos($url,'124') !== false) {
?> <script> type="text/javascript" src"home-fr.js"></script> <?php
} elseif (strpos($url,'96') !== false) {
?> <script type="text/javascript" src="home-de.js"></script> <?php
} elseif (strpos($url,'82') !== false) {
?> <script type="text/javascript" src="home-en.js"></script> <?php
}
If I put the JS file on the page it works perfectly.
But the hoh system recognizes the page ID.
Can you help me?
Thanks so much,
Pascal
Contact Form 7 provides several types of custom DOM events. You can utilize the events within your JavaScript code to run a function in a specific situation.
In your case, you may want to try the wpcf7submit custom DOM event:
var wpcf7Elm = document.querySelector( '.wpcf7' );
wpcf7Elm.addEventListener( 'wpcf7submit', function( event ) {
alert( "Fire!" );
}, false );
For more information about CF7 events:
https://contactform7.com/dom-events/
Also, about your code - it's not a good practice to search for the ID in the URL:
Consider a very probable situation when you have pages with ids 96 and 196 your code will run for both because you are searching for 96
An alternative could be using the native WordPress function get_the_ID() to retrieve the ID of the current item (See here: https://developer.wordpress.org/reference/functions/get_the_id/)
Maybe try:
<?php
$post_id = get_the_ID();
if ($post_id == 2) {
?> <script type="text/javascript" src="home-it.js"></script> <?php
} elseif { ... }
?>
Thanks for the reply.
Who has set me wordpress and apache has something wrong and now no longer recognizes the IDs.
Meaning: if I use your formula or tell wordpress to use permalinks it doesn't work.
For this I need to be able to parse the link and redirect accordingly

Modify a source based on strings in the current URL

I am a little bit stuck trying to get a tracking code to work for my website.
Every click to my website through a tracker inserts a randomly generated unique string within the URL. For example, http://www.examplepage.com/?sub_ref=333ktcm1ckpv2uvd
When someone does goes through a step by step process on my website, a PHP script will load containing various variables, one of which is an external javascript:
$script = <script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa970aa5f018dcce821dc6251"></script>
In order for me to facilitate the tracking, I want to be able to add the unique string in the URL into the javascript. The idea is that I can track when someone clicks my website and then completes an entry with an external script. For example:
$script = <script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa970aa5f018dcce821dc6251?sub_ref=333ktcm1ckpv2uvd"></script>
Could someone advise the best way to achieve this? I've been playing around with this for most of the day without success.
I should add, at the point I want the unique ID added onto the script, the URL on my website is http://www.examplepage.com/?sub_ref=333ktcm1ckpv2uvd#submit-entry
Thank you #CFP Support that's really useful.
So based on your advice, I've managed to work out that using the below displays the correct URL string that I'm looking to add within the javascript.
https://example.com/test/test.php?sub_ref=230948324095
<?php
echo __LINE__ . " here, we look at _GET "; print_r($_GET); echo "<br>";?>
8 here, we look at _GET Array ( [sub_ref] => 230948324095 )
So based on the above, I believe I should be using:
<?php echo ($_GET['sub_ref'])?>"
The problem I've got now, is that if I use the following, I end up with an error:
$script = <script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa?&sub_ref=<?php echo ($_GET['sub_ref']); ?>"></script>
PHP message: PHP Parse error: syntax error, unexpected '<' in
/home/admin/web/exampledomain.com/public_html/settings.php
on line 13" while reading response header from upstream
EDIT:
This is where I am at currently. I've made the change you recommended (first one) which doesn't product an error, however the sub_ref in the button that loads the script is still blank.
settings.php file
<?php
// Set the referral network
$network = 'A';
// Set your submit code below.
$onClick_code = 'call_referral()';
// Set your the referral script below.
$script = '
<script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa?&sub_ref=' . $_GET['sub_ref'] . '"></script>';
?>
final-step.php
<?php
require_once '../settings.php';
?>
<h1>Submitting Data</h1>
<p class="second-paragraph">Please wait while we process your data.</p>
<div class="data-processing-wrapper">
<div class="data-processing-inner-wrapper">
<div class="cssload-loader-walk">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<span class="console-msg"></span>
<div class="data-verification-wrapper">
<h3>Data Verification</h3>
<p>Thank you, you are almost done submitting your data.
<br>Click on the Submit Now button below to submit your data.
</p>
<div class="button-wrapper data-verification-button-wrapper">
<a class="button data-verification-button"
<?php if ($network == 'A' || $network == 'B') {?> onclick="
<?php if (!empty($onClick_code)) { echo $onClick_code; } ?>"
<?php } ?>>Submit Now
</a>
<?php if ($network == 'A' && !empty($script)) { echo $script; } ?>
</div>
</div>
<div id="progressBarConsole" class="console-loadbar">
<div></div>
</div>
</div>
</div>
From inspecting the Submit Now button in Chrome, this is what it shows (the ?sub_ref is blank):
<div class="button-wrapper data-verification-button-wrapper">
<a class="button data-verification-button" onclick="call_referral()">Submit Now</a>
<script type="text/javascript" id="js1" src="https://www.example.com.net/test.php?id=8bb1ff8&sub_ref="></script> </div>
Am I correct in assuming that the sub_ref does not appear because the script is not being when the page is opened (only when final-step.php runs)?
Looks to me like you are close, just need to point to the right query....
src="https://www.example.com/load.php?id=8bb1ff8aa970aa5f018dcce821dc6251&sub_ref=<?php echo urlencode($_GET['sub_ref'])?>"
Looks fine (though from the example you gave you shouldn't need the urlencode).
It is really hard to tell what is going on though without some actual code.... (which is likely why nobody is answering you..... - nor can I give you much of an answer......)
However, as a 'troubleshooting' tip......
You have to know what you have as variables to work with at any given moment, so learn to stop the code at any given point and take a look what the code sees.
In this case, a good one would be to see what is in the $_SERVER array to see what links are really available before trying to build the reference link (this will tell you where you really are as well as how the user got to you, etc. - a wealth of info to be sure!)
echo __LINE__ . " here, we look at _SERVER "; print_r($_SERVER); echo "<br>";
Another good one at this point is the $_GET, which will tell you what is in the query string as an array....
echo __LINE__ . " here, we look at _GET "; print_r($_GET); echo "<br>";
Having the results of both those will tell you that you actually have the data you think you do (and that is quite often the reason things don't work like you expect!)
(you can also add a
die();
after any line to make the code stop..... Lots of ways to do this, and the most important part is just seeing what is going on!
Use the above, change your question to include more code and show what you are getting in $_SERVER and $_GET at that point and you will get some great, exact answers, I'm sure!
EDIT (after a bit more info.... - but still no full code..... :( again, seeing the script around all this would help get this done..... not sure why you aren't including it...)
Obviously you are in PHP at this moment (as it is a PHP error - the script would tell us that...) and your code won't work in PHP.
You have....
$script = <script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa?&sub_ref=<?php echo ($_GET['sub_ref']); ?>"></script>
and
PHP message: PHP Parse error: syntax error, unexpected '<' in
/home/admin/web/exampledomain.com/public_html/settings.php on line 13"
while reading response header from upstream
Which is telling you the issue - - - you can't write JS inside PHP! You can make it a variable, then use it later, or you could 'jump in/out' of PHP/HTML to do it, but you must remember what language you are in and respect that language's rules.
So, you could have:
$script = '<script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa?&sub_ref=' . $_GET['sub_ref'] . '"></script>';
Or, 'jump in/out' with:
// PHP code ......
// 'jump out'....
?>
<!-- now you are in HTML and can do some JS -->
<script type="text/javascript" id="js1" src="https://www.example.com/load.php?id=8bb1ff8aa?&sub_ref=<?php echo ($_GET['sub_ref']); ?>"></script>
<!-- where you had correctly 'jumped', but improperly mixed... -->
<!-- now, back to PHP... ->
<? // and you can do more PHP code here.....
You have to respect the language - and where you are at any point in the code!
If you still have issues, INCLUDE THE FULL CODE AROUND THIS (I'm sure it isn't rocket science gov't secret stuff, so save us all some time so you can get the help you are asking for, please!
EDIT:
in your settings.php the link shows as
src="https://www.example.com/load.php?id=8bb1ff8aa?&sub_ref=' . $_GET['sub_ref']
However, you say in the button it is
src="https://www.example.com.net/test.php?id=8bb1ff8&sub_ref="
Your code is not clear on how things are going...... (does this sound familiar? SHOW THE CODE AS IT IS PROCESSED..... - I can't {and now, won't be able to - I've put too much time on this and am getting 'looks'...} try to guess where that weird change came from. You need to show something that is logical.....
and, prove that you have the _GET - use the print_r just before the _GET to make sure you have the data as it is being processed (sometimes with PHP you have to do some 'tricks' to keep the data on one page and use it on another..... there are several ways to do it, but until I understand your flow and what you are trying to do overall {and mostly, why you are using so many pages.... - it could be an overall design/flow issue...}, it is really hard to get a picture of what you are trying to accomplish..)
SO is not really a training facility - and I have other projects (I'm allowed a bit of time each day to answer questions, etc. - part of the 'give back to the community' policy around here, but my primary work is on paid projects {I'm sure you understand...}, so I can't do more today, but if you give some clear 'steps' on what is going on and errors you see, etc. I can look at this again tomorrow.

PHP Script in OnClick Event

This IS a duplicate from Calling a php function by onclick event, but I have a question on it. The answer I had a question on is by timpanix, and basically it won't work.
He said to execute some PHP code in a On Click event do this:
onclick="document.write('<?php //call a PHP function here ?>');"
and call the PHP function. Yet whenever I try it:
<button id="profileinformationbutton" input type="submit" value="Login" onclick="document.write('<?php profileupdated() ?>');"> Update Profile </button>
it prints out ');" > Update Profile, yet I have no clue why. It is inside of a form, and the PHP function looks like this:
<?php
function profileupdated() {
?>
<div id="profileupdated"> Profile Updated </div>
<?php
}
?>
Why would the code be displaying this? Please help! :) Thank You.
EDIT
The code does not seem to be writing Profile Updated to the page, any idea why?
function profileupdated() {
echo "<div id='profileupdated'> Profile Updated </div>";
}
Also if you only want to print this value to your tag why you're using function? Assign it to a variable.
like
$myVar = '<div id="profileupdated"> Profile Updated </div>';
Then use this variable where you want?
you should echo or return your function body. Carefull! I changed quotes!
Your PHP function is writing to the page already, rendering the document.write (javascript) useless. Try this:
<?php
function profileupdated() {
return "<div id='profileupdated'>Profile updated</div>";
}
?>
I do want to note though that you might want to consider a cleaner way of doing this: If you just want to display a fixed text ("Profile updated"), stick to pure client-side Javascript.
Otherwise (if there's logic to be done server-side), you might want to decouple server and client and use an AJAX call and JSON to transfer your data.
PHP is a server side programming language, you are executing the JavaScript on the client side.
If you want to call a PHP script from your JavaScript you need Ajax, f.e. jQuery.

How can I put PHP code inside JavaScript document.write

Hello can anyone please help me in fixing this code?
1st code
<script type="text/javascript">
if (document.getElementById("tester") != undefined)
{
document.write('**2nd code should be here**');
}
else
{
document.write('<img scr="./img.png" />');
}
</script>
2nd code
<?php while (have_posts()) : the_post(); get_template_part('item-video');
endwhile; ?>
What I want to happen is to insert the 2nd code into the first code. But when I try to insert it, it gives me a blank page.
the biggest thing I've heard is that PHP is server side, while Javascript is client side. Therefore, changing the html page using document.write() isn't going to do anything unless you reload the page. I think you can circumvent this problem tho, using Ajax and the load() function.

How to add inline JavaScript to a wordpress tempate file

How to add inline JavaScript to a WordPress template file?" Plus add it to every post on my page? for instance, <script type="text/javascript">alert('hello world');</script> would be...
Adding it to a template is easy; just stick it within a tag in any part of the template you want to add it to. For instance:
<script>alert('Hello world!');</script>
as an incredibly basic (and kinda messy and improper) way to demonstrate it. Any template file is just a PHP file, or in other words an HTML file with some extra PHP code thrown in.
Also, to add something to a post, you'll want to add it to the appropriate part of your Wordpress template. For instance, in the default Twentytwelve theme, that'd be the content.php file--that contains the code for a single article, and adding something to that will add it to every instance of an article on the page.
To add some javascript to every post on your page just place it inside the loop. Something like:
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
?>
<script type="text/javascript">alert('hello world');</script>
<?php
the_title();
the_excerpt();
} // end while
} // end if
?>
Would add an alert for every post on the page. That would be pretty messy to have a popup for every post but that's the gist.

Categories