JS not working in PHP (document.getElementById) - javascript

i'm doing a very rookie password signup thing for my web development project and i'm stuck here
<script>
<?php
if ( isset($_POST['enter']) ){
if ($_POST['password']=='0000'){
echo('document.getElementById("adminsection").style.display = "block";
document.getElementById("passsection").style.display = "none" ;');
}
else{
echo ("alert('password incorrect');");
}
}
?>
</script>
for some reason this part doesn't seem to work when the condition is met:
echo('document.getElementById("adminsection").style.display = "block";
document.getElementById("passsection").style.display = "none" ;');
adminsection and passsection are just section tags that contain the elemnts of the page and they look kinda like this
<form style="width:100%; margin:10% 0 10% 0" action="administrator123.php" method="POST">
<section id="passsection">
<input style="margin-left:-5px" id="passfield" name="password" type="password" placeholder="****">
<input type="submit" id="password" name="enter" value="enter">
</section>
<section id="adminsection">
<p>hey</p>
</section>
</form>
the goal behind this code is to hide the passsection and show the adminsection upon entering the correct password
i'd appreciate it very much if you provided me with a solution that doesn't involve jQuery

You're mixing javascript and PHP the wrong way.
Normal form submission. The order of operations are:
you have a form in html (you're missing the form element)
user submits the form
this sends the submit to the server causing a page load/reload
server-side PHP checks if the password is good
The newly loaded page does stuff with the PHP output.
<?php
if ( isset($_POST['enter']) ){
if ($_POST['password']=='0000'){
$loggedin = true;
} else {
$error="Password was incorrect";
}
}
?>
<?php if (!$loggedin) {?>
<section id="passsection">
<?php if ($error) {?>
<div class='error'>
<?php echo $error;?> </div>
<?}?>
<form method='post'>
<input style="margin-left:-5px" id="passfield" name="password" type="password" placeholder="****">
<input type="submit" id="password" name="enter" value="enter">
</form>
</section>
<?}?>
Ajax form submission. The order of operations are:
you have a form in html (you're missing the form element)
user submits the form
javascript prevents the form from reloading the page, and sends the form data through ajax to the server
server-side PHP checks if the password is good and outputs the response in json_encode() format
ajax function gets response and uses that data to provide feedback.
Your php will live in a separate file
doLogin.php
<?php
$loggedin = false;
if ( isset($_POST['enter']) ){
if ($_POST['password']=='0000'){
$loggedin = true;
} else {
$error="Password was incorrect";
}
}
$response = array('isLoggedIn' => $loggedin);
if ($error) $response['error'] = $error;
echo json_encode($response);
?>
document.querySelector('#passsection form').addEventListener('submit', function(e) {
e.preventDefault(); // stop the page from reloading
var request = new XMLHttpRequest();
let url = "/php/doLogin.php";
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json");
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
var jsonData = JSON.parse(request.response);
if (jsonData.isLoggedIn) {
document.querySelector('#passsection').style.display = "none"
} else if (jsonData.error) {
document.querySelector('#passsection form .error').innerHTML = jsonData.error
}
}
};
let data = JSON.stringify({
"passfield": document.getElementById("passfield").value
});
request.send(data);
});
<section id="passsection">
<div class='error'></div>
<form method='post'>
<input style="margin-left:-5px" id="passfield" name="password" type="password" placeholder="****">
<input type="submit" id="password" name="enter" value="enter">
</form>
</section>

Related

I want to change content of my subscription div without refreshing

I want to change the content of my subscription div,like when user is already subscribed I want to change the div color into red and to tell a message that 'you are already subscribed'.I know it can be done with ajax but I don't know anything about Ajax.
Here is the PHP inserted div
<?php
echo ';
<div id="sub">
<form method="post" action="subscription.inc.php">
<input type="text" name="email" placeholder="Enter your Email">
<button type="submit" name="submit" value="submit" `enter code here`onclick="myAjax()">Subscirbe</button>
</form>
</div>
';
?>
This is the PHP code that should be run on clicking
<?php
include 'conn.php';
include 'sub.php';
if (isset($_POST['submit'])) {
$email=mysqli_real_escape_string($conn,$_POST['email']);
$sql="INSERT INTO `subscribe` (`id`, `email`) VALUES (NULL, '$email');";
$emailcheck="SELECT * FROM `subscribe` WHERE email='ayush.antino#gmail.com'";
$doubleemail=mysqli_query($conn,$emailcheck);
$num_rows=mysqli_num_rows($doubleemail);
if ($num_rows>0) {
header("Location:sub.php?subscribe=alreadyexist");
exit();
}elseif ($num_rows==0) {
if (!filter_var($email,FILTER_VALIDATE_EMAIL)) {
echo "please enter valid email";
} else {
mysqli_query($conn,$sql);
header("Location:sub.php?subscribe=success");
exit();
}
}
}
?>
How should I refresh the message 'you are already subscribed' without refreshing the page
Try Like this..
<div id="sub">
<form method="post" action="subscription.inc.php">
<input type="text" name="email" placeholder="Enter your Email">
<button type="submit" name="submit" value="submit" `enter code here`onclick="myAjax()">Subscirbe</button>
</form>
</div>
<script>
checkSubscribe();
function checkSubscribe() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
$('#sub').css('background-color:red;')
}
};
xmlhttp.open("GET", "checkuser.php", true);
xmlhttp.send();
}
</script>

"Undefined" response when submitting contact form without page refresh

I am building a basic contact form (three fields) for my site. I have the form built in HTML and CSS; all I had to do was build the PHP to make the form responses send to my email. I found a tutorial and built the PHP file (which worked), but wanted the form to submit in the background and not leave the original page. I found an online tutorial to do that using Ajax, and after some tweaking, I got it mostly to work. The only issue I'm having now is that when I receive the email with the response, the message field is coming back as "undefined."
I have a good grasp on HTML and CSS, but PHP and JS are new to me (just started learning them for this project), so any help on how to fix this issue and possibly correct any wrong code would be a huge help. I've included the form HTML, PHP, and JS below (PHP and JS are both named 'contact.[filetype]'.
HTML
<div id="contact_form">
<form name="contact" action="">
<div class="field">
<label for="name">Name</label>
<input type="text" name="name" id="name" required/>
</div>
<div class="field">
<label for="email">Email</label>
<input type="text" name="email" id="email" required/>
</div>
<div class="field">
<label for="comments">Comments</label>
<textarea name="comments" id="comments" rows="3"></textarea>
</div>
<ul class="actions">
<li><input type="submit" name="submit" class="button" id="submit_btn" value="Send Message" /></li>
</ul>
</form>
</div>
PHP
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
$formcontent="From: $name \n Message: $comments \n";
$recipient = "alltheladsmedia#gmail.com";
$subject = "Message From Website";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!" . " -" . "<a href='index.html' target='_blank' style='text-decoration:none;color:#505050;'> Return Home</a>";
?>
JS
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
if (name === "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email === "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var message = $("input#message").val();
if (message === "") {
$("label#message_error").show();
$("input#message").focus();
return false;
}
$.ajax({
type: "POST",
url: "contact.php",
data: {name:name,email:email,message:message},
success: function() {
$('#contact_form').html("<div id='success'></div>");
$('#success').html("<h2>Your message was successfully submitted!</h2>")
.append("<p>We will get back to you within 24-48 hours.</p>")
.hide()
.fadeIn(1500, function() {
$('#success');
});
}
});
return false;
});
});
In your markup the field's id is "comments" but you are looking for "message" in your JS and PHP.
you have print your mail result
if(#mail($recipient, $subject, $formcontent, $mailheader))
{
echo "Mail Sent Successfully";
}else{
echo "Mail Not Sent";
}
Make few changes if you are using jquery 3.
Change this
$(".button").on("click", function() {
// Validation here
// Put ajax outside this block
});
Edit html form like this code.
Check the dev. tools if the action attribute is added correctly by the php.
<form id="contact" name="contact" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" >
And ajax call into this
$("#contact").on("submit", function(e) {
e.preventDefault(); // Now the page won't redirect
var url = $(this).attr("action");
// Check console if contact is printed after the form is submitted
// If contact is printed the url is right
console.log(url);
$.ajax({
type: "POST",
url: url,
data: $(this).serialiseArray(), // Found a typo here fixed
success: function() {
// Your stuffs
}
});
});
Don't put the ajax call inside the input field verification.
Let me know if you find any issue so I can fix my code.

Not able to get successful login in web page using ajax

here is the code
I am not able to get the message as successful login despite debugging in console whereas directly entering the php link with username & password in browser directly is working perfectly
The output I'm getting is " INcorrect Login information. Please Try Again".
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<script src="/_js/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function() {
$('#login').submit(function() {
var formData = $(this).serialize();
$.post('login.php',formData,processData).error('ouch');
function processData(data) {
console.log(data==='pass');
if (data==='pass') {
$('.main').html('<p>You have successfully logged in!</p>');
} else {
if ($('#fail').length === 0) {
$('#formwrapper').prepend('<p id="fail">Incorrect login information. Please try again</p>');
}
}
} // end processData
return false;
}); // end submit
}); // end ready
</script>
</head>
<body>
<div class="wrapper">
<div class="header">
<p class="logo">Demo LOGIn</p>
</div>
<div id="content">
<div class="main">
<h1>Login</h1>
<div id="formwrapper">
<form method="POST" action="../_php/login.php" id="login">
<p>
<label for="Username">Username:</label>
<input type="text" name="Username" id="Username">
</p>
<p>
<label for="Password">Password: </label>
<input type="text" name="Password" id="Password">
</p>
<p>
<input type="submit" name="button" id="button" value="Submit" >
</p>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
and here is php file
$Username = mysqli_real_escape_string($con,$_POST['Password']);
$Password = mysqli_real_escape_string($con,$_POST['Username']);
$result = mysqli_query($con,"SELECT Password from Use_Pass WHERE Username='$Username'");
$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
echo 'pass';
}
else {
echo 'fail';
}
mysqli_close($con);
?>
Updated answer:
<script>
$(document).ready(function()
{
$('#login').submit(function()
{
var formData = $(this).serialize();
$.post('login.php', $("#login").serialize(), function(response)
{
if ($.trim(response) == 'pass') {
$('.main').html('<p>You have successfully logged in!</p>');
} else {
if ($('#fail').length === 0) {
$('#formwrapper').prepend('<p id="fail">Incorrect login information. Please try again</p>');
}
}
}
);
}
); // end submit
}
); // end ready
</script>
Please use this updated code, make sure the url is passed correctly. I hope this will help.
In your PHP file, it looks like you're trying to get a username of exactly $Username. You will need to concatenate it to be getting the variable instead of that string itself.
$result = mysqli_query($con,"SELECT Password from Use_Pass WHERE Username='".$Username."');

Can I call a php file on form submit, and call or echo a JS function from that?

So I'm basically trying to create an HTML form that will
process my login through php POST method
close my login lighbox with javascript, or display an error (right now I'm using JS to change an invisible form value under the login form.
HTML
if (isset($_GET['error'])) {
echo '<p class="error">Error Logging In!</p>';
}?>
<br />
<form action="process_login.php" method="post" name="login_form">
Email: <input class="searchform" type="text" name="email" size="20"/><br />
Password: <input class="searchform" type="password"
name="password"
id="password" size="20"/><br />
<input type="button" class="searchform"
value="Submit" size="40" style="height:45px; width:90px"
onclick="formhash(this.form, this.form.password);" />
<input type="text" id="errorbox" style="height:45px; width:180px" value=""><br>
</form>
here's the php file:
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p'];
if (login($email, $password, $mysqli) == true) {
// Login success
echo "<script>document.getElementById('light').style.display=
'none';document.getElementById('fade').style.display= 'none'</script>";
} else {
// Login failed
echo "<script>document.getElementById('errorbox').value='Error'</script>";
}
} else {
// The correct POST variables were not sent to this page.
echo 'Invalid Request';
}
I know I'm not doing this right, I'm just not sure HOW to do it at all...
Well, yes, technically you can do that, but it is a VERY bad practice, and extremely not clean.
what you'd prefer to do is use Ajax, and do those JS actions in it's success callback:
Note: you will need to include the jQuery lib in your scripts.
Another none: if you don't have PHP 5.4 on your server, just remove the second callback function, and handle all the scenarios in the success callback
!(function($){
$(function() {
$('#submitBtn').on('submit', function(){
$.post('process_login.php', $('form[name="login_form"]').serialize(), function(data){
//data is a json object which contans the reponse
data = $.parseJSON(data);
$("fade").fadeOut();
$("light").fadeOut();
},
function(data){//error callback
data = $.parseJSON(data);
if(data.forbidden){
$("#errorBox").html("Error!");
}
else if(data.error){
$("#errorBox").html("Invalid request!");
}
});
});
});
})(window.jQuery);
HTML:
<form name="login_form">
<div>
<input type="text" name="email" placeholder="email">
</div>
<div>
<input type="password" name="p" placeholder="password">
</div>
<div>
<input type="button" id="submitBtn" value="Login">
</div>
</from>
PHP:
$response = array();
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p'];
if (login($email, $password, $mysqli) == true) {
http_response_code(200);//HTTP OK, requires php 5.4
$response['success'] = true;
} else {
// Login failed
$response['forbidden'] = true;
http_response_code(401);//HTTP forbidden
}
} else {
// The correct POST variables were not sent to this page.
$response['error'] = true;
http_response_code(400);//HTTP bad request
}
echo json_encode($response);
add onsubmit event attribute to the form:
<form onsubmit="return validate();">...
where validate() is a js function that closes lightbox and returns true if form is ok, or displays errors and returns false if form is bad.

Using the $.post with JQuery for two forms on the same page?

Hello I am wondering if this is possible? Having two different forms on the same page using the jquery post to send it php to do some checking. The first from works flawlessly, however when I go to the second form I get an error saying it is an undefined variable but I am using the exact same method I used for the first form. It will load anything echoed in the php page for the feed form but will not echo back what I am typing in. Is there a better, more correct way to do it?
This is not for a real site, just testing for a project I am working on.
HTML:
<form action="php/signup.php" method="post" class="form-inline" name="signupForm">
<input type="text" maxlength="20" name="username" id="user_in">
<input type="password" maxtlength="20" name="password" id="pass_in">
<input type="submit" name="submit" Value="Sign Up">
</form>
<div id="feedback"></div> <!-- Feedback for Sign Up Form -->
<br /><br />
<form name="feedForm">
<input type="text" id="feed_in" name="feed_me_in" placeholder="feed">
<div id="feedme"></div> <!-- FEEDback for feed form -->
</form>
<script src="js/jquery-1.9.1.js"></script>
JavaScript:
<script>
$(document).ready(function() {
$('#feedback').load('php/signup.php').show();
//SIGN IN FORM
$('#user_in, #pass_in').keyup(function() {
$.post('php/signup.php', { username: document.signupForm.username.value,
password: document.signupForm.password.value },
function(result) {
$('#feedback').html(result).show
});
});
$('#feedme').load('php/feed.php').show();
//FEED FORM
$('#feed_in').keyup(function() {
$.post('php/feed.php', { feed: document.feedForm.feed_me_in.value },
function(result) {
$('$feedme').html(result).show
});
});
});
</script>
PHP for Feed Form:
<?php
$feed = mysql_real_escape_string($_POST['feed']);
if(isset($feed)) {
echo $feed;
} else {}
?>
PHP for the Sign Up Form:
<?php
if(isset($_POST['username'])) {
include_once('connect.php'); //Connect
$username = mysql_real_escape_string($_POST['username']);
$sql1 = "SELECT username FROM users WHERE username='$username'";
$check = mysql_query($sql1);
$numrows = mysql_num_rows($check);
if(strlen($username)<=4) {
echo "Username is too short";
} elseif($numrows == 0) {
echo "Username is available";
} elseif($numrows > 0) {
echo "Username is already taken";
}
} else {
echo "Please type a username";
}
?>
$('$feedme').html(result).show
should be
$('#feedme').html(result).show();

Categories