Wordpress - Unable to use variable - javascript

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;
}

Related

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+"\" />");';

Displaying result of PHP function in a div

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>

PHP and Javascript : Multiple Buttons inside a table

I'm working with PHP, Javascript and MySQL. My goal is to have a button on each row. The button should call the onclick fucntion and href to another page.
My problem with my code -- > only the button from the first row is clickable...
I'm assuming the Button ID needs to be unique for each button.. What are my options to make all buttons clickable ?
// printing table rows
while($row = mysqli_fetch_row($result))
{
echo "<tr>";
echo "<td><button id='greenbutton' class='small pill green'>$row[0]</button></td>";
echo "<td><img src='/iframe/$row[7]'>&nbsp$row[5]</td>";
echo "<td>$row[4]&nbspmin(s)</td>";
echo "<td><img src='/iframe/$row[6]'>&nbsp$row[2]</td>";
if ($row[3] == 0) {
echo "<td>Unknown</td>";
}
else {echo "<td>$row[3]</td>";}
echo "</tr>\n";
// FOR ONCLICK
echo "<script type='text/javascript'>";
echo "document.getElementById('greenbutton').onclick = function () {";
echo "location.href = '/user';";
echo "};";
echo "</script>";
}
echo "</table></center>";
You're id's of your dom elements should be unique at all time. To achieve this you can add a counter in your while so that all of your button have an id like 'greenbutton1', 'greenbutton2', 'greenbutton3', etc.
$cnt = 1;
// printing table rows
while($row = mysqli_fetch_row($result))
{
echo "<tr>";
echo "<td><button id='greenbutton$cnt' class='small pill green'>$row[0]</button></td>";
echo "<td><img src='/iframe/$row[7]'>&nbsp$row[5]</td>";
echo "<td>$row[4]&nbspmin(s)</td>";
echo "<td><img src='/iframe/$row[6]'>&nbsp$row[2]</td>";
if ($row[3] == 0) {
echo "<td>Unknown</td>";
}
else {echo "<td>$row[3]</td>";}
echo "</tr>\n";
$cnt++;
}
echo "</table></center>";
In that exemple I didnt add your javascript function into your while loop because it look like the same function for all your buttons. I suggest you add the function only once but bound it with the class selector instead of the id selector like this.
// FOR ONCLICK
echo "<script type='text/javascript'>";
echo "document.getElementsByClassName('myGreenButtons').onclick = function () {";
echo "location.href = '/user';";
echo "};";
echo "</script>";
And then add the myGreenButtons class to your buttons in the while loop. You can also use attributes or types selector to gather your dom elements in a more flexible way. Check out theses links for more info:
http://www.w3schools.com/cssref/css_selectors.asp
http://www.htmlgoodies.com/beyond/javascript/using-javascripts-css3-selectors.html#fbid=FhIuAA6GqpH
hope this helps!
echo "<td><a href='/user'><button class='small pill green'>$row[0]</button></a></td>";
...will do the trick.

I am trying to update records by php code. but having trouble in my code

I am trying to update records by php code. but having trouble in my code.
code is running without using functions (get40(),show()) but i want to use buttons to call these functions.
code is give below:
this is main code file:
<?php
$data;
$count=0;
$host='localhost';
$uname='root';
$pass="";
$dbname="testing";
$db=new mysqli($host,$uname,$pass,$dbname);
$result;
$query;
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
function get40($off='0', $rcd='2')
{
global $db,$result,$query;
$query="SELECT sword, tword, reviewed from TempDictionary LIMIT $off,$rcd";
$result = $db->query($query)or trigger_error($db->error);
}
function show()
{
global $db,$result,$query;
echo "<form action='testSave.php' method='POST'>";
echo "<table border=1 >";
while($row = mysqli_fetch_array($result))
{
global $count;
$count+=1;
echo "<tr>";
echo "<td><input type='text' name='s[]' value=" . $row['sword'] . "></td>";
echo "<td><input type='text' name='t[]' value=" . $row['tword'] . "></td>";
echo "<td><input type='text' name='r[]' size='1' value=" .$row['reviewed'] . "></td>";
echo "</tr>";
}
echo "</table>";
echo "<input type='text' name='no' size='2' value=" .$count. ">";
echo "<input type='submit' value='Save'>";
echo "</form>";
}
//get40(1,2);
//show();
mysqli_close($db);
?>
<script type="text/javascript">
function get()
{
<?php
get40(0,3);
show();
?>
}
</script>
<form action="" method="POST">
<input type=button name=btnGet value=Get onclick="get()">
</form>
and savetest.php file is:
<?php
$no=$_POST['no'];
$i=0;
$s=$_POST['s'];
$t=$_POST['t'];
$r=$_POST['r'];
$host='localhost';
$uname='root';
$pass="";
$dbname="testing";
$db=new mysqli($host,$uname,$pass,$dbname);
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
// display
foreach ($s as $key=>$value)
{
print "$key = $value $t[$key] $r[$key]";
echo '<br>';
}
// save to DB
foreach ($s as $key=>$value)
{
// $query="UPDATE TempDictionary set sword=".$value.",tword=".$t[$key].",reviewed=".$r[$key]."
// WHERE sword=".$value;
$query="UPDATE TempDictionary set sword='$value',tword='$t[$key]',reviewed='$r[$key]'
WHERE sword='$value'";
$result = $db->query($query)or trigger_error($db->error);
}
mysqli_close($db);
?>
the problem is while i click button it does not works.
AFAIK you are trying to run PHP code with Javascript code.
Use Jquery/Ajax to solve your problem. You can Google for that or look at stackoverflow.
Step 1: Learn how a click on a button can run PHP
Run php function inside jQuery click
Step 2: Learn how to use data from a database and populate a form with it:
ajax call to populate form fields from database query when select value changes
That's the first step in solving your problem. (sorry it's no copy/paste solution, just a pointer in the right direction)

Two different actions in one form

I have a form with two different submit buttons. One is to delete the corresponding row in the MySQL, which is done on the same page, the other is to save the row to another database, which is done on a separate page. The delete action works fine, but I cannot figure out how to send the save form data to the other page without putting it in the "action" value. I've tried JavaScript, but haven't had much luck. It's a bit of a lengthy post, but I figure the more information I give, the easier it will be for a solution to be found.
Here's just the save submit button:
echo "<td><input type=\"submit\" name=\"save\" value=\"Save\" onclick=\"this.form.action='publishmod.php'\"></td>";
Here's the form code (main page):
echo "<form name=\"editmod\" method=\"post\">";
echo "<tr class='modlist'>";
echo "<td>".$row['id']."</td>";
echo "<td><div class=\"edit\" id=\"div_1\">".$row['title']."</div></td>";
echo "<td><div class=\"edit\" id=\"div_2\">".$row['mod_url']."</div></td>";
echo "<td><div class=\"edit\" id=\"div_3\">".$row['developer']."</div></td>";
echo "<td><div class=\"edit\" id=\"div_4\">".$row['type']."</div></td>";
echo "<td><div class=\"edit\" id=\"div_5\">".$v162."$nbsp".$v164."$nbsp".$v172."</div></td>";
echo "<td><div class=\"edit\" id=\"div_6\">".$row['title'].",$nbsp".$row['developer']."</div></td>";
echo "<td><input type=\"submit\" name=\"save\" value=\"Save\" onclick=\"this.form.action='publishmod.php'\"></td>";
echo "<td><input type=\"submit\" name=\"delete\" value=\"Delete\"></td>";
echo "</tr>";
echo '<input type="hidden" name="id" value="', htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8'), '" />';
echo '<input type="hidden" name="id" value="', htmlspecialchars($row['mod_url'], ENT_QUOTES, 'UTF-8'), '" />';
echo '<input type="hidden" name="id" value="', htmlspecialchars($row['developer'], ENT_QUOTES, 'UTF-8'), '" />';
echo '<input type="hidden" name="id" value="', htmlspecialchars($row['type'], ENT_QUOTES, 'UTF-8'), '" />';
echo '<input type="hidden" name="id" value="', htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8'), '" />';
echo "</form>";
}
Publish code (page that the save action is supposed to redirect to):
Variable sanitation omitted for Stack Overflow purposes.
$name = $_GET['title'];
$desc = "Installation tutorial for '.$name.'";
$url = ereg("^[A-Za-z_\-]+$", $name) + ".php";
$keywords = "'.$name.', '.$dev.'";
$type = $_GET['type'];
$link = $_GET['mod_url'];
$dev = $_GET['developer'];
$id = $_GET['id'];
// Query
$savequery = "INSERT INTO search (title, description, url, keywords, type, mod_url, developer, v162, v164, v172)
VALUES ('$name', '$desc', '$url', '$keywords', '$type', '$link', '$dev', '$v162', '$v164', '$v172')";
// Mod file creation
$file = ereg("^[A-Za-z_\-]+$", $name) + ".php";
$handle = fopen($file, 'w');
$data = '<?php
$title = "'. $name. '";
$keywords = "'. $name. ','. $developer. '";
$description = "How to install '. $name. ' for PC and Mac.";
include("templates/modheader.php");
include("templates/modfooter.php");
?>';
$save = $dbsave->query($savequery) or die(mysqli_error($dbsave));
// Run creation
echo $save;
fwrite($handle, $data);
print " mod file created!";
fclose($handle);
?>
Don't send it to another page. Use one page and branch with an if (or switch or whatever) statement.
e.g.
if (isset($_POST['save'])) {
include('save.php');
} elseif (isset($_POST['delete'])) {
include('delete.php');
} else {
# logic for when the page is arrived at without the form being submitted with a submit button
}
As an aside. A <form> may not be the parent element of a <tr>, and no element that may have a <td> as a child element may also have an <input> as a child element, you will find some browsers will move elements around to make them acceptable in a way that is going to break your form. Write valid HTML.
I Think you should change type of submit to button for both delete and save and the use following jquery code:
$("#savebutton_id").onclick(function(){
$("#formid").attr('action','Your save Page');
$("#formid").submit();
});
$("#deletebutton_id").onclick(function(){
$("#formid").attr('action','Your delete Page');
$("#formid").submit();
});
you can send data to other pages using hyperlink
eg:Shoes
we can get the category variable in the next page by using
$_GET['category'];

Categories

Resources