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>";
Related
The result I want:
<div class="cat_cards_item" onclick="myFunction('http://website','name','description')">
I tried 2 methods:
1.
echo "<div class='cat_cards_item' onclick='myFunction(" . $resultwebsite['website'] . "," . $resultname['name'] . "," . $resultdesc['description'] . ")'>"
My result:
<div class="cat_cards_item" onclick="myFunction(http://website,name,description)">```
echo "<div class='cat_cards_item' onclick='myFunction('" . $resultwebsite['website'] . "','" . $resultname['name'] . "','" . $resultdesc['description'] . "')'>"
My result:
<div class="cat_cards_item" onclick="myFunction(" http:="" website="" ',' name="" ',' description=""')'="">
Im trying to call a javascript function that opens a modal with the information I pull from my php code.
I tried most styles of placing quotes and im getting a headache from it, any help?
By using the heredoc-syntax you can get a more readable string, and you can simply integrate your variables without concatenations:
<?php
$mydiv = <<<EOD
<div class="cat_cards_item" onclick="myFunction('{$resultwebsite['website']}','{$resultname['name']}','{$resultdesc['description']}')">
EOD;
echo $mydiv;
?>
If you would create multiple of the same HTML-structure, I would create a simple PHP function that generates the HTML code, so you don't have to worry about the quotes:
<?php
$HTML = createModal('cat_cards_item', "myFunction('http://website','name','description')");
echo $HTML;
function createModal($class, $onClick) {
return "<div class=\"${class}\" onclick=\"${onClick}\">";
}
<div class="cat_cards_item" onclick="myFunction('http://website','name','description')">
Try the PHP code online!
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.
So here is my problem. I have the below set of javascript code and HTML.
What is supposed to happen is that as you click on various checkboxes in a form, the script is supposed to take the Value of the Checkbox you checked and fill in a text field below that has a similar "name" identifier. The below code works for all values but one. The one with a space in the value "Character Only" doesn't work. I tried to use the Javascript method .Replace(" ", "-") to accomplish replacing the space with a hyphen but it doesn't seem to work. Since the HTML is being dynamically created via a PHP loop, I can't just add in the needed values and hard code everything.
Is there a way to make
JSFiddle - The full program and HTML layout.
The Javascript (Click the JSFiddle link to see the entire result)
function autofill(ElementName) {
//window.alert('You got this: ' + ElementName);
if(document.getElementById('keyword-' + ElementName.toLowerCase()).checked == true) {
document.getElementById('keyword-entry-' + ElementName.toLowerCase()).value = document.getElementById('keyword-' + ElementName.toLowerCase()).value;
} else {
document.getElementById('keyword-entry-' + ElementName.toLowerCase()).value = '';
}
}
// window.alert('This value is: ' + document.getElementById('keyword-ally').value.toLowerCase() );
//--> </script>
The PHP being used to create the HTML elements for the above JScript
<?php
$keywords = array("Ally" , "Breaker" , "Character Only" , "Combo" , "Desperation" , "Item" , "Kick" , "Multiple" , "Powerful" , "Punch" , "Ranged" , "Reversal" , "Stance" , "Stun" , "Taunt" , "Terrain" , "Throw" , "Unique" , "Weapon");
$i =0;
foreach($keywords as $keyword_name) {
echo '<td style="width: 20%;">' . zen_draw_checkbox_field('ufs_keywords[]', $keyword_name, in_array($keyword_name, $pInfo->resources), '', 'id="keyword-' . str_replace(" ","-",strtolower($keyword_name)) . '"') . ' <label for="keyword-' . str_replace(" ","-",strtolower($keyword_name)) .'">' . $keyword_name . "</label><br />" . zen_draw_input_field('ufs_keywords_entry[]', '', 'id="keyword-entry-' . str_replace(" ","_",strtolower($keyword_name)) . '" style="width:100px; float: right;"') . "</td>" . "\n\n";
$i++;
echo ($i % 5 == 0 ? "</tr>\n\n<tr>" : "");
}
?>
I'm currently requesting some text via jQuery on a php page. The problem is that the new line symbols \n are displayed in the alert window, and do not get interpreted as new line. I do not escape the string at any time.
In the error: function(..) block of my jQuery request, I get the string returned by php via jqXHR.responseText, here is it's exact value :
Some fields are empty!\n$name= \n$schedule= 480;1140;480;1140;480;1140;480;1140;480;1140;480;1140;480;1140\n$free_connection= false\n$free_coffee= false\n$rating= -1\n$lat= 44.715513732021336\n$lng= 1.9775390625\n
When I do this, new lines DON'T WORK :
alert(jqXHR.responseText);
So to debug, I decided to paste the php response string (which is the previous string) directly in the alert() function, and in this case the new lines WORK :
alert("Some fields are empty!\n$name= \n$schedule= 480;1140;480;1140;480;1140;480;1140;480;1140;480;1140;480;1140\n$free_connection= false\n$free_coffee= false\n$rating= -1\n$lat= 44.715513732021336\n$lng= 1.9775390625\n)");
The string is exactly the same, but yet new lines don't work when I use jqXHR to get it.
Anybody has any clue ?
EDIT: php code that generates the string :
$errorMessage = 'Some fields are empty!' . '\n'
. '$name= ' . $name . '\n'
. '$schedule= ' . $schedule . '\n'
. '$free_connection= ' . $free_connection . '\n'
. '$free_coffee= ' . $free_coffee . '\n'
. '$rating= ' . $rating . '\n'
. '$lat= ' . $lat . '\n'
. '$lng= ' . $lng . '\n';
echo $errorMessage;
You're using the wrong type of quotes. In PHP, escape sequences aren't processed in single quotes, only in double quotes. So it should be:
$errorMessage = 'Some fields are empty!' . "\n"
. '$name= ' . $name . "\n"
. '$schedule= ' . $schedule . "\n"
. '$free_connection= ' . $free_connection . "\n"
. '$free_coffee= ' . $free_coffee . "\n"
. '$rating= ' . $rating . "\n"
. '$lat= ' . $lat . "\n"
. '$lng= ' . $lng . "\n";
echo $errorMessage;
I do not know if I understood well but You can try
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
or
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
I have the following code which parses the Twitter text to change links, mentions and hashes into hyperlinks:
function parseTwitterText($text) {
$returnText = $text;
$hashPattern = '/\#([A-Za-z0-9\_]+)/i';
$mentionPattern = '/\#([A-Za-z0-9\_]+)/i';
$urlPattern = '/(http[s]?\:\/\/[^\s]+)/i';
$robotsFollow = false;
// SCAN FOR LINKS FIRST!!! Otherwise it will replace the hashes and mentions
$returnText = preg_replace($urlPattern, '\<a href\="$1" ' + (($robotsFollow)? '':'rel\=\"nofollow\"') + '\>$1\<\/a\>', $returnText);
$returnText = preg_replace($hashPattern, '\<a href\="http\:\/\/twitter\.com\/\#\!\/search\?q\=\%23$1" ' + (($robotsFollow)? '':'rel\=\"nofollow\"') + '\>\#$1\<\/a\>', $returnText);
$returnText = preg_replace($mentionPattern, '\<a href\="http\:\/\/twitter\.com\/$1" ' + (($robotsFollow)? '':'rel\=\"nofollow\"') + '\>#$1\<\/a\>', $returnText);
return $returnText;
}
However I'm just getting 0 returned if I had a tweet like #test
I based this code on a JavaScript version I had, so wondering if I've done something wrong in the preg_replace() that only worked in the JS replace()
There are 2 problems in your code:
In PHP, you concatenate strings with ., not with a +. When using +, PHP is casting the strings to an integer before adding them, which results in the 0.
In the preg_replace() calls, you do not have to escape all the characters in the second parameter. So remove all backslashes within these three lines.
You should end up with something like this:
$returnText = preg_replace($urlPattern, '<a href="$1" ' . (($robotsFollow)? '':'rel="nofollow"') . '>$1</a>', $returnText);
$returnText = preg_replace($hashPattern, '<a href="http://twitter.com/#!/search?q=%23$1" ' . (($robotsFollow)? '':'rel="nofollow"') . '>#$1</a>', $returnText);
$returnText = preg_replace($mentionPattern, '<a href="http://twitter.com/$1" ' . (($robotsFollow)? '':'rel="nofollow"') . '>#$1</a>', $returnText);
In PHP, you use . to concatenate two strings, not + as you would in JavaScript. Also, as BluePsyduck mentioned, you don't have to escape all the characters as you're currently doing.
Change the preg_replace() statements as follows:
$returnText = preg_replace($urlPattern,
'<a href="$1" ' .
(($robotsFollow)? '' : 'rel="nofollow"') .
'>$1</a>', $returnText);
$returnText = preg_replace($hashPattern,
'<a href="http://twitter.com/#!/search?q=%23$1" ' .
(($robotsFollow)? '' : 'rel="nofollow"') .
'>#$1</a>', $returnText);
$returnText = preg_replace($mentionPattern,
'<a href="http://twitter.com/$1" ' .
(($robotsFollow)? '' : 'rel="nofollow"') .
'>#$1</a>', $returnText);
Test:
header('Content-Type: text/plain');
echo parseTwitterText('#foo lala');
echo parseTwitterText('#test');
Output:
#foo lala
#test
Demo.