I was wondering if there is a way to display or echo a $username variable within a javascript function that display an html string. This is the original function:
Plugin.prototype.counter = function() {
if (this.s.counter) {
$(this.s.appendCounterTo).append('<div id="counter"><span id="counter-current">'
+ (parseInt(this.index, 10) + 1) + '</span> / <span id="counter-all">'
+ this.$items.length
+ '</span><sig> JOHN SMITH </sig><img src="jOHN.png"></div>');
}
};
I've tried inserting this:
<?php $arrays = file_get_contents('username.txt'); echo $arrays;?>
Instead of JOHN SMITH, with and without quotes... Not working.
Any idea how to do such task?
Taking a wild guess here, it's possible your file is being called incorrectly.
This will specify the absolute path on the server.
<?=file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/username.txt');?>
Related
I am trying to display a button under certain condition on my HTML output
I succesfully wrote the code like this:
<?
var HTMLToDisplay = "";
if (data[i][5] == 0) {
HTMLToDisplay = ""
} else {
HTMLToDisplay = '<input type="button" value="Réserver" onclick="openForm(' + "'" + new Date(data[i][4]).toLocaleDateString('fr-BE', options) + "'" + ",'" + data[i][3] + "'," + data[i][0] + ')" />'
}
?>
<?= HTMLToDisplay ?>
But unfortunately, the HTML code appears in plain text rather than in the code
In fact the script automatically added some unwanted double quotes
Any idea how I can display my button just by code, without doing complex stuff?
Thanks a lot
In your script, please modify as follows and test it again.
From:
<?= HTMLToDisplay ?>
To:
<?!= HTMLToDisplay ?>
By this, if the value of HTMLToDisplay is the valid HTML tag, the value of HTMLToDisplay put as the raw string. When it is loaded by the browser, it is shown as a button. If no button is shown, please check the value of HTMLToDisplay again.
Reference:
Force-printing scriptlets
In Javascript i encode parts of the request parameter like this
window.location.href = "search.php?qry=" + encodeURIComponent("m & l");
In my Search.php i reach this like this
$url = urldecode($_SERVER['REQUEST_URI']);
echo ."Full URL: " .$url ."<br>";
$parts = parse_url($url);
parse_str($parts['query'], $query);
$qry = "Just Query: " .trim($query['qry']);
echo $qry ."<br>";
This prints out:
Full Url: /Search.php?qry=m & l
Just Query: m
Looks like the stuff after the & is being dropped in the 'm & l`
What changes do i need to make in PHP or Javascript?
Just change:
$url = urldecode($_SERVER['REQUEST_URI']);
to
$url = $_SERVER['REQUEST_URI'];
You're basically double-decoding as parse_url will decode it as well.
Worth noting that PHP has already done this for you so there's not really a reason to parse your own URL. $_GET['qry'] will contain 'm & l'
If you're doing this for several query variables, you'll need to run encodeURIComponent separately for each.
Example:
window.location.href = "search.php?qry=" + encodeURIComponent("m & l") + "&subcat="+encodeURIComponent("hello & there");
You're explicitly telling it to encode the & after all.
I want to set the value/text of a div using javascript/jquery inside a loop but I don't know how to implement it. I need help with this one guys.
Objectives:
Retrieve data from database.
Set the value of an element using javascript/jquery (inside a loop) from the database.
Make the value a link
I have this a_link column from links table with the ff. values:
- www.google.com
- https://www.google.com
- www.stackoverflow.com
And here is my code:
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$thelink = $rowlink['a_link'];
?>
<div class = "row">
<span id = "linkhere"></span>
</div>
<script>
var link = "<?php echo $thelink; ?>";
$("#linkhere").html(urlify(link));
function urlify(text) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
//var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function(url,b,c) {
var url2 = (c == 'www.') ? 'http://' +url : url;
// return '<span style = "color:blue;text-decoration:underline">' + url + '</span>';
return '' + url + '';
})
}
</script>
<?php
}
?>
Any help would be highly appreciated. Thanks.
#aimme is technically not wrong about using a different database library. Please read "Why shouldn't I use mysql_* functions in PHP?" for reasons why not to use mysql_ and for some neat alternatives, some tutorials, and some good reads. (yes, all in the same page! just scroll down)
I think you're trying to:
display a <div> of class 'row'
with an <a> tag inside that uses the 'a_link' column of the 'links' table as the href and the label.
The href for the tag must always have a scheme (http://).
Just PHP and HTML
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$theLink= $rowlink['a_link'];
$regexMatches = array();
// removed (what seemed to be) needless groups in regex
$urlFound = preg_match("#((https?:\/\/|www\.)[^\s]+)#",$theLink,$regexMatches);
if($urlFound === 1) {
// only add http:// if http:// was not detected
$href = ($regexMatches[2] === "www." ? "http://" : "") . $theLink;
?>
<div class="row">
<?php echo $theLink; ?>
</div>
<?php }
}
?>
This code won't echo a row if a_link doesn't contain either 'http://' or 'www.' in it. so google.com will not be displayed.
Of note, as written, the regex will work on "urls" like 'applewww.google.com'. Don't know if that matters. Adding a '^' to the beginning of the regex may solve the problem (like so:preg_match("#^((https?:\/\/|www\.)[^\s]+)#",$theLink,$regexMatches);)
A (better|different) solution could use parse_url($url)
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$theLink= $rowlink['a_link'];
$href = (parse_url($theLink,PHP_URL_SCHEME) === NULL ? "http://" : "") . $theLink;
?>
<div class="row">
<?php echo $theLink; ?>
</div>
<?php
}
?>
However, using parse_url() would mean any old string would be displayed (while the first solution would not display any links that didn't have either http:// or www.) but since your pulling from a table called 'links' it's probably safe to assume everything is a valid path.
That's not how it works, that's not how any of this works
Now let's assume that you really need to use Javascript to process your generated links (which is not).
You first need to separate your Javascript code from your PHP code. You will only use Javascript once you have fetched your data and generated some output.
I guess you just want some kind of working code
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink)) :
$link = $rowlink['a_link'];
?>
<div class="row">
</div>
<?php
endwhile;
?>
<script type="text/javascript">
$(function() {
$('.row a').each(function() {
var urlified = urlify($(this).data('url'));
$(this).attr('href', urlified.url)
.text(urlified.label);
});
});
function urlify(text) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
return text.replace(urlRegex, function(url,b,c) {
var label = (c == 'www.') ? 'http://' +url : url;
return {url: url, label: label};
});
}
</script>
First i want to advice that use PDO or mysqli instead of mysql. as it
is vulnerable to sql injection and its depreciated.
"I want to set the value/text of a div using javascript/jquery inside a loop but I don't know how to implement it. I need help with this one guys."
for that i would say Php is a server side language whereas javascript is a client side language. and Ajax is the way to manipulate client side from server vice versa, without refreshing the whole page.
below is just a demonstration that i edited little bit from your code to show the separation of server side and client side code and to just give an idea how it works.I don't know whether the code will work or not. haven't tested. php code (server side) will be executed first but could control the display of it using javascript(client side) functions inside document.ready() or window.load() to apply the affects as soon as possible.Through this we could bring changes to the links that we want before its being shown to the client . For each of the link retrieved and displayed you could use a specific class and jquery .each() function to apply certain fix to the selected link as Lyes BEN mentioned above or all the elements with a specific class could be manipulated as a whole without using .each.
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$thelink = $rowlink['a_link'];
echo '<div class = "row">
<span id = "linkhere">
</span>
</div>';
}
?>
<script>
$("#linkhere a").html(urlify(link));
function urlify(text) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
//var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function(url,b,c) {
var url2 = (c == 'www.') ? 'http://' +url : url;
// return '<span style = "color:blue;text-decoration:underline">' + url + '</span>';
return '' + url + '';
})
}
</script>
You can implement this using php with parse_url function (http://php.net/manual/en/function.parse-url.php) to get different components.
In parse_url, there is 'scheme' key for http or https.
Then to do this with php, just call formatUrl function to make the url
<?php
function formatUrl($url)
{
$urlData = parse_url($url);
if(!isset($urlData['scheme'])) {
$url = 'http://' . $url;
}
return '' . $url . '';
}
?>
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$thelink = $rowlink['a_link'];
?>
<div class = "row">
<span id="linkhere"><?php echo formatUrl($thelink)?></span>
</div>
<?php
}
?>
I am scripting a chat for a forum, and it seems that it uses php to get the user's avatars. (PS idk anything about weather or not javascript can use sql databases or how to work with it so i would like to stick to php) But the problem is that the javascript isnt liking it if i put php variables into it.
getUserNodeString: function(userID, userName, userRole) {
var encodedUserName, str;
if(this.userNodeString && userID === this.userID) {
return this.userNodeString;
} else {
encodedUserName = this.scriptLinkEncode(userName);
str = '<div id="'
+ this.getUserDocumentID(userID)
+ '"><a href="javascript:ajaxChat.toggleUserMenu(\''
+ this.getUserMenuDocumentID(userID)
+ '\', \''
+ encodedUserName
+ '\', '
+ userID
+ ');" class="'
+ this.getRoleClass(userRole)
+ '" title="'
+ this.lang['toggleUserMenu'].replace(/%s/, userName)
+ '">'
+ userName
+ '</a><?php echo \'<img src="test.php" />\' ?>'
+ '<ul class="userMenu" id="'
+ this.getUserMenuDocumentID(userID)
+ '"'
+ ((userID === this.userID) ?
'>'+this.getUserNodeStringItems(encodedUserName, userID, false) :
' style="display:none;">')
+ '</ul>'
+'</div>';
if(userID === this.userID) {
this.userNodeString = str;
}
return str;
}
},
'</a><?php echo \'<img src="test.png" />\' ?>'
is the line thet im trying to use, i havent put my variable yet, im trying it with a test immage first
It should be like this:
+ '</a><img src="<?php echo htmlentities($src, ENT_DISALLOWED | ENT_QUOTES | ENT_HTML5) ?>" />'
You should only escape back into PHP for the specific part of the code that needs to contain the PHP variable. The rest of it should be literal HTML or Javascript.
You should also use htmlspecialchars() to ensure that the variable content is encoded properly to be used in an HTML attribute, in case it contains special characters.
The above is for getting a PHP variable into a JS literal that contains HTML code. If just you want to get a PHP value into a Javascript variable, it's slightly different. Then you can use json_encode() to generate the JS representation:
var js_var = <?php echo json_encode($php_var) ?>;
UPDATE
this is a .js file, its taken from ajax chat
It won't work inside a .js file, because those files are not parsed by PHP. It can be set up so that they get parsed, but I strongly suggest you don't do it, ever.
Besides, you don't need PHP for what you're doing.
ORIGINAL ANSWER
This is not a proper PHP inside this line:
+ '</a><?php echo \'<img src="test.php" />\' ?>'
Or just to strip the PHP part:
<?php echo \'<img src="test.php" />\' ?>
To get it to work, you need to remove those escaped quotes (you don't need to worry about JS quotes, because PHP parser will hit the file first, leaving you with whatever you echoed), and add a semi-colon:
<?php echo '<img src="test.php" />'; ?>
and the full line should be:
+ '</a><?php echo '<img src="test.php" />'; ?>'
which will render as:
+ '</a><img src="test.php" />'
It doesn't really make sense to use PHP for this, but okay.
Of course, it has to be inside a file that the server will parse with PHP (.php files by default, strongly suggest you don't set up PHP parsing for JS files). You never answer about the filetype in the comments.
I am trying to make a pop up load as soon as the page loads. I've used this already on the site and it works. However now nothing pops up.
<script>
window.onload = function (<?php echo $name . "," . $club ;?>){
var txt = name + " has been deleted from this club";
$.prompt(txt,{
buttons:{Delete:true},
close: function(e,v,m,f){
if(v){
var uid = f.userid;
window.location = "manageclub.php?id=" + club;
}
else{}
}
});
}
</script>
First of all, I should say that this approach doesn't feel quite right; you're building a new page just so that you can show a JavaScript prompt which will then redirect to another page ... I'm sure that could be done in a better way.
That said, here's the answer. You can't pass arguments inside the function definition like that; define those variables inside the function body instead;
Secondly, you're not escaping club properly for use in a URL.
window.onload = function ()
{
var name = <?php echo json_encode($name) ?>,
club = <?php echo json_encode($club) ?>,
txt = name + " has been deleted from this club";
$.prompt(txt, {
buttons:{Delete:true},
close: function(e,v,m,f) {
if (v) {
var uid = f.userid;
window.location = "manageclub.php?id=" + encodeURIComponent(club);
}
}
});
}
I'm using encodeURIComponent() to escape club properly inside JavaScript at the redirect code, and json_encode() to escape the PHP variables to be used in JavaScript.