How do I get a php element into a javascript - javascript

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.

Related

Google Sheet webapp: Display a button programmatically

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

Comma doesn't separate parameters

Trying to set up a WhatsApp button with a custom message, I've created a script in JavaScript to do that and calling it onclick.
I've tried moving quotation marks around but nothing works, this might be a silly issue but I just started with coding and can't get this to work, been trying since yesterday.
Here is my JavaScript code:
function sendSms(number, title) {
window.open('https://api.whatsapp.com/send?phone=' + number + '&text=' + 'hello' + title);
}
Here is my PHP code:
echo '<span class="ad-whatsapp" onclick="sendSms(\' '. $ad_wa .' , '. str_replace(" ", "%20", get_the_title()) . '\')"></span>';
It seems to be sending the whole content of the parenthesis as the number parameter instead of separating the 2.
function sendSms(number, title) {
window.open('https://api.whatsapp.com/send?phone=' + number + '&text=' + 'hello' + title);
}
echo '<span class="ad-whatsapp" onclick="sendSms(\' '. $ad_wa .'\' , \''. str_replace(" ", "%20", get_the_title()) . '\')">bb</span>';
Try using this JavaScript:
function sendSms(number, title) {
window.open(`https://api.whatsapp.com/send?phone=${number}&text=hello${title}`);
}
With this PHP:
<?php
$replaced = str_replace(" ", "%20", get_the_title());
echo '<span class="ad-whatsapp" onclick="sendSms(\'' . $ad_wa . '\', \'' . $replaced . '\')">SEND</span>';
?>
Good luck.
Try using this instead:
echo "<span class='ad-whatsapp' onclick=\"sendSms('".$ad_wa."' , '".str_replace(" ", "%20", $this->get_the_title())."')\">asdf</span>";

Javascript variable works only the first time

I have function that works with JSON.
function makeItem(data){
var tbl_body = "";
$.each(data, function() {
var id = parseInt(this.ProductId);
var tbl_row = "";
tbl_row += "<a href='article.php?cat=<?=$cat?>&subcat=<?=$subcat?>&id="+id+"'>";
tbl_row += "<div class='subCatImg'><img src='imagesDB/articles/<?=$main["+id+"]['dir']?>/<?=$main["+id+"]['image']?>'></div>";
tbl_row += "<div class='subCatName'>"+this.ProductNameBG+"</div>";
tbl_row += "<div class='subCatText'>"+this.ProductNameBG+"</div>";
tbl_row += "</a>";
tbl_body += "<div class='categoryWrap'>"+tbl_row+"</div>";
})
return tbl_body;
}
The problem is that the variable id works only the first time - in the a tag but not in the second nor the third time.
Is it because the a tag is not immediately closed or because the second and the third time I'm trying to use it in php array. I'm sure that the array works because if I hardcore it(<?=$main[1]['dir]?>) the image is displayed(no need for quotation marks, I need integer).
The thing is that I have to make it dynamic so I can't just type some number.
Why does it work the first time but not the others?
You can convert your PHP array into a json object like this :
var main = <?php echo json_encode($main) ?>;
then iterate through it.
#epascarello is correct. PHP is server side, were JS is client side. Instead, try to do something like
UPDATED:
tbl_row += <?php print("\"<a href='article.php?cat=$cat&subcat=$subcat&id=\" + id + \"'>\""); ?>
tbl_row += <?php print("\"<div class='subCatImg'><img src='imagesDB/articles/$phpVal1/$phpVal2'></div>\""); ?>
tbl_row += <?php print("\"<div class='subCatName'>\" + this.ProductNameBG + \"</div>\"");?>
tbl_row += <?php print("\"<div class='subCatText'>\" + this.ProductNameBG + \"</div>\"");?>
tbl_row += <?php print("\"</a>\"");?>
In this, you will have to pass the value of the id and the dir from JS to php so php can parse it's multidimensional array. You'll notice that <?=$main["+id+"]['dir']?>/<?=$main["+id+"]['image']?> has changed to $phpVal1/$phpVal2.
You can do this a number of ways - perhaps through a click of a button. But php will be done first, and then the JS.
In essence, you are getting all the values from the server (php) and forcing it to write the client side (JS) for you.

How to echo $username variable into a javascript

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');?>

Google Maps API - storing image URL and calling it

I've added an image URL to an entry in the mySQL database, and I want it do be displayed in the information window on my sidebar.
Here's what the part I'm fiddling around with:
downloadUrl("genxml.php", function(data) {
var xml = data.responseXML;
var locations = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < locations.length; i++) {
var name = locations[i].getAttribute("name");
var address = locations[i].getAttribute("address");
var type = locations[i].getAttribute("type");
var price = locations[i].getAttribute("price");
var img = locations[i].getAttribute("img");
var point = new google.maps.LatLng(
parseFloat(locations[i].getAttribute("lat")),
parseFloat(locations[i].getAttribute("lng")));
var html = "<div class=loc-img><img src=" + img + "/></div><div class=loc-name>" + name + "</div> <br/>" + address + "<br/>" + "<div class=loc-type>" + type + "</div><div id=loc-price>Price Rating:" + price + "</div>";
The bit at the bottom looks right to me, so I can't work out what's wrong.
The image is saved on the server, and the URL has been added to the img field of the entry, and there are no spelling errors. When the page loads, and the info window loads, this shows in the Inspector.
<img src="null/">
Here are the details of the column from phpMyAdmin, whcih I think could be causing the problem. varchar(120) latin1_swedish_ci, Null is set to no. I assumed that because it was a URL, varchar would be the appropriate choice.
Any thoughts?
EDIT: I am also having a similar issues with another field. I think it might be related. There's a 'price' field, set to int(5), and is simply a rating of 1 to 5. However, when the info window displays, it just says 'null'
I've actually managed to work out the problem.
Rather simple, yet easily overlooked!
When adding new fields to each item, you need to remember to register them in the XML converter that pulls the information from the database, and then converts it to a Maps-readable format (XML).
In my case, I had to go into genxml.php (as directed by the Maps documentation), and make it look like this:
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo 'price="' . $row['price'] . '" ';
echo 'img="' . $row['img'] . '" ';
echo '/>';
}
Hope that helps someone else!

Categories

Resources