Displaying a php script result in a div using jquery - javascript

I am a beginner on coding. I am working on a WordPress website using beaver builder theme. My challenge is to display a login form (when the user is not logged in) and the user name when he is logged in, to a specific area of the header that has a class "header-text".
Here is my php code located in a file named "file.php"
<?php
if(is_user_logged_in()) {
$user = wp_get_current_user();
$var1 = "<p>Welcome <?php echo $user->display_name; ?></p>
<p><a href='/login/login.php?logout=true'>Click here to log out</a></p>";
$var2 = "<form action='login.php' method='post'>
<input type='text" autocomplete='off' placeholder='Username' name='username'/>
<input type='text' autocomplete='off' placeholder='Password' name='password'/>
<button type='submit' value='Submit'>Submit</button>
</form>";
echo echo json_encode($var1);
} else {
echo echo json_encode($var2);
}
?>
Here is javascript
<script type="text/javascript">
jQuery(document).ready(function($){
function displayAccess() {
$.get("login/file.php");
return false;
}
if(<?php echo json_encode($var1); ?>) {
var variable1 = <?php echo json_encode($var1); ?>;
document.getElementByClassName("header-text").innerHTML = variable1;
}
if(<?php echo json_encode($var2); ?>){
var variable2 = <?php echo json_encode($var2); ?>;
document.getElementByClassName("header-text").innerHTML = variable2;
}
});
</script>
I need help to correct my script. Thanks!

in this case, javascript an jquery is not necessary, because the login status changes on reload, anyway.
all you need is a change in your php code:
<?php
/* put this to your template file (e.g. header.php) */
if(is_user_logged_in()) {
$user = wp_get_current_user();
/* change $var1 to echo it via html block inside php */
?>
<p>Welcome <?php $user->display_name; ?></p>
<p>Click here to log out</p>
<?php
/* cut $var2 because it is not accessible in the else clause */
} else {
/*
paste $var2 here and echo it
btw:
* For tags that are self-closing, the forward slash should have exactly one space preceding it (https://make.wordpress.org/core/handbook/best-practices/coding-standards/html/#self-closing-elements)
* use single or double quotes – make a decision!
*/
?>
<form action="login.php" method="post">
<input type="text" autocomplete="off" placeholder="Username" name="username" />
<input type="text" autocomplete="off" placeholder="Password" name="password" />
<button type="submit" value="Submit">Submit</button>
</form>
<?php
}
?>

Related

How can I update any row rather than only the top row with the update button on each side in PHP and AJAX

just starting out so gonna sound like a noob question but how can I use the update button to update individual rows rather than only the top row.
Whenever I use the update button, the request only goes through if it was the top row.
This is the code for the index.php
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<center>
<h3>UPDATE DATA</h3>
<?php
$run = 0;
$conn = new mysqli('localhost', '', '', '');
$sql = "SELECT * FROM moderator";
$result = $conn->query($sql);
while ( $row=mysqli_fetch_assoc($result)) {
$run = $run + 1;
?>
<div>
ID<input type="text" id="id" value="<?php echo $row['id']; ?>">;
Moderator<input type="text" id="mod" value="<?php echo $row['name']; ?>">;
Category<input type="text" id="ctgr" value="<?php echo $row['category']; ?>">;
<button type="submit" id="update" rel="<?php echo $run; ?>">UPDATE</button>
</div>
<?php
}?>
</center>
<script>
$(document).ready(function(){
$("#update").click(function(){
var name=$("#mod").val();
var ctgr=$("#ctgr").val();
var id=$("#id").val();
$.ajax({
url:'update.php',
method:'POST',
data:{
name:name,
ctgr:ctgr,
id:id
},
success:function(response){
alert(response);
}
});
});
});
</script>
</body>
This is the code for the update.php
<?php
$conn = new mysqli('localhost', '', '', '');
$name=$_POST["name"];
$ctgr=$_POST["ctgr"];
$id=$_POST["id"];
$sql="UPDATE moderator set name='$name', category='$ctgr' where id='$id'";
if($conn->query($sql)===TRUE){
echo "DATA updated";
}
?>
You can probably see I'm trying to create an individual variable for each row but I can't figure it out. Sorry, code's very messy too.
I've removed datebase information but the rows display when credentials are inserted.
This is because you have duplicated input ids, you should have only one ID with the same value on html, this is valid some how, you don't get an error, but you will have trouble in javascript when you try to access those id, you will get only the first one.
To fix this you can remove id and put it as class:
<div>
ID<input type="text" class="id" value="<?php echo $row['id']; ?>">;
Moderator<input type="text" class="mod" value="<?php echo $row['name']; ?>">;
Category<input type="text" class="ctgr" value="<?php echo $row['category']; ?>">;
<button type="submit" class="update" rel="<?php echo $run; ?>">UPDATE</button>
</div>
and use this JS:
$(document).ready(function(){
$(".update").click(function(){
var container = $(this).closest('div'); // parent div
var name = container.find('.mod').val();
var ctgr = container.find('.ctgr').val();
var id = container.find('.id').val();
$.ajax({
url:'update.php',
method:'POST',
data:{
name:name,
ctgr:ctgr,
id:id
},
success:function(response){
alert(response);
}
});
});
});
All your rows input elements have same id attribute
Like id of first rows elements are like id, mod, ctgr
Also id of second rows elements are id, mod ctgr
Jquery find first element, if multiple elements of same id there
You can make unique id by apppending a uniqe incremental variable $run to it as
ID<input type="text" id="id"+<?php echo $run; ?> value="<?php echo $row['id']; ?>">; Moderator<input type="text" id="mod"+<?php echo $run; ?> value="<?php echo $row['name']; ?>">; Category<input type="text" id="ctgr"+<?php echo $run; ?> value="<?php echo $row['category']; ?>">; <button type="submit" id="update" rel="<?php echo $run; ?>" onclick="updatetodb( <?php echo $run; ?>);“ >UPDATE</button>
Then create a javascript function with name updatetodb with one argument, and identify row by that argument as
function updatetodb(var run) {
var id=$('#id' +run).value;

Php javascript conflict in wordpress template file

I have built a contact form for my wordpress site. Four fields are there - name, email, subject, message. For logged in users I want their name and email to be auto-filled in their respective fields in the form and those name, email fields will be disabled for them to edit. And for non-logged in users they will put name, email fields manually. I have put this code in the page template file -
<?php
$current_user = wp_get_current_user();
$user_email = $current_user->user_email;
$user_name = $current_user->user_firstname.' '.$current_user>user_lastname;
if ( 0 != $current_user->ID ) {
echo '<script type="text/javascript">
document.getElementById("curUserName").value = "'.$user_name.'";
document.getElementById("curUserName").disabled = "disabled";
document.getElementById("curUserEmail").value = "'.$user_email.'";
document.getElementById("curUserEmail").disabled = "disabled";
</script>';
}
?>
But this code is disabling name, email fields for both users (logged in and non-logged in). I have controlled the script through if condition. Still the javascript is applying for both users. Please advise where I have gone wrong.
Here is the form html -
<form action="/success.php" method="post">
<label>Name :</label><br>
<input type="text" id="curUserName" name="sender_name" required><br>
<label>Email :</label><br>
<input type="text" id="curUserEmail" name="sender_email" required><br>
<label>Subject :</label><br>
<input type="text" name="sender_sub"><br>
<label>Message</label><br>
<textarea name="sender_msg" rows="4" cols="60" required></textarea><br>
<input type="submit" name="submit" value="Send">
</form>
The source you are going to change has disabled option already.. so just remove it if the user is not logged in :)
<?php
$current_user = wp_get_current_user();
$user_email = $current_user->user_email;
$user_name = $current_user->user_firstname.' '.$current_user>user_lastname;
echo '<script type="text/javascript">';
if ( 0 != $current_user->ID )
{
echo 'document.getElementById("curUserName").value = "'.$user_name.'"
document.getElementById("curUserName").disabled = "disabled"
document.getElementById("curUserEmail").value = "'.$user_email.'"
document.getElementById("curUserEmail").disabled = "disabled"';
}
else
{
echo 'document.getElementById("curUserName").disabled = false;
document.getElementById("curUserEmail").disabled = false;';
}
echo '</script>';
?>
Don't echo javascript with php. It's bad practice.
Try using value tags in your inputs, check if user logged in with a ternary operator, and if so, echo to value tag their credentials.
<?php (is_user_logged_in()) ? $current_user = wp_get_current_user() : $current_user = false; ?>
<label>Name</label>
<input type="text" id="curUserName" name="sender_name" value="<?php ($current_user) ? echo $current_user->user_name : '' ?>" required>
<label>Email</label>
<input type="text" id="curUserEmail" name="sender_email" value="<?php ($current_user) ? echo $current_user->user_email : '' ?>" required>

Codeigniter - form error display underneath the input field

I am trying to display a form error underneath the input fields but after I click the submit button it will redirect to another page...
Here's my code page controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Pages extends CI_Controller{
public function view($page = 'home'){
if(!file_exists(APPPATH.'views/pages/'.$page.'.php')){
show_404();
}
$data['title'] = ucfirst($page);
$this->load->view('template/header');
$this->load->view('pages/'.$page);
$this->load->view('template/footer');
}
public function login(){
echo $this->input->POST('username');
}
public function registercheck(){
echo $this->input->POST('username');
echo $this->input->POST('pwd');
echo $this->input->POST('pwd2');
echo $this->input->POST('fname');
echo $this->input->POST('position');
echo $this->input->POST('contactnumber');
$this->form_validation->set_rules('username', 'USERNAME', 'required|max_lenght[20]');
$this->form_validation->set_rules('pwd', 'USERNAME', 'required|max_lenght[20]');
$this->form_validation->set_rules('pwd2', 'UPPERCASE', 'required|max_lenght[20]');
$this->form_validation->set_rules('fname', 'USERNAME', 'required|max_lenght[20]');
$this->form_validation->set_rules('position', 'USERNAME', 'required|max_lenght[20]');
$this->form_validation->set_rules('contactnumber', 'USERNAME', 'required|max_lenght[20]');
if($this->form_validation->run() == false){
$this->load->view('pages/register');
} else{
echo 'register ok';
}
}
}
?>
And here is my views/pages/register.php
<form action="<?php echo base_url(); ?>pages/registercheck" method="post">
<input type="text" class="form-control" id="username" name="username" value="<?php echo set_value('username'); ?>" >
<?php if (form_error('username')) { ?>
<span class="help-block"><?php echo form_error('username'); ?> </span>
<?php } ?>
<input type="text" class="form-control" id="username" name="username" value="<?php echo set_value('username'); ?>" >
<?php if (form_error('username')) { ?>
<span class="help-block"><?php echo form_error('username'); ?> </span>
<?php } ?>
</form>
Please help me..
What am I doing wrong?
Thank you in advance!
You are in the right direction. But to achieve the desire functionality, you should do as so:
The form and the input validation should be in the same page (controller). In your example, both should be in register.php.
This basic pseudo code should do the trick:
On register page controller:
If method == get:
Display register form.
If method == post:
Check the form data:
If errors exists:
display register page with error.
else:
redirect to ....
Good Luck!

I want to load a get.php file in iframe on index.html once the Submit button is pressed

Ok so I'm facing this problem here
I've got 2 files :
index.html
get.php
On index.html I've got a form :
<form method="POST" action="get.php">
<input name="x" placeholder="first value" type="text">
<input name="y" placeholder="second value" type="text">
<input value="send" type="submit">
</form>
<br>
<iframe id="frame" class="right" width="100%" height="300" src="get.php"></iframe>
and here is the get.php file
<?php
if(isset($_POST['x'])==false)
{
echo "<h3>First variable is required...</h3>";
exit;
}
if(isset($_POST['y'])==false)
{
echo "<h3>Second variable is required...</h3>";
exit;
}
echo "<a style='padding:15px;background:#eee;color:#fff;border-radius:5px;' href='index.html'>Go back to the main page</a><br><br><br>";
$x=0;
$y=0;
$x=$_POST["x"];
$y=$_POST["y"];
echo "Values entered were $x and $y respectively<br><br><br>";
echo "Sum of $x+$y= ".($x+$y)."<br><br>";
echo "Multiplication of $x*$y= ".($x*$y)."<br><br>";
echo "Division of $x/$y= ".($x/$y)."<br><br>";
echo "Power of of $x<sup>$y</sup>= ".pow($x,$y)."<br><br>";
echo "power of $y<sup>$x</sup>= ".pow($y,$x)."<br><br>";
echo "Table of $x<br><br>";
for($i=1;$i<=10;$i++){
echo "$x * $i = ".($x*$i)."<br>";
}
echo "<br><br>Table of $y<br><br>";
for($i=1;$i<=10;$i++){
echo "$y * $i = ".($y*$i)."<br>";
}
?>
Now what is needed is that I put 2 values in both fields and once I click the submitted button it should show result of the get.php in the <iframe> placed on index.html rather then loading a new page of get.php
You could set iframe content using following snippet. The data are send using ajax and you need to prevent form submit behaviour. Try e.g:
$(function() { // document ready handler
$('form[action="get.php"]').on('submit', function(e) {
e.preventDefault();
$.post(this.action, $(this).serialize(), function(data) {
var iframeDoc = $('#frame')[0].contentDocument;
iframeDoc.open();
iframeDoc.write(data);
iframeDoc.close();
})
})
});

Form check information & insert on same page

So I've got a regular form
<form action="includes/send.php" method="post" onsubmit="return isValidForm()" />>
<h1>Opgeven workshops</h1>
<label for="name">Voornaam:</label>
<input type="text" autocomplete="off" id="name" name="firstname">
<label class="choice" data-id="1"><input type="checkbox" name="group1" value="use your apple1">use your apple<span class="left" ></span>
</label>---more stuff more stuff more stuff--
Now I submit the form I want to show the information the user filled in in the form like this
$f_name = $_POST['firstname'];
$l_name = $_POST['lastname'];
U hebt zich ingeschreven bij: <br />
Eerste workshop : <?php echo $first; ?><br />
Tweede workshop : <?php echo $second; ?><br />
Klopt dit?
<button type="submit" onclick="send()">Ja</button>
<button type="submit" onclick="noSend()">nee</button>
and when the user clicks on send it sends the information from the previous form to the query to insert it into the database. I'm trying to do this without having to make another 'hidden form' which submits it again because it is unnecessary code when you can just let the script 'wait' and continue with the script / insert functionallity when the button is pressed.
I tried setting a variable $submit= false; and inside the send function (which is in javascript) set submit to true but that doesn't seem to work because it automatically sets the variable to true without pressing the button.
function send(){
<?php $submit = true ?>
var submit = <?php echo $submit ?>;
console.log(submit);
}
if($submit){
echo 'submitted';
} else {
echo 'not true';
}
On your php side pass the values when calling your Javascript 'send()' function
<?php
$first = "First course";
$second = "Second course";
?>
U hebt zich ingeschreven bij: <br />
Eerste workshop : <?php echo $first; ?><br />
Tweede workshop : <?php echo $second; ?><br />
Klopt dit?
<!-- pass the required values into the function, this is just a basic implementation you could also use a loop to fill in the values -->
<button type="button" onclick="send(true, '<?php echo $first ?>', '<?php echo $second ?>')">
Ja
</button>
<button type="button" onclick="send(false)">
nee
</button>
For the receiving function you could implement something like this
<script type="text/javascript">
function send(submit){
//Get all arguments passed except the first variable, the submit boolean
var listOfVariablesToPost = Array.prototype.slice.call(arguments,1);
if(submit){
console.log("post");
console.log(listOfVariablesToPost);
/* Do POST here either by using XMLHttpRequest or jQuery AJAX/POST (Or any other way you like)*/
/* XMLHttpRequest: http://stackoverflow.com/questions/9713058/sending-post-data-with-a-xmlhttprequest */
/* jQuery POST https://api.jquery.com/jquery.post/ */
}else{
console.log("No post")
/* Don't post and do whatever you need to do otherwise */
}
}
</script>
This is a very simple implementation, but I hope it helps.

Categories