Modify a source based on strings in the current URL - javascript

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.

Related

Pass PHP variable from one page to another to get correct item from button [duplicate]

This question already has answers here:
PHP Pass variable to next page
(9 answers)
Closed 1 year ago.
I have 2 pages, content.php & pagecontent.php, and in content.php I display products info from database into table tags and inside has a grid of 2 rows and 3 columns that I echo descriptions of the products into. One of the grids row holds a button with and thumbnail image over it so that it would link or send user to pagecontent.php for that specific product info page. On pagecontent.php the user will be able to add the product/s to a cart/wishlist(not there yet, future stuff).
Ok so far on content.php I've been able to display all products from database, from the query and while loop, works, I was able to change stuff in database and changes would happen on content.php. I've had no success on passing a variable or id with $_GET, and I believe that's what I would want to use for this case. Also don't think my ajax is correct or it's missing things. I was trying to figure out how the button would get the products PartsID (1,2,3,etc...) from database, PartsID is the column name, to later be called when clicked then pass it to pagecontent.php to get correct product info from button. If there's a better way then the way I have the being used then let me know.
content.php
<?php
$stmt = $pdo->query("SELECT * FROM Parts");
while ($product = $stmt->fetch(PDO::FETCH_ASSOC)) {
?>
<td>
<?php
echo '<button type="button" class="testButton" onclick="test()">
<img src="images/APA802AC.jpg">
</button>';
?>
</td>
<td class="td-manufacturer">
<h6>MANUFACTURER</h6>
<p>
<?php
echo $product["Manufacturer"];
?>
</p>
</td>
<script type="text/javascript">
function test(itemid) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200)
{
window.location.assign("pageContent.php").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "pageContent.php?id=" + itemid, true);
xhr.send();
}
</script>
pagecontent.php
This page has tables as well but no grids. I need to get previous page button clicked PartsID(1,2,3,etc...) here and display that products info where I echo $row.
<div class="productInfo">
<h2 class="productTitle">
<?php
echo $row["PartTitle"];
?>
</h2>
</div>
<td>
<?php
echo $row["Availability"];
?>
</td>
<td>
<?php
echo $row["Price"]
?>
</td>
I would really hope for some detailed help please. I've tried all sorts of different variations of code and research, learning as I go with little time I have, new to php and javascript/ajax so go easy on me please. I hope I was clear and makes sense. Thanks!
First of all, your line
window.location.assign("pageContent.php").innerHTML = xhr.responseText;
is not doing what you think it is doing. "location.assign" loads a different page. Haven't tried myself to see if that will through an error to console for the innerHTML dereferencing, but you should check the network tab in your browser, most probably you will see 2 calls to pageContent: one with parameter (your ajax call) and 2nd one without (your location.assign call).
Secondly, if you have a multipage php application, you probably dont need ajax, as the page content is generated on the server side and after that it becomes static. Ajax is more suited for a single page applications with dynamic content.
w/o changing your application code too much, try to remove the ajax call and use only window location:
<script type="text/javascript">
function test(itemid) {
window.location.assign(_your_base_url_ + "pageContent.php?id=" + itemid)
}
</script>
I believe that would allow you to see the parameter on the server side in $_GET query.
P.S. I havn't been doing php lately so the above answer is more or less a concept. You may have to check php documentation for how to access the parameters. And reading some tutorials on this subject is not such a bad idea, as it seems that you do have some gaps in understanding the overall concept of doing web applications with php.

Including a PHP from another server using JS

I am attempting to build a very simple advertising system which is included on all of my websites and is called using a variable above the script to determine what kind of advert is displayed.
For this system, I have been using basic include functions. For example, on a clients website, near the footer, I would have:
$ad_type = 'banner';
include = '../../adsystem/adsystem.php';
The code for this adsystem.php is:
///// BANNER AD //////
if($ad_type == 'banner'){
$today = date("Y-m-d");
$sql = "SELECT * FROM `ad_adverts` WHERE `ad_start_date` <= '$today' AND `ad_end_date` >= '$today' AND `ad_type` = 'banner' ORDER BY RAND() LIMIT 1";
$result = $ad_conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$ad_id = $row["ad_id"];
$ad_link = $row["ad_link"];
$ad_direc = $row["ad_direc"];
?>
<div align="center">
<a target="_blank" href="http://mysite.co.uk/adsystem/adsystem.php?redirect=<? echo $ad_link; ?>&adid=<? echo $ad_id; ?>"><img src="<? echo $ad_direc; ?>" alt="<? echo $ad_link; ?>" style="width:70%; height:70px;"></a>
</div>
<?
}
}
$ad_type = '';
}
/////////////////////
VERY BASIC AT THE MOMENT - IS NOT YET COMPLETE. Simply using this as a test to get it working, then I will deal with fixing security problems and SQL injection, etc...
This will then display the adsystem.php code at the bottom of the site, or wherever I decide to add it. And this works perfectly for local websites - although I am working with websites which are not on the same server, and as you can imagine, that's where I run in to problems due to security issues.
Google Adsense and other advertising agencies combat this issue by using JS code to call the adverts, although I'm not skilled enough with JS to do this. On that direction though, I am wondering if it might be possible to use JS to just call the PHP script or if that would even work?
If anybody could point me in the right place here that would be great?
Without JS you are not able to do it. Please check document.write method. Here you have an example how to add dynamically your JS file with ads into html document:
<script>
var url = 'http://ads.com/buyme?rand='+Math.random()
document.write('<script src="'+url+'"></scr'+'ipt>')
</script>
Under this url, you should generate piece of JavaScript code dynamically in PHP, which should contains content of advertising and write in into html document using document.write method again.
You could use AJAX to call asynchronously to that script. In your php return a JSON with available advertisements.
Also you should consider using template engine and/or PHP framework. Mixing views with business logic isn't great idea.

Where to declare javascript/jQuery scripts

I'm trying to do some stuff with jquery/js (I don't know which one it is..), for example this script ; http://pastebin.com/V3HpU0NY - > http://blog.mainstreethost.com/light-youtube-embeds-faster-page-load#.VG9HKamkVSJ
But now comes the difficult part.
Url: http://erwin.my89.nl/stage/sieh/
This is the website when you go to the url.
This loads the "gallery (top)" and all content/ and kinda images(lazyload) for all the 'gallery' posts. If this has to be done another way please say so.
When you click a image you'll get this:
I hope you understand the idea.
So everything working ok
but now i go in to the inspector and i encounter this?!
I assume it is because i have the script defined in the loop of the content.. so when i click a gallery image, it loads another bunch of those text/css's.
So my question is: Is this the right way to do it? or should i be doing this different?
while ($loop->have_posts()) : $loop->the_post($post->ID);
if ($metas) {
foreach ($metas as $metakey) {
} elseif ($metakey['url']) {
preg_match(
'/[\\?\\&]v=([^\\?\\&]+)/',
$metakey['url'],
$matches
);
$id = $matches[1];
?>
<div class="youtube" id="<?php echo $id ?>" style="width: 560px; height: 315px;"></div>
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/youtube.js"></script>
<?php
^part of the code, if need more please say so.
Thanks in advance!
Can you put your CSS file/s in the head? That's where it normally goes.
Also, I don't see anywhere in your PHP where it could be loading these <style></style> tags. However it does look like it's going to import the same script at the end of each loop.
Could you provide more information on what your exact problem is?

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 do I use php functions in 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 ?>

Categories