wordpress - php and javascript dont go well together - javascript

I know some HTML and CSS but zero JAVA or PHP. I would like to insert LineIt button into my functions.php in WordPress:
The code goes like this:
<img src="imgpath" alt="LINE it!" />
Unfortunately this will display only the line link without my permalink. The_Permalink will be display as text not as dynamically taken URL.
I tried to do something like this:
<img src="linkin" width="[Width of Button]" height="[Height of Button]" alt="LINE it!" />'
But of course that didn't work. Oh and I don't want to use tags <script >.
Could help?
Thanks
Here is the function in my functions.php that I'm trying to modify with custom "LineIT" button:
function show() {
$return = '<aside class="show1 show2">'
. show_content() .
'<div class="show-box">'
. apply_filters('show_filter', show_rander()) .
'<div class="show3">'
. getIcons() .
'</div></div>**<img src="linkin" width="[Width of Button]" height="[Height of Button]" alt="LINE it!" />**<div style="clear:both;"></div>'
. show_content()
. show_content2() .
'</aside>
return apply_filters('show_buttons', $return);
}

according to the document at https://codex.wordpress.org/Function_Reference/the_permalink, the the_permalink() function is usually applied in the template within The Loop. Whereas functions.php is usually provide convenient functions and register them for the future use or register in The Loop.
So put the_permalink() in functions.php might not work as what you expected.
The general template files are like home.php, page.php or category-6.php(which will provide specific template for the category with id as 6).
In these files, the Loop usually is like:
<?php
if(have_posts()){
while(have_posts():
the_post();
the_content();
?>
//here you can add the link
<img src="imgpath" alt="LINE it!" />
<?php
endwhile;
endif;?>
Please refer to this page https://codex.wordpress.org/The_Loop_in_Action for further knowledge of the loop.
if you really want to use the functions.php, I would suggest using the other function get_permalink($id) and get_the_title($id) which will get the permalink of the post by the id and add a function for it. so the function will be:
function get_line($id){
$url = get_permalink($id);
$title = get_the_title($id);
return '<img src="imgpath" alt="LINE it!" />';
}
and then call the function in The Loop of the template.
To learn more about wordpress template, please refer https://developer.wordpress.org/themes/basics/template-hierarchy/

As suggested by #lhrec_106 I have used 3rd option and modified code works like a charm. Thanks!
I have inserted function get_line($id) before my function and then simply entered
. get_line($id) inside my custom function. Button works and share via Line my dynamically generated url.
Thank you

Related

how to call php function through hypertext link

I want to call a PHP function passing an argument on clicking a hyperlink (text with <a> tag) on the same page, i.e. href='#' onclick='loadpic($id).
Where $id is the variable to be passed to PHP function.
You can do that by ajax easily. Create a loadpic function in javascript instead and then pass $id to the php file via ajax and do something when you get the result.
Your javascript file should look like this-
(make sure you've inserted a link for jquery in your index file)
function loadpic(id_param){
$.post("filename.php",
{
id: id_param
},
function(data){
alert("Data received:" + data);
});
};
The data parameter in function(data) would be the value that you've echoed in the php file.
If you want to use onclick() method in your HTML element then you have to write your method is javascript and make an AJAX call to PHP. THis is one simple way to do this using php and javascript. And for this please see javascript and ajax with PHP.
But if you dont want to use javascript then here is a simple way and very simple code.
<?php
if(isset($_GET['myMethod'])){
myMethod($_GET['id']);
}
function myMethod($id){
echo $id."<br>";
}
?>
<?php
$myId = 4;
?>
<a href="index.php?id=<?php echo $myId ?>&myMethod" >MyLink</a>
Note: Copy this code and paste into a file called index.php because notice the hyper link tag and its attribute href="index.php".
Also note that you can not directly call php method using js like onclick() from your HTML tag. You should use AJAX or something. But using above demo code you can easily call myMethod() which is a PHP method using the hyper link tag.
In your case:
<?php
if(isset($_GET['call_loadpic'])){
loadpic($_GET['id']);
}
function loadpic($id){
echo "My loadpic method has been called! and the id is".$id."<br />";
}
?>
<!-- your other codes -->
<?php
$id = 4;
?>
<a href="this-same-file-name.php?id=<?php echo $id ?>&call_loadpic" >MyLink</a>
This is because your php function is in the same page and you want to call that function using same file and hyperlink in the same file. (According to your question)
You still will have to make javascript handle the exception because php has no onclick.
onClick=\"loadpic("'.$id.'");"\
//this will only send a php variable javascript will still have to loadpic();

Targeting dynamic id's within a javascript file

In a php file I have tags with dynamic id's.
Example:
<ul id="<?php echo 'ul_'.$xx; ?>">
<li id="test_li">...</li>
</ul>
In a separate JavaScript file I am wanting to use the load function and target that div.
$('<?php echo 'ul_'.$xx; ?>').load('../includes/myphpfile.inc.php #test_li');
My question is, how could I load that php within a JavaScript file?
Notes:- The reason I have it set up this way is due to looping multiple ul's. I just want my ajax file to refresh the li's within the specific ul I am inside of.
Edit: If I use classes instead of Id's it adds my newly inserted rows into all of the ul's with the same class. If I use a plain Id it only works on the first ul. Further explaining why I need to target the way I am.
Unable to find a solution using the path I was on, I looked for alternate methods. Worked out I could add the event in the php file on the submit form button click.
The reason I wasn't using this method at first was because the code was running before it submitted to the DB and therefore was always behind in relation to the new data being submitted.
To my surprise I fixed this by just duplicating the line of code.
<script>
$("<?php echo '#enter_submit_button'.$linkid ?>").click(function(){
/*1*/
$('#<?php echo 'ul__'.$linkid; ?>').load('../includes/pursuit.inc.php <?php echo '#li__'.$linkid; ?>');
$("<?php echo '#insert_new'.$linkid; ?>").fadeOut();
/*2 with delay*/
$('#<?php echo 'ul__'.$linkid; ?>').delay( 800 ).load('../includes/pursuit.inc.php <?php echo '#li__'.$linkid; ?>');
});
</script>
I honestly couldn't say exactly why this works but the logic behind trying the method came from hoping that the double load would pick up the latest submission.
The simplest answer would be to put your JavaScript code into the PHP file inside
<script></script> tags, i.e, just before closing your <body> tag, do this:
<script type="text/javascript">
$('<?php echo 'ul_'.$xx; ?>').load('../includes/myphpfile.inc.php #test_li');
</script>
But if you must use an external js file, then you could do this:
Create a (.php) file and write:
<?php
header("Content-type: application/javascript");
?>
// your js code with php inside (as you would do in HTML)
var othervar='<?php echo $phpVar; ?>';
//<?php //some php ;?>
Then, in your main (html/php) file, put in:
<script src='myjs.php' type='application/javascript'></script>
Hope that solves it.

PHP Script in OnClick Event

This IS a duplicate from Calling a php function by onclick event, but I have a question on it. The answer I had a question on is by timpanix, and basically it won't work.
He said to execute some PHP code in a On Click event do this:
onclick="document.write('<?php //call a PHP function here ?>');"
and call the PHP function. Yet whenever I try it:
<button id="profileinformationbutton" input type="submit" value="Login" onclick="document.write('<?php profileupdated() ?>');"> Update Profile </button>
it prints out ');" > Update Profile, yet I have no clue why. It is inside of a form, and the PHP function looks like this:
<?php
function profileupdated() {
?>
<div id="profileupdated"> Profile Updated </div>
<?php
}
?>
Why would the code be displaying this? Please help! :) Thank You.
EDIT
The code does not seem to be writing Profile Updated to the page, any idea why?
function profileupdated() {
echo "<div id='profileupdated'> Profile Updated </div>";
}
Also if you only want to print this value to your tag why you're using function? Assign it to a variable.
like
$myVar = '<div id="profileupdated"> Profile Updated </div>';
Then use this variable where you want?
you should echo or return your function body. Carefull! I changed quotes!
Your PHP function is writing to the page already, rendering the document.write (javascript) useless. Try this:
<?php
function profileupdated() {
return "<div id='profileupdated'>Profile updated</div>";
}
?>
I do want to note though that you might want to consider a cleaner way of doing this: If you just want to display a fixed text ("Profile updated"), stick to pure client-side Javascript.
Otherwise (if there's logic to be done server-side), you might want to decouple server and client and use an AJAX call and JSON to transfer your data.
PHP is a server side programming language, you are executing the JavaScript on the client side.
If you want to call a PHP script from your JavaScript you need Ajax, f.e. jQuery.

GET with javascript instead of PHP to track stats

I use a simple PHP script placed on each page of my websites to track some stats.
<?php
echo( "<img src='http://maindomain.com/stats.php?var1=" . #$_GET['var1'] . "&var2=" . #$_GET['var2'] . "&r=" . #$_SERVER['HTTP_REFERER'] . "' width='1' height='1' border='0' />" );
?>
This script works fine, once placed on domain1.com and domain2.com the file in maindomain.com/stats.php must validate the GET and register the stats.
The problem is that i also have domain3.com and this site is not PHP but simple HTML.
So i'm looking for a way to change the script in javascript, something like this:
<script src="http://maindomain.com/stat.php?var1=XXX&var2=YYY&r=HTTP_REFERER"></script>
I think this is possibile but i don't know how to pass the GET vars with js.
You could try using CSS instead of JavaScript.
If you create your stylesheet as such; style.css.php, you can execute php code in the stylesheet, and let the rest of the stylesheet just be as it already is.
Something like:
<?php
include('stats.php')
?>
html {
color: #000
}

How do I embed Javascript in PHP code?

I have a HTML form and PHP code. In my form, I have a textbox and a textarea. Within both, I have included the "disabled" option. I want both textboxes to remain disabled until the user decides to click the "Edit" button, in which case both textboxes should be enabled so changes can be made and the output once again saved. According to the research I have done, the only way to do this is to use javascript, so I have included the following code within my PHP;
if (isset($_POST['edit']))
{
echo "<script type=\"text/javascript\">";
echo "var oldnotes = document.getElementById('oldnotes');";
echo "oldnotes.disabled = false;";
echo "var record = document.getElementById('record');";
echo "record.disabled = false;";
echo "</script>";
}
I have also tried;
if (isset($_POST['edit']))
{
echo "<script type=\"text/javascript\">";
echo "$('#oldnotes').removeAttr('disabled')";
echo "$('#record').removeAttr('disabled')";
echo "</script>";
}
But no luck :(
I am not receiving any errors, the textboxes just remain disabled after I click the Edit button. Could anyone help me with this? Thanks in advance.
This is a better approach for these kind of problems :
if (isset($_POST['edit'])){
?>
<script type="text/javascript">
var oldnotes = document.getElementById('oldnotes');
oldnotes.disabled = '';
var record = document.getElementById('record');
record.disabled = '';
</script>
<?php
}
<?
<script language='javascript'>
(javascript code here)
</script>
?>
Try use onclick on your Button
<input type="button" name="edit" id="edit" onclick="document.getElementById('oldnotes').disabled=false; document.getElementById('record').disabled=false; return false;">
I hope it helps.
The second approach seems correct, but you're missing ; there. Also, you haven't put any newline characters.
Here's what I suggest:
<?php
if (isset($_POST['edit'])) {
?>
<script type="text/javascript">
alert("Check entry"); // Use this for checking if your script is reaching here or not
$('#oldnotes, #record').removeAttr('disabled');
</script>
<?php
}
?>
You don't need to echo the whole thing. You can simply put it out of the PHP and keep it inside a if block.
Also, I've kept the alert to check if your code structure is proper. If you're getting the alert on clicking the edit button, means you're on the right path. You just need to workout on the JS.
If not, something wrong with your edit button and the form POST
Use single quotes for script type
echo "<script type='text/javascript'>\n";
//javascript goes here
echo "</script>";
use this jquery code:
<script>
$('#oldnotes,#record').attr('disabled','')
</script>
If you want to use JS with PHP you can read here:
how to write javascript code inside php
However: it seems you want the JS to be called on it own accord upon evaluation in the php logic as per the implementation provided.
Technically speaking your JS simply states it should re-enable the controls. Rather add the JS functionality to the OnClick of the submitting control and it should work fine. This is a quicker way of testing the functionality as well.
<a href="javascript:void(0);" onclick="document.getElementById('oldnotes').disabled=false;" >
Once it is clicked it will hide the appropriate control instead of trying to write new JS on the fly that is not executed. This is tried and tested and should work fine for you.
Hope it helps!
you can always make a cookie
use document.cookie()
set the onclick=“” to changing the cookie
and make a script that runs and gets the cookie when you open the site (use window.onload = function(){/*code goes here*/})

Categories