Displaying result of PHP function in a div - javascript

So I am building a site in Wordpress and am allowing the user to register/login. However I would like to create a custom nav bar instead of the awful 'admin bar' and so I want to be able to load the user name into an html element. I know that the username can be retrieved with this php:
<?php wp_get_current_user(); ?>. But what I want to know is, what is the best way to pull that into a JS variable that can then be set to be the inner html of an element. Is there another more direct way to do this? I also looked at JSON but couldn't find much that relates to this kind of scenario.
Any help is much appreciated.

Use echo:
<div>
<?php echo wp_get_current_user(); ?>
</div>
You can add this to a JavaScript variable in the same way:
<script>
var username = "<?php echo wp_get_current_user();?>";
</script>
EDIT Looking at the WP function reference, the wp_get_current_user() is an object, and you can access its variables like so:
<?php
$current_user = wp_get_current_user();
echo 'Username: ' . $current_user->user_login . '<br />';
echo 'User email: ' . $current_user->user_email . '<br />';
echo 'User first name: ' . $current_user->user_firstname . '<br />';
echo 'User last name: ' . $current_user->user_lastname . '<br />';
echo 'User display name: ' . $current_user->display_name . '<br />';
echo 'User ID: ' . $current_user->ID . '<br />';
?>
Therefore, you can use this script to output the display name into a div element:
<?php $current_user = wp_get_current_user(); ?>
<div>
<?php echo $current_user->display_name; ?>
</div>

Related

HTML Quotes are making a mess

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!

Add onclick event to a dynamic created link (PHP)

I have many links which are dynamically created with PHP and now I want to add an onclick event.
while($row = mysqli_fetch_array($xyz)) {
echo "<tr>";
echo "<td><a href=\"test.php?parameter=". $row['z'] ."\" target=\_blank>" . $row['z'] . "</a></td>";
echo "</tr>";}
but I want like this:
while($row = mysqli_fetch_array($xyz) {
echo "<tr>";
echo "<td><a href=\"test.php?parameter=". $row['z'] ."\" target=\_blank>" . $row['z'] . onclick="test()"</a></td>";
echo "</tr>";}
is this possible?
I am not sure if I understood what exactly you are asking but I try to answer you the same:
You can't record a normal JS variable in a page session and then to access to it after the loading of a page.
For this case you can use cookies (that are accessible via server-side too):
// put this code into methods that users suggested you.
document.cookie = "value_selected=something"
and once page is loaded:
var cookies = document.cookie.split(';');
var value_selected = JSON.parse(JSON.stringify(cookies[YOUR_COOKIE].split("=")[0]))
or server side:
echo "<td><a href=\"test.php?parameter=". $row['z'] ."\" data-something=htmlentities($_COOKIE['value_selected']) target=\_blank>" . $row['z'] . "</a></td>"; //(example)
Or more simply, pass the value selected through query
?value_selected=something //elaborate the new link in the method users suggested you
and
in server-side, use $['GET'] to obtain all values in query string.
IMHO I think the first choice is simpler than second.
I hope I helped you
Try Like this
while($row = mysqli_fetch_array($xyz) {
echo "<tr>";
echo "<td><a class='myclick' href=\"test.php?parameter=". $row['z'] ."\" target=\_blank>" . $row['z'] . **onclick="test()"**</a></td>";
echo "</tr>";}
i have added a class to link as myclick
and in jquery
$(document).on('click','.myclick',function(e){
e.preventDefault();
alert('clicked');
});
You can try like this..just a simple way.
<script type="text/javascript">
function test(){
alert('test');
}
</script>
<?php
while($row = mysqli_fetch_array($xyz) {
echo "<tr>";
echo "<td><a href='your link' onclick='test()'></a></td>";
echo "</tr>";
}
?>

Passing javascript array via POST to PHP does not working

I need to pass a javascript array, via POST, to a PHP file.
I've tried to semplify my original business trying to explain my troubles ...
This is my first PHP file, in which I declare a javascript array and I set each element to 1 value (not a great business I know, but it doesn't matter, it's only to explain ....)
<?php
echo '<form action="testPhp-2.php" method="POST" target="testPhp-2">';
echo '<script type="text/javascript">';
echo 'var arr_selections = [];';
echo 'for(i=0; i < 10; i++)';
echo ' {';
echo ' arr_selections[i] = 1';
echo ' }';
echo 'arr_selections_json = JSON.stringify(arr_selections);';
echo 'alert (arr_selections[2]);';
echo 'document.write("<br/>");';
echo ' ';
// echo 'document.write("<input type="hidden" />");';
echo 'document.write("<input type=\"hidden\" name=\"arr_selections_json\" value=\"arr_selections_json\" />");';
echo ' ';
echo '</script>';
echo ' <input type="submit" value="Controlla">';
echo ' </form>';
?>
.... and here you are the code of testPhp-2 file ...
<?php
if(isset($_POST['arr_selections_json']))
{
echo "OK, array exist !! ";
echo '</br>';
echo '</br>';
$arr_selections = json_decode($_POST['arr_selections_json'], true);
echo $arr_selections[0];
}
else {
echo "NO; array does not exist !! ";
echo '</br>';
echo '</br>';
}
?>
Now, if you try to execute the code you'll see the OK, array exist !! message but no array value is printed about the echo $arr_selections[0]; line of code in testPhp-2.php file.
Any suggestion will be appreciated! Thank you in advance!
Cesare
Problem is that you're setting the value of the input to the litteral string "arr_selections_json" instead of to the contents of that variable.
Change
echo 'document.write("... value=\"arr_selections_json\" />");';
To
echo 'document.write("... value=\""+arr_selections_json+"\" />");';

Change button text from "Like" to "Liked" when clicked

I am creating a forum where users are able to like and unlike posts and comments. The challenge I'm facing is that I would like the text of the like button to change without reloading the page. How can I go about differentiating between the buttons on the page and change individual button-texts from "Like" to "Liked" and vice versa? The buttons are, at the moment created and show like this:
<?php
$result3=mysqli_query($link, "SELECT * FROM cs_comments WHERE post_id = $postID");
while($row3 = mysqli_fetch_assoc($result3)){
$commentID=$row3['comment_id'];
$memberID=$row3['member_id'];
$likes=$row3['likes'];
$content= $row3['content'];
$anonymous=$row3['anonymous'];
if($anonymous=='1')
$name='Anonym';
else{
$result4= mysqli_query($link, "SELECT firstname, lastname FROM cs_members WHERE member_id = $memberID");
$row4=mysqli_fetch_assoc($result4);
$name = '' . $row4['firstname'] . " " . $row4['lastname'] . '';
}
$result5=mysqli_query($link,"SELECT * FROM cs_likes WHERE comment_id=$commentID AND member_id={$_SESSION['memberID']}");
if(mysqli_num_rows($result5)!=0)
$liked="unlike";
else
$liked="like";
echo '<div class="post_container">';
echo ' <div class="info_header">';
echo ' <div class="info_name">' . $name . '</div>';
echo ' <div class="info_group"></div>';
echo ' </div>';
echo ' <div class="post_content">';
echo $content;
echo ' </div>';
echo ' <div class="post_footer">';
echo ' <div class="like_button"><button onclick="likeComment('. $commentID . ')">' . $liked . '(' . $likes . ')</button></div>';
echo ' </div>';
echo '</div>';
}
mysqli_close($link);
?>
Javascript for onclick-event:
function likeComment(id) {
$.ajax({
url: '/resources/phpScript/like.php',
type: 'POST',
data: {comment_id:id},
success: function(data) {
console.log(data); // Inspect this in your console
}
});
Like.php
<?php
session_start();
include "./db-connect.php";
$memberID= $_SESSION['memberID'];
if(isset($_POST['post_id'])){
$postID=mysqli_real_escape_string($link,$_POST['post_id']);
$sqlCheck="SELECT * from cs_likes WHERE post_id = $postID AND member_id = $memberID";
$sqlInsert="INSERT INTO cs_likes (post_id, member_id) VALUES ('$postID','$memberID')";
$sqlDelete="DELETE FROM cs_likes WHERE post_id= $postID AND member_id = $memberID";
}
elseif(isset($_POST['comment_id'])){
$commentID=mysqli_real_escape_string($link,$_POST['comment_id']);
$sqlCheck="SELECT * from cs_likes WHERE comment_id = $commentID AND member_id = $memberID";
$sqlInsert="INSERT INTO cs_likes (comment_id, member_id) VALUES ('$commentID','$memberID')";
$sqlDelete="DELETE FROM cs_likes WHERE comment_id= $commentID AND member_id = $memberID";
}
else
echo "Something went wrong";
$checkResult=mysqli_query($link, $sqlCheck);
if(mysqli_num_rows($checkResult)==0)
$result=mysqli_query($link,$sqlInsert);
else
$result=mysqli_query($link,$sqlDelete);
?>
Any help is appreciated!
So I found the solution! I have little to no experience with javascript, which is why this may have been too simple of a question for anyone to find out what I was after!
This is what I did:
I simply sent the element clicked by adding this to the function call on click:
echo ' <div class="like_button"><button onclick="likePost('. $postID . ',this)">' . $liked . '</button></div>';
I then added this tiny bit to my function:
function likePost(id, elem) {
if(elem.innerHTML== "like")
elem.innerHTML="unlike";
else
elem.innerHTML="like";
I still want to thank everyone who made and effort to try understanding what I was asking.

Wordpress - Unable to use variable

Testing out Wordpress on WAMP by creating a basic plugin.
Scenario:
Created an Admin panel with a form that just contains a text area and button. The form will be used to insert JavaScript code and this code will be placed in the header of all pages. I'm having issues trying to access the text area value within function post_tag. Code below:
<?php
add_action('admin_menu', 'setup_menu');
function setup_menu(){
add_menu_page( 'Tag Menu', 'Tag Menu', 'manage_options', 'tag-menu', 'html_form' );
}
function html_form(){
echo '<h1>JavaScript Tag</h1>';
echo '<form action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post">';
echo '<p>';
echo 'Paste your code below: <br/>';
echo '<br/>';
echo '<textarea rows="10" cols="150" name="tag"></textarea>';
echo '</p>';
echo '<p><input type="submit" name="tag-submit" value="Submit"></p>';
echo '</form>';
if(isset($_POST['tag-submit'])){
$tag = esc_textarea(stripslashes($_POST["tag"]));
echo '<p>Your tag has been placed on all pages!</p>';
return $tag;
}
}
$value = html_form();
add_action('wp_head', 'post_tag');
function post_tag(){
global $value;
$output = $value;
echo $output;
}
?>
Can't seem to output the value in $tag to the header pages.Any help would be much appreciated.
If you don't have any reason to structure it the way you did, try this, which is cleaner
add_action('wp_head', 'post_tag');
function post_tag(){
$output = html_form();
echo $output;
}

Categories

Resources