I'd like to perform the following function in php.
""If there is URL format in a text, the URL becomes link.
When the link of the URL is clicked, onclick event is called.
Then the alert from the onclick event generates. ""
I am writing down the following code, but it doesn't work well.
Could you tell me how to solve this ploblem?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<title>test</title>
</head>
<body>
<?php
function makeLink($value) {
return mb_ereg_replace("(https?)(://[[a-zA-Z0-9]\+\$\;\?\.%,!#~*/:#&=_-]+)", '\1\2' , $value);
}
$text = 'HELLO!! http://google.com';
echo makeLink($text);
?>
</body>
</html>
I believe you want '\1\2'
Depending on the version of php, there are a few ways to use variables within strings. In your case, you are just writing the string $value, not using the variable.
What I did is end the string (with the single quote) then use dots . to concatenate the variable, then continue the string (single quotes again).
If using double quotes, you can do this:
$foo = 'code';
echo "this $foo works"; //will echo "this code works"
There is also much else wrong with your code. It's worth noting that using "onclick" in your html has never been a good practice and just serves to make your code even more confusing. The proper modern approach to communicating between javascript and php is through ajax, but if you must take this approach, at least put your javascript into <script> tag and at the beginning of that tag, get the information you need into javascript variable. Altogether, like this:
var value = '';
//etc
So, remove that whole regex thing altogether...according to your example here, it's useless and bloated.
<?php
$text = 'HELLO!! http://google.com';
$linkId = 'my-link';
echo '12';
?>
<script>
var text = '<?php echo $text; ?>';
var linkId = '<?php echo $linkId; ?>';
var linkElem = document.getElementById(linkId);
linkElem.addEventListener('click', function() {
myFunction(text);
});
function myFunction(text) {
alert(text);
}
</script>
If you did this, it would at least be better, but this whole approach is still very flawed. I recommend learning about separation of concerns and SOLID principles. This is all global, hard to read, hard to debug, etc.
Related
My end goal to pass eventSources via JSON dynamically. Before I even get to producing the JSON content dynamically, I am trying to use the documentation example to pass a simple single event via a JSON URL into my event tag, written manually.
I can see the URL works because I can echo the results in my wordpress website via php, but the JS script i'm passing the JSON URL to just crashes the calendar. I'm really scratching my head on this one.
There's also mention of the prev/next buttons triggering a GET to the JSON with the local timezone dates (say for the range of the currently displayed month). How am I supposed to syntax the json so as to have the event call find the data points range? I'm just really confused about all this.
JSON File: calendar.json
{
"title" : "something",
"start" : "2019-04-23"
}
PHP File: page-calendar.php
<?php
//Wordpress function for URL to the file location
$url = get_stylesheet_directory_uri() . '/calendar.json';
$data = file_get_contents($url);
$content = json_decode($data);
echo $content->title; // Just to test if the URL works
echo $content->start; // This echos just fine
?>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'dayGrid' ],
events: $url;
});
calendar.render();
});
</script>
</head>
<body>
<div id='calendar'></div>
</body>
</html>
The JSON needs to be an array of events (even if the array only contains one object). Currently you have a single object, and fullCalendar won't read that.
Make your calendar.json file look like this:
[
{
"title" : "something",
"start" : "2019-04-23"
}
]
You'll also need to change the code a bit so that your PHP $url variable is treated as PHP and rendered, and also so the output is treated as a string by JS, not just injected into the JS as-is:
events: "<?php echo $url; ?>"
If your php and fullcalendar is on the same page you may need this
<?php
$url = get_stylesheet_directory_uri() . '/calendar.json';
?>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'dayGrid' ],
events: "<?php echo $url; ?>";
});
calendar.render();
});
</script>
</head>
<body>
<div id='calendar'></div>
</body>
</html>
Remember to check your output of calendar.json.
It should look like so
[
{
"title" : "something",
"start" : "2019-04-23"
}
];
I'm not really sure, if this might solve your problem, also I don't know about WordPress. However, maybe you might try using WordPress built-in functions, maybe in this case, you might try wp_remote_get or find similar functions to use instead of file_get_content(). Because, maybe for security or permission reasons, you are not allowed to get contents from some URLs, not sure.
You might test it with chmod($url, 0000); to see if you are allowed to change the permission of the file. Then, if it was a permission issue, you could just add chmod()to your script:
//Wordpress function for URL to the file location
$url = get_stylesheet_directory_uri() . '/calendar.json';
chmod($url, 0777);
//$data = file_get_contents($url);
$data = wp_remote_get($url);
$content = json_decode($data);
chmod($url, 0755);
echo $content->title;
echo $content->start;
Your PHP codes seem to be fine. Maybe, var_dump($url); to make sure everything is fine.
Also, you might try changing
events: $url;
to
events: <?php echo $url; ?>
I know there are a lot of questions covering something similar, but I've tried the answers without any luck.
Snippet of PHP:
$usernum_query = "SELECT numPersonID FROM tbllogins WHERE txtUserName='$currentuser'";
if(!$usernumber = $db1->query($usernum_query)){
die('There was an error running the usernumber query [' . $db1->error . ']');
}
while($row = $usernumber -> fetch_assoc()) {
$userIDnum = $row['numPersonID'];
$userIDnum = utf8_encode($userIDnum);
}
Snippet of Javascript:
$(function(){
$("#0").click(function(){
var userIDnum = <?php echo json_encode($userIDnum); ?>;
alert(userIDnum);
The most common answer I've come across says to UTF_encode my variable, which I think I've done correctly. I've also tried:
var userIDnum = <?php echo $userIDnum; ?>;
Which doesn't work.
In my HTML outside of the script,
<?php echo json_encode($userIDnum); ?>
return "90" (with the quotes)
<?php echo $userIDnum; ?>
returns 90 (without the quotes).
Within the script, I get null and no alert box, respectively.
Any ideas as to why the variable isn't passed into the script? Thanks!
edit: tried with quotes and got the same result
[Taken from comments as requested]
If I can make a recommendation, put your value in a data-attribute in the HTML (e.g. <body data-user-id="<?php echo $userId ?>">. This keeps you from mixing code languages together which is hard to read, and would allow your external script to run correctly without making it a PHP page.
As far as IE9, I'll take a quick look. You might want to see how jQuery manages the data attributes. You should, at the least, have access to
domObject.getAttribute('data-user-id').
Yep, just did a quick lookup, and even IE10 doesn't support the dataset feature. So, you'll need to use getAttribute for IE <= 10.
A solution based on a suggestion by calamari:
In the HTML:
<!DOCTYPE html>
<!--[if lt IE 11 ]> <html class="ie10orless"> <![endif]-->
<head>
... more code here ...
And in the script:
var oldIE;
if ($('html').is('.ie10orless')) {
oldIE = true;
}
if (oldIE) {
var x = document.getElementsByTagName("div")[0].getAttribute("data-number");
alert("in IE");
alert(x);
} else {
var userinfo = document.querySelector('#user');
alert("NOT in IE");
alert(userinfo.dataset.number);
}
Hope this helps someone else. Thanks everyone for the other suggestions as well.
There are couple of things to check. Lets say this is your script:
<?php $htmlString= 'testing'; //Lets say this is a snippet of your php
?>
<html>
<body>
<script type="text/javascript"><!-- And this is the snippet of your JS -->
// notice the quotes around the ?php tag
var htmlString="<?php echo $htmlString; ?>"; //Make sure there's double
//quotes around your php
alert(htmlString);
</script>
</body>
</html>
Make sure you have PHP and JS in a file called .php. If its an external .js file, php inside it will not work (you can rename the JS file to a .php extension if you have it set up that way)
Also make sure you have the html, php and js setup the way above. There has to be double quotes around php, for example:
var userIDnum = <?php echo json_encode($userIDnum); ?>;
change this to below:
var userIDnum = "<?php echo json_encode($userIDnum); ?>";
I wanna start by saying that I have absolutely NO knowledge in JS ( which I think I'm gonna learn because I'm over-heating like never before ).
I'm making a website for a friend , and I wanted to add a little more stylish that just plain CSS3 & HTML, So I went on Google and did a little research and I downloaded a free usable jQuery plugin called "Simple Modal".
I want to display a PHP variables inside that Modal.
Here's a screenshot of it:
And here is the minimum required to make the plugin work properly on any page:
> <link rel="stylesheet" href="simplemodal.css" type="text/css"
> media="screen" title="no title" charset="utf-8">
> <script src="assets/javascript/mootools-more-1.3.1.1.js" type="text/javascript charset="utf-8"></script>
> <script src="/js/simple-modal.js" type="text/javascript" charset="utf-8"></script>
> <script src="assets/javascript/demo.js" type="text/javascript" charset="utf-8"> </script>
Now here comes the problem. The content of the Modal is in -> simple-modal.js in the following form:
$("modal").addEvent("click", function(e){
e.stop();
var SM = new SimpleModal({"btn_ok":"Confirm button"});
// Confirm Button
SM.addButton("Confirm", "btn primary", function(){
alert("Action confirm modal");
this.hide();
});
// Cancel button
SM.addButton("Cancel", "btn");
SM.show({
"model":"modal",
"title":"Modal Window Title",
"contents":"<p >Hey , how you doing? Nice weather today!</p>"
});
})
In order to edit the content that is displayed , i need to edit the "contents".
I tried to put my PHP variable in it .. It didn't worked .. Googled it... And I found a solution. Which is putting a JS variable and then, PHP one on the main page.
<?php $content = $user['username']; ?>
<script type="text/javascript"> var name = "<?= $content ?>"; </script>
So after my new found , I tried to do this:
"contents":"<p>Hey" + name + ", how you doing? Nice weather today!</p>"
Didn't work. I then, tried (To see , maybe the variable was the problem ):
"contents": name
And this time it worked. It seems , for an unknown reason to me, that I can't 'combine' 2 things(? if that's a proper way to name them all).
I even tried things such as "Good" + "Morning" but I got the same result.
I'm very confused on why is that.
So, if anybody could be of any help by explaining me why this is happening, how to fix it or at least give a precise path for researches, I would be very graceful.
Thank you.
<?php $content = $user['username']; ?>
<script type="text/javascript">
var name = "<?= $content ?>";
var fullcontent = "<p>Hey" + name + ", how you doing? Nice weather today!</p>";
</script>
and here it will be
"contents":fullcontent
Where as for the modal you can try EXTJS its quite efficient and easy to use.
The problem is. I want to inset margin-left: 20%; to maincontent, when the user is logged in.
No i dont have a problem with syntax, i can get it done in js, but im told to use php.
So i also added a class in css and to my body.
<?php
if ($_SESSION['username']){
include("/view/leftmenu.php");
}
?>
How do i activate css in php?
As revealed by the syntax highlighting, you're trying to put a single quote inside a single-quoted string.
Your options are:
Escape the single quotes with \'.
Use double quotes instead.
Use ?> ... <?php instead of echo.
Don't do this with JavaScript at all! You control the server side; why not just add a class to the body like logged-in, and have a CSS rule like body.logged-in #maincontent { margin-left: 20%; }?
(For what it's worth your JavaScript is invalid too; you need to quote the 20%. Percentages aren't legal JS.)
Put your JavaScript in double quotes, with single quotes inside. You may want to run your include first as well. include does not need (). Your code could look more like:
<?php
session_start(); // has to be run before any headers are sent
if(isset($_SESSION['username'])){
include '/view/leftmenu.php';
echo "<script type='text/javascript'>$('#maincontent').css('margin-left', '20%');</script>";
}
?>
The better solution however would look more like:
<?php
session_start(); $marginLeft = '0'; // $marginLeft should be your default
if(isset($_SESSION['username'])){
$marginLeft = '20%';
include '/view/leftmenu.php';
}
echo "<!DOCTYPE html><html><head><style type='text/css'>".
"#maincontent{margin-left:$marginLeft;}</style></head><body>".
"<div id='maincontent'>content</div></body></html>";
?>
A better approach yet, would look like:
<?php
session_start(); $className = 'withoutMargin'; // $marginLeft should be your default
if(isset($_SESSION['username'])){
$className = 'withMargin';
include '/view/leftmenu.php';
}
?>
<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
.withoutMargin{
margin-left:0;
}
.withMargin{
margin-left:20%;
}
</style>
</head>
<body>
<?php echo " <div class='$className'>"; ?>
<!-- your content here -->
</div>
</body>
</html>
Note: Your code above does not have to look exactly like this. This just illustrates concept. You would have more code testing for submit to be set and so forth. Also, with the second example, which I recommend, I would use external CSS, so it is cached by the user's Browser.
20% needs to be in quotes:
$('#maincontent').css('margin-left', '20%');
This also applies to px, em, pt, and any other form of CSS unit of measurement.
I'm making a website that has 3 documents. The Php document that has all html structure and script, the css document that has no interest in the question, and the javascript document.
I'm trying to input html contents of a javascript variable through .innerHTML statement. And to do that, I need (of course) to code the HTML content, and so I do the code within the javascript file itself. Like so:
document.getElementById("exp").innerHTML = "<div class=\"cell\">\
<div class=\"project_cell\"><img src=\"img.png\"></div>\
<div class=\"project_cell\">text</div>\
</div>\";
And this works. However, the code is obviously not just this. It's a complex HTML structure that I do not wish to see in the javascript file. So I would like to put the HTML content to be inside this variable into a text file, using PHP, and make that variable on the innerHTML statement instead of all the code.
My PHP file is like this.
<html>
<head>
<title>sample</title>
<?php
$filename = "thisishtml.txt";
$doc = file_get_contents($filename);
?>
<script src="javascriptfile.js" type="text/javascript"></script>
</head>
<body>
...call javascript function...
It seems ok to me, but if I do like:
document.getElementById("exp").innerHTML = "<?php echo $doc ?>"
It doesn't work. I've tried simple text and I've tried with a new project, and it works on a new project, but not in this one. What am I doing wrong? I've looked to many questions and tutorials and didn't help and that's why I'm looking for help in here.
Thank you very much for your time. I hope we could solve this.
Chances are you need to escape the contents of $doc for JS output.
document.getElementById("exp").innerHTML = <?php echo json_encode($doc) ?>;
If your javascript code is in a javascript file, PHP does not process that so you cannot execute PHP code there.
So you can either put the javascript code directly into the PHP page
<script type="text/javascript">
function someFunction()
{
document.getElementById('exp').innerHTML = "<?php echo $doc ?>";
}
</script>
or you can do the follow:
<script type="text/javascript">
var doc = "<?php echo $doc ?>";
</script>
Then in the javascript file do:
function someFunction()
{
document.getElementById('exp').innerHTML = doc;
}