I need to insert logged in user's username and email in an existing input automatically.
I tried the following code, but it doesn't insert the value in the input. I test echo $username and $user_email, it shows correct user info).
Would you please let me know how to solve this?
Existing input code (created by YITH plugin):
<from id="yith-ywraq-default-form">
<input type="text" class="input-text " name="first_name" id="first_name" placeholder="" value="">
<input type="email" class="input-text " name="email" id="email" placeholder="" value="">
</form>
Code I tried:
$autofillNameEmail = <<<EOD
<script>
(function thisFunction() {
$("input[name=first_name]").val(Print($username););
$("input[name=email]").val(Print($user_email););
})();
</script>
EOD;
$user = wp_get_current_user();
$username = $user->user_login;
$user_email = $user->user_email;
if( $user->ID ) {
echo $autofillNameEmail;
}
Thank you.
My initial thought is the javascript part of your code. Although it's not a good practice to pass php variables to a page in a way you did, but the main point in your code is whenever you want to use jQuery in wordpress, you need to explicitly tell wordpress that you need $ from jQuery. So i'd say, run the following snippet instead.
This is NOT a good practice to pass php variables to a page nor the correct way to inject javascript to a page. It is NOT recommended to use this in production! Instead consider it as a learning opportunity and go learn about wp_localize_script and wp_enqueue_script.
global $current_user;
$user_name = $current_user->user_login;
$user_email = $current_user->user_email;
if ($current_user->ID) { ?>
<script>
jQuery(document).ready($ => {
let userName = "<?php echo $user_name ?>";
let userEmail = "<?php echo $user_email ?>";
$("input[name=first_name]").val(userName);
$("input[name=email]").val(userEmail);
});
</script>
<?php }
Tested and works!
Related
I posted two javascript variables to a php file aswell as a html form using Ajax separately. I want to use the two javascript variables with the posted form values but I'm not sure how to go about this.
<script>
$(document).ready(function() {
var aucid = "<?php echo $auctionID; ?>";
var userid = "<?php echo $userID; ?>";
$.ajax({
url: "JqueryPHP/HighestBid.php",
method: "POST",
data: {'auctionid': aucid, 'userid' : userid },
success: function (result) {
$('#price').html(result);
}
});
$('form').bind('submit', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
type: 'POST',
url: 'JqueryPHP/HighestBid.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
I posted the two javascript variables separately to the form.
<form>
<input type="number" min="<?php echo $startingprice ?>" step="any" style="width: 10em;" size="35" name="newbid" id="newbid" tabindex="1" class="form-control" placeholder="New Bid €" value="" required>
<input type="submit" name="submit" id="submit" tabindex="2" class="form-control btn btn-login" style="width: 14em" value="submit">
</form>
<h4 class="price">Highest bid : <span id="price"></span></h4>
When I echo the value of userID into the span class, you can see it has a value of 2.
//JqueryPHP/HighestBid.php'
$auctionid;
$userID;
$auctionid = $_POST['auctionid'];
$userID = $_POST['userid'];
echo $userID;
if (isset($_POST['newbid']))
{
$newbid=$_POST['newbid'];
$conn = new mysqli('localhost', 'root', '', 'auctionsite');
$sql = 'INSERT INTO auction (useridhighestbid)VALUES("'.$userID.'")';
if(#$conn->query($sql)){ //execute the query and check it worked
return TRUE;
}
}
however when I try use the userID when the form is submitted and try insert it into the database for testing purposes, the value is 0.
How would I go about posting the form value with the javascript variables so I can use an update statement to update my database?
Set two hidden inputs to save aucid and userid like this:
<form>
<input type="number" min="<?php echo $startingprice ?>" step="any" style="width: 10em;" size="35" name="newbid" id="newbid" tabindex="1" class="form-control" placeholder="New Bid €" value="" required>
<input type="submit" name="submit" id="submit" tabindex="2" class="form-control btn btn-login" style="width: 14em" value="submit">
<input name='aucid' style="display:none"/>
<input name='userid' style="display:none"/>
</form>
<script>
$(document).ready(function() {
$("input[name='aucid']").val("<?php echo $auctionID; ?>");
$("input[name='userid']").val("<?php echo $userID; ?>");
.......................
});
</script>
Send your form to a php script. When the user logs in, retrive his ID from DB and put it in session like this
switch(isset($_POST['login'])):
case 'Register':
$email = htmlspecialchars(trim($_POST['em']), ENT_QUOTES, 'UTF-8');
$password = htmlspecialchars(trim($_POST['pw']), ENT_QUOTES, 'UTF-8');
// check if the combination fname/lname/email is already used
include('./Models/log_check.php');
unset($_SESSION['ID'],$_SESSION['role']);
$_SESSION['ID'] = $row['ID'];
$_SESSION['role'] = $row['role'];
So you can use ID in your Model/query:
<?php
/* Jointure sama RDV des vets */
$query =
"SELECT
appointment.start,
appointment.app_day,
patients.pet_name,
patients.breed,
patients.ID,
clients.last_name,
clients.first_name,
appointment.type,
appointment.canceled
FROM appointment
JOIN patients
JOIN clients
WHERE clients.users_ID = patients.owner_ID
AND patients.ID = appointment.patients_ID
AND appointment.vets_ID = (SELECT ID FROM vets WHERE users_ID = :ID)
AND appointment.canceled = 'n'
AND WEEK(appointment.app_day) = WEEK(:date)
ORDER BY appointment.app_day,appointment.start";
$query_params = array(':ID' => $_SESSION['ID'],
':date' => $date);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
?>
Insert instead of SELECT
Assuming you parsed the variables correctly, you can use:
$_POST['JavaScript_variable_name_goes_here'];
or
$_GET['JavaScript_variable_name_goes_here'];
to retrieve the variables in a PHP format, depending on your AJAX method.
A direct example from your AJAX function would be:
<?php $auctionId=$_POST['auctionid']; ?>
However, what I would encourage you to do, is that once a user is logged in, you set their userId as a session variable that you can use wherever the user "goes". That way, you are not parsing a crucial data element through JavaScript, which is handled client side, meaning that it's fully editable by the user through the use of a browsers dev tools. The same goes for the auctionId. I would recommend a php session variable logic for the exact same reasons. You can always overwrite the auctionId session variable with another auctionId depending on which auction is "in use".
Another good reason to why setting userId as a session variable, is that you will never have any trouble accessing the variable anywhere, as long as you remember to set the following at the very beginning of your PHP files:
<?php session_start(); ?>
The PHP/SQL syntax for the mysqli_* extension would then be the following:
$conn=mysqli_connect("localhost", "root", "", "auctionsite");
$sql="INSERT INTO auction SET useridhighestbid='$userID'";
mysqli_query($conn, $sql);
Let me know if you need anything elaborated, or if you run into any other problems.
You can append the data with the serialize like this in ajax call
data: $("#form_id").serialize() + '&xyz=' + xyz
I am making a news feed something like Facebook and other social media platform. For this, I am making a commenting section for each post on the page. I am trying to make the commenting section live (real time), so that when a comment is posted, the page does not refresh.
I know that the commenting system works because I did a test without real time feature (without the use of any form of javascript code).
The following is my code in brief....i only posted what I believe is necessary based on my issue.
function getposts ()
{
global $con;
$getposts = "SELECT * FROM posts";
if ($result = $con->query($getposts)) {
while ($row1 = $result->fetch_assoc()) {
$postid = $row1['post_id'];
?>
<form action='comments_ins.php' method='post' id='reply'>
<input type="hidden" value="<?php echo $postid;?>"
name="postid"/>
<textarea name="comment" id="comment" class="cmt_form"
placeholder="Type a commmment here..."></textarea>
<input type='submit' name='reply' value='Comment'/>
</form>
<?php
}
}
}
?>
Also, the above script i stored in a file given a name of functions. File is php file.
The following code is stored in a different file that is named as home where the functions file is included:
<?php include("functions.php"); ?>
<?php getposts ();?>
So, as indicated earlier, the above code works well. Now, I have slightly altered the code to make attempts to have the comment system be real time.
The following is the altered code:
function getposts ()
{
global $con;
$getposts = "SELECT * FROM posts";
if ($result = $con->query($getposts)) {
while ($row1 = $result->fetch_assoc()) {
$postid = $row1['post_id'];
?>
<form method='post' id='reply'>
<input type="hidden" value="<?php echo $postid;?>"
name="postid" id="postid" />
<textarea name="comment" id="comment" class="cmt_form"
placeholder="Type a commmment here..."></textarea>
<input type='submit' name='reply' value='Comment'/>
</form>
<?php
}
}
}
?>
//in addition to the java to make it real time
<script type="text/javascript">
$(document).ready(function() {
$(".cmt_form").keypress(function(evt) {
if(evt.which == 13) {
var postid = $("#postid").val();
var body = $("#comment").val();
$.post("comments_ins.php", { postid: postid, comment: body},
function(data) {
$('.log').html(data);
$('#reply')[0].reset();
});
}
});
});
</script>
The above java I included in the same functions.php file but outside of the php tags, not being in any loops. The home file is just the same..no changes.
Finally, the following code is the php file that inserts the comment into the database. File name as seen on previous codes: comments_ins.php
$comment1 = ($_POST['comment']);
$post_id = $_POST['postid'];
global $userId;
$insert1 = "insert into comments (post_id,user_id,comment,date) values
('$post_id','$userId','$comment1',NOW())";
$run1 = mysqli_query($con,$insert1);
The above code works to an extent only:
it's not posting the correct postid value to the database. It's only posting postid 1 even though i commented on another post with a different id number.
Also, it's not inputting the comment into the comment field in the database. I see an empty space..no text.
Finally, the output is some crazy output after posting the comment: some strange numbers and some nonsense.
What have i done wrong?
Please help
I want to check a text field in form that if username exists in database or not.i want it without refreshing page and i am using Wordpress.I know it is possible through ajax but i have tried ajax in Wordpress and any ajax code didn't run on it. Kindly provide any piece of code or any helpful link. Last time i have tried this but didn't work:
<?php
if(!empty($user_name)){
$usernamecheck = $wpdb->get_results("select id from wp_teacher_info where user_name='$user_name'");
if(!empty($usernamecheck)){
echo'username not available';
}
else {
}
}?>
<label for="user_name" id="user_name">Username: </label>
<input type="text" name="user_name" id="user_name" required/>
<span id="user-result" ></span>
<script type="text/javascript">
jQuery("#user_name").keyup(function (e) { //user types username on inputfiled
var user_name = jQuery(this).val(); //get the string typed by user
jQuery.post('teacher_form.php', {'user_name':user_name}, function(data) {
jQuery("#user-result").html(data); //dump the data received from PHP page
});
});
</script>
use
if(!empty($_POST['user_name']){
$user_name = $_POST['user_name'];
to be
<?php
if(!empty($_POST['user_name']){
$user_name = $_POST['user_name'];
$usernamecheck = $wpdb->get_results("select id from wp_teacher_info where user_name='$user_name'");
if(!empty($usernamecheck)){
echo'username not available';
}
else {
}
}
?>
but keyup event will call the ajax each keyup .. you can use **.blur()** instead of **.keyup()**
I have been fighting with this issue for many days and got really stuck.
I'm trying to call a php script which contains code to access mysql database from a html file through javascript. But when I run the following on my NetBeans, I always get error at "$.ajax({" place. And NetBean doesn't specify what error it is. It only says Request was cancelled. Please help me out!!!!
HTML:
<form>
<p><input type="text" name="username" value=""></p>
<p><input type="password" name="password" value=""></p>
<p class="remember_me">
<label>
<input type="checkbox" name="remember_me" id="remember_me">
Remember me on this computer
</label>
</p>
<p><input type="submit" onClick="connect_to_db()" name="submit" value="Login" id="submit"></p>
<script>
function connect_to_db(){
utils.connectToDb(document.getElementsByName("username")[0].value,
document.getElementsByName("password")[0].value);
}
</script>
</form>
api/connect.php:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
try {
$dbh = new PDO('mysql:host=localhost;dbname=mydb', $username, $password);
$insert_cmd = "INSERT INTO version VALUES(1)";
$read_cmd = "SELECT * FROM version";
foreach($dbh->query($insert_cmd) as $row) {
print_r($row);
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
util.js:
window.utils = {
connectToDb: function (username, password) {
$.ajax({
url: 'api/connect.php',
data: {'username': username, 'password': password},
type: 'post',
success: function(output) {
alert(output);
}
});
},
};
NOTE: I have used similar code on Windows, and it worked. I'm currently exporting this to my Mac. I have also enabled php5 module in https.conf and configured my php.ini. I have tested my php and apache using a simple .php file which contains in it. And it is able to display the php information.
If it worked before and you didn't changed the code then its probably a setting.
Check if
Database server running
Database exists (with the same credentials)
Differences in the php version can effect this
AJAX call is to the new server (same domain/host)
the chmod rights are ok
This may not be the best answer but I'm sure this will work because this is the best way to connect to mysql database:
$dblocation="localhost"; //Your db location
$yourusername= "root"; //db name
$yourpass= ""; //blah3x
$dbname = "sample"; //database name
$connect = mysqli_connect($dblocation,$yourusername,$yourpass,$dbname);
You can use either mysql or mysqli but mysqli is much more better.
I would like to extract the users facebook-id and put it into a php-variable.
The code I'm using is from a facebook tutorial video, and its working. I just want to be able to use the user id in a php code.
This is my code:
<form action="" method="post">
<div id="user">
Name: <input name="name" size="27" /><br />
<fb:login-button length="long" onlogin="update_user_box();"></fb:login-button>
</div>
<textarea name="comment" cols="30" rows="5"></textarea><br />
<input type="submit" value="Submit comment" />
</form>
<script type="text/javascript" src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"></script>
<script type="text/javascript">
function update_user_box() {
var user_box = document.getElementById("user");
user_box.innerHTML =
"<span>"
+"<fb:profile-pic uid='loggedinuser'></fb:profile-pic>"
+"Welcome, <fb:name uid='loggedinuser' useyou='false'></fb:name>. "
+"You are signed in with your Facebook account."
+"<fb:uid uid='loggedinuser'></fb:uid>"
+"<a href='#' onclick='FB.Connect.logout(function() { reload(); }); return false;' ><img id='fb_logout_image' src='http://static.ak.fbcdn.net/images/fbconnect/logout-buttons/logout_small.gif' border='0' alt='Connect'/></a>"
+"</span>";
FB.XFBML.Host.parseDomTree();
}
FB.init("API-KEY","xd_receiver.htm");
FB.ensureInit ( function () {
FB.Connect.ifUserConnected(update_user_box);
});
</script>
You can't pass a variable from JavaScript to PHP; JavaScript is a client-side language (ie. it's executed by the browser), whereas PHP is a server-side language (ie. it's executed by the server).
It's possible to pass data from JavaScript to PHP using an XMLHttpRequest (commonly known as AJAX) to send a HTTP request to a PHP script, but I'm not sure that's what you want.
Once the user is logged in (usually using javascript FB.login()), a cookie is set. PHP can access that cookie. Check out the following PHP code (from http://developers.facebook.com/docs/guides/web#login):
<?php
define('FACEBOOK_APP_ID', 'your application id');
define('FACEBOOK_SECRET', 'your application secret');
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
?>
You can then get $cookie('uid'), and use that where you need it.
The page I linked above should have all you need to know about using the JavaScript SDK in conjunction with PHP.
You should include the facebook client library for php and then you can get the user id easily something like this:
include ('facebook_client_library.php');
$facebook = new facebook('API', 'SECRET');
$fbid = $facebook->get_loggedin_user();
echo $fbid;
Or try this javascript (not sure):
alert(FB.Facebook.apiClient.get_session().uid);
Use an array, Check my question Facebook Registration Connect it has the code I used then just add
$fuid = $response["registration"]["user_id"];
Or if that doesn't work then try
$fuid = $response["user_id"];
Hope I've been of help,
Brad