Im all new to ajax and jquery so iam asking u guys for some help. I have to forms that one creates a new user and second logs the user in.
The functions work greate, but i want to create alert boxes for success or failure of the functions.
And i dont know how... Here is my code
HTML
<!-- Formular for signing up -->
<h4 class="form-headline"> Not a member? Sign up here </h4>
<form method="post">
<div class="form-group">
<label> Username </label>
<input type="text" class="form-control" id="newusername">
</div>
<div class="form-group">
<label> Password </label>
<input type="password" class="form-control" id="newpassword">
</div>
<div class="form-group">
<label> Your club </label>
<input type="text" class="form-control" id="newclub">
</div>
<input type="button" id="btn-reg" class="btn btn-success" value="Sign up!">
</form>
Script
// -----------------Registration of new user----------------------
console.log('Script loaded...');
// Calling for the method - reg
$("#btn-reg").on("click", reg);
function reg(e) {
e.preventDefault();
console.log('Klick, klick...');
// Declaring variables
var newusername=$("#newusername").val();
var newpassword=$("#newpassword").val();
var newclub=$("#newclub").val();
$.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
},
function(data){
console.log(data);
});
}
PHP
// Creating instance of the class userClass.php
var_dump($_POST);
if(isset($_POST['newusername'])){
// Defining variables
$newusername = $_POST['newusername'];
$newpassword = $_POST['newpassword'];
$newclub = $_POST['newclub'];
// Password hash
$hashpassword = sha1($newpassword);
$user = new User();
$user->newUsers($newusername, $hashpassword, $newclub);
} else {
}?>
OOP
// >>>>>>>>>>>>>>>> Function for saving new user to database
public function newUsers($newusername, $hashpassword, $newclub) {
// Using prepared statement to prevent mysql injections.
$stmt = $this->db->prepare("INSERT INTO users(username, password, club)VALUES(?, ?, ?);");
$stmt->bind_param("sss", $newusername, $hashpassword, $newclub);
if($stmt->execute()) {
echo "<h3 class='usercreated'>Created</h3>";
} else {
echo "<h3 class='usercreated'> Failed </h3>";
}
}
Just noticed that you are using function to create a new user, my bad again
if(isset($_POST['newusername'])){
// Defining variables
$newusername = $_POST['newusername'];
$newpassword = $_POST['newpassword'];
$newclub = $_POST['newclub'];
// Password hash
$hashpassword = sha1($newpassword);
$user = new User();
$status = $user->newUsers($newusername, $hashpassword, $newclub);
if($status) {
echo json_encode(array("status" : "success"));
}else {
echo json_encode(array("status" : "failed"));
}
}
Make a return from this function
public function newUsers($newusername, $hashpassword, $newclub) {
// Using prepared statement to prevent mysql injections.
$stmt = $this->db->prepare("INSERT INTO users(username, password, club)VALUES(?, ?, ?);");
$stmt->bind_param("sss", $newusername, $hashpassword, $newclub);
if($stmt->execute()) {
return true;
}else {
return false
}
}
this will be the same
$.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
},
function(data){
var object = JSON.parse(data);
alert(object.status);
// or you can add if else by using the status
});
}
You could just echo the script tag.
if($stmt->execute()) {
echo "<h3 class='usercreated'>Created</h3>";
echo "<script type="text/javascript">";
echo "alert("Hello World!")";
echo "</script>";
} else {
echo "<h3 class='usercreated'> Failed </h3>";
echo "<script type="text/javascript">";
echo "alert("Hello World!")";
echo "</script>";
}
}
For the Script block.
var posting = $.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
});
posting.done(function( data ) {
alert( "Data Loaded Ok");
});
posting.fail(function( data ) {
alert( "Error loading data");
});
Hope this helps you.
Related
I have never worked with $_COOKIES, and now I've been given the task to make it work.
I have been following a couple of tutorials online.
Found here: http://www.phpnerds.com/article/using-cookies-in-php/2
And then here:https://www.youtube.com/watch?v=Dsem42810H4
Neither of which worked for me.
Here is how my code ended up. I shortened it as much as I could.
Starting with the index.php page, which contains the initial login form:
<form role="form" action="index.php" method="post" id="loginForm" name="loginForm">
<input type="text" class="form-control" id="username" name="username"
value="<?php if(isset($_COOKIE['username'])) echo $_COOKIE['username']; ?>" />
<input type="password" class="form-control" id="password" name="password"
value="<?php if(isset($_COOKIE['password'])) echo $_COOKIE['password']; ?>"/>
<button type="button" id="loginSubmit" name="loginSubmit" class="btn btn-primary btn-block btn-flat">Sign In</button>
<input type="checkbox" id="rememberme"
<?php if(isset($_COOKIE['username'])){echo "checked='checked'";} ?> value="1" />
</form>
Here is the JavaScript used to send the form values:
$('#loginSubmit').on('click', function()
{
var username = $('#username').val();
var password = $('#password').val();
var rememberme = $('#rememberme').val();
// skipping the form validation
$.post('api/checkLogin.php', {username: username, password: password, rememberme:rememberme}, function(data)
{
// the data returned from the processing script
// determines which page the user is sent to
if(data == '0')
{
console.log('Username/Password does not match any records.');
}
if(data == 'reg-user")
{
window.location.href = "Home.php";
}
else
{
window.location.href = "adminHome.php";
}
});
});
Here is the processing script, called checkLogin.php. This is where I attempt to set the $_COOKIE:
<?php
include ("../include/sessions.php");
if(isset($_POST['username']) && isset($_POST['password']))
{
$username = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['username'])));
$password = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['password'])));
$rememberme = $_POST['rememberme'];
$select = "SELECT username, fullname, password FROM users WHERE username = '".$username."'";
$query = mysqli_query($dbc, $select);
$row = mysqli_fetch_array($query);
$dbusername = htmlentities(stripslashes($row['username']));
$dbfullname = htmlentities(stripslashes($row['fullname']));
$dbpassword = htmlentities(stripslashes($row['password']));
if(password_verify($password, $dbpassword))
{
// setting sessions here
$_SESSION['username'] = $username;
$_SESSION['fullname'] = $dbfullname;
// here is where I attempt to set the $_COOKIE
if(isset($remember))
{
setcookie('username', $_POST['username'], time()+60*60*24*365);
setcookie('password', $_POST['password'], time()+60*60*24*365);
}
else
{
setcookie('username', $_POST['username'], false);
setcookie('password', $_POST['password'], false);
}
echo $username; // this gets sent back to the JavaScript
mysqli_free_result($query);
}
else
{
// username/password does not match any records
$out = 0;
echo $out;
}
}
?>
So now that I have attempted to set the $_COOKIE, I can try to print it to the home page, like so:
<?php echo 'cookie ' . $_COOKIE["username"]; ?>
To which does not work, because all I see is the word 'cookie'.
Besides that, when I log out, I am hoping to see the login form already filled out, which is the overall task I have been trying to complete, but have been unsuccessful at doing so.
I am trying to create a page that will delete a user from my database when it is searched, ask for confirmation, and then delete it, i am extremely close but i need to pass the function through ajax to java script but im not understanding how to do that. Here is my code:
<html>
<head>
<?php
require_once('conn.php');
function deleteEmployee($conn, $employee, $table){
$query = "DELETE from $table where EmployeeName = '$employee'";
$confirmed = mysqli_query($conn, $query);
if ($confirmed){
echo "User Deleted";
}
else{
return True;
echo 'User has been deleted';
}
return;
}
//$query1 = 'select *
?>
<script>
function myFunction() {
var txt;
return confirm('Are you sure?');
if (confirm == true) {
deleteEmployee($conn, $name, "employee");//This is where i am having trouble
} else {
txt = "Okay";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</head>
<body>
<p id="demo"></p>
<form action="" method="post">
Search Name to be Deleted: <input type="text" name="term" /><br />
<button onclick="myFunction()" type="submit" value="Submit" />submit</button>
</form>
<?php
if (!empty($_POST['term'])) {
$term = mysqli_real_escape_string($conn,$_POST['term']);
$sql = "SELECT EmployeeName FROM employee ";
$r_query = mysqli_query($conn,$sql);
if($r_query->num_rows == 0){
echo "Name not in database";
} else{
while ($row = mysqli_fetch_array($r_query)){
$name = $row['EmployeeName'];
}
}
}
?>
</form>
As of right now, the window pops up but when i press ok, nothing happens since i do not understand how to pass a function through ajax to javascript. Can someone help? If you need more info, let me know
How about using jQuery AJAX, storing your php functions in different files and just past post/get data so your PHP methods can process what you want to process?
Example Usage:
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
I am currently working on a PHP based web-interface, with a login system.
But for some reason when I hit login, it seems to get to the login.php and return a response back.
But the thing is, the response is not what I need to have, and furthermore logging in is still not happening.
The HTML based login form (Within a modal):
<form class="form" method="post" action="<?php echo Utils::resolveInternalUrl('backend/Login.php') ?>" id="loginForm">
<div class="form-group">
<label for="loginUsername">Username:</label> <input type="text" class="form-control" name="loginUsername" id="loginUsername" />
</div>
<div class="form-group">
<label for="loginPassword">Password:</label> <input type="password" class="form-control" name="loginPassword" id="loginPassword"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Login</button>
</div>
</form>
Javascript/jQuery related to login:
var form = $('#loginForm');
form.submit(function (e) {
e.preventDefault();
$.ajax({
'data': form.serialize(),
'type': $(this).attr('method'),
'url': $(this).attr('action'),
'dataType': 'JSON',
success: function (data) {
alert("Success: " + data)
},
error: function (error) {
alert("Error: " + error)
}
})
})
PHP backend, related to login:
if($_SERVER['REQUEST_METHOD'] == "POST") {
$database = Database::getDefaultInstance();
if(isset($_POST['loginUsername']) && isset($_POST['loginPassword'])) {
$connection = $database->getConnection();
$username = $_POST['loginUsername'];
$password = $_POST['loginPassword'];
echo $username . ":" . $password;
$stmt = $connection->query("SELECT * FROM banmanagement.users;");
if($stmt->fetch()) {
session_start();
$_SESSION['username'] = $username;
$_SESSION['sessionId'] = Utils::randomNumber(32);
echo json_encode("Successfully logged in as ${username}.");
exit;
} else {
echo json_encode("No user exists with the name \"${username}\".");
exit;
}
} else {
echo json_encode("Username and/or password is not provided.");
exit;
}
} else {
echo json_encode("Submit method is not POST.");
exit;
}
The result of it:
Click here for screenshot
Edit:
Changed SQL query to: SELECT COUNT(*) FROM banmanagement.users WHERE username=:username;
Edit 2:
Per suggestion, I have used var_dump the output var_dump($_POST) is: array(0) { }.
$stmt = $connection->query("SELECT * FROM banmanagement.users;");
I'm assuming you're using PDO on the backend. If so, you don't need the semicolon in your query. That's why your fetch is failing.
$stmt = $connection->query("SELECT * FROM banmanagement.users");
Ok, so that wasn't it. I was reading the wrong braces. Have you tried var_dump($_POST) to see what, if anything, is being sent?
I have created a form which includes the following field and below it I have created a div with the id email_feedback to display the message.
label>Email</label>
<div class="input-group">
<input name="email" id="email_id" type="email" class="form-control" placeholder="Email" required>
<span class="input-group-addon"><i class="fa fa-envelope-o fa-fw"></i></span>
<div id="email_feedback"></div>
</div>
and I have created the following jquery function in a separate file in js.
$(function() {
$("#register_submit").click(function() {
$.post("<?php echo base_url(); ?>user/login_register/about",
{ email : $("#email_id").val() }, function(data) {
$("#email_feedback").html(data);
console.log(data.length);
});
});
});
and I have written the following function in the controller.
function about() {
$email = $this->input->post('email');
$email_verify = $this->userdata_insertion->read_user_information($email);
if($email_verify == "true"){
echo "The user already exists";
}
}
and this function in the model.
public function read_user_information($email) {
$condition = "email =" . "'" . $email . "'";
$this->db->select('*');
$this->db->from('vtiger_users_details');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
but whenever I try to use the email id that I have used before it is not showing the error message can anyone let me know where I am committing the mistake.
try :
Controller:
if($email_verify){
echo "The user already exists";
}
Model:
public function read_user_information($email) {
$this->db->select('*');
$this->db->from('vtiger_users_details');
$this->db->where('email',$email);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
There was an issue with the base URL whenever I use to pass the base_url in the jquery as follows.
<?php echo base_url(); ?>user/login_register/about
it uses to consider the path of the controller where the function is been written and then concatenate the base URL to that resulting in the wrong URL. I have removed the echo "base_url()" and it is working fine now.
I have a login script that should return 'success' or 'failure' respectively, but it adds many spaces before the result, in the console it shows tha value as "<tons of space> success". This is the PHP for the login script:
public function login() {
global $dbc, $layout;
if(!isset($_SESSION['uid'])){
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($dbc, trim($_POST['email']));
$password = mysqli_real_escape_string($dbc, trim($_POST['password']));
if(!empty($username) && !empty($password)){
$query = "SELECT uid, email, username, password, hash FROM users WHERE email = '$username' AND password = SHA('$password') AND activated = '1'";
$data = mysqli_query($dbc, $query);
if((mysqli_num_rows($data) === 1)){
$row = mysqli_fetch_array($data);
$_SESSION['uid'] = $row['uid'];
$_SESSION['username'] = $row['username'];
$_SERVER['REMOTE_ADDR'] = isset($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];
$ip = $_SERVER['REMOTE_ADDR'];
$user = $row['uid'];
$query = "UPDATE users SET ip = '$ip' WHERE uid = '$user' ";
mysqli_query($dbc, $query);
setcookie("ID", $row['uid'], time()+3600*24);
setcookie("IP", $ip, time()+3600*24);
setcookie("HASH", $row['hash'], time()+3600*24);
echo 'success';
exit();
} else {
//$error = '<div class="shadowbar">It seems we have run into a problem... Either your username or password are incorrect or you haven\'t activated your account yet.</div>' ;
//return $error;
$err = 'failure';
echo($err);
exit();
}
} else {
//$error = '<div class="shadowbar">You must enter both your username AND password.</div>';
//return $error;
$err = "{\"result\":\"failure\"}";
echo json_encode($err);
exit();
}
}
} else {
echo '{"result":"success"}';
exit();
}
return $error;
}
and the form and JS
<div class="shadowbar"><form id="login" method="post" action="/doLogin">
<div id="alert"></div>
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<span class="input-group-addon">E-Mail</span>
<input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
<span class="input-group-addon">Password</span>
<input type="password" class="form-control" name="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form></div>
$(function login() {
$("#login").validate({ // initialize the plugin
// any other options,
onkeyup: false,
rules: {
email: {
required: true,
email: true
},
password: {
required: true
}
}
});
$('form').ajaxForm({
beforeSend: function() {
return $("#login").valid();
},
success : function(result) {
console.log(result);
if(result == " success"){
window.location = "/index.php";
}else if(result == " failure"){
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
}
});
});
but the result always has a lot of spaces for some reason. I'm new to JS, so if this is common, I don't already know.
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
define("CCore", true);
session_start();
//Load files...
require_once('include/scripts/settings.php');
require_once('include/scripts/version.php');
require('include/scripts/core.class.php');
require('include/scripts/nbbc_main.php');
$parser = new BBCode;
$core = new core;
$admin = new admin;
require_once('include/scripts/layout.php');
require_once('include/scripts/page.php');
//Set Variables...
global $dbc, $parser, $layout, $main, $settings, $core;
$page = new pageGeneration;
$page->Generate();
?>
this is my index, and anything before the page is generated and login() is called, is in there.
I suppose you are using Ajax calls. I had the same problem, but it my case the result hadn't contain spaces, it was returned in new line. The problem was that my script which was requested by Ajax, contained "new line" character before the PHP script. Search your script file for spaces before PHP script starting with <?php //code... If you had included some scripts in the script which returns success note, search them as well.
I dont know if it matters but your
if(result == " success"){ // <<<<<< Here is a Problem maybe
window.location = "/index.php";
}else if(result == " failure"){ // <<<<<< Here is a Problem maybe
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
compares your result from the server which is i.e. "success" with " success". There is space too much.
EDIT:: I dont get ether why you jumps between the response format. Sometimes you echo "success" which is plain and good with your if condition but sometimes you return json encodes strings.
These Responses you can't just compare with plain text. These Responses you have to Parse into a JSON Object. Then you could compare with:
if (parsedJSONobject.result == "success"){}
The comments on the question are most probably correct: the spaces are being (again, probably, nobody can know for sure without reading the whole source) echoed by PHP included before this. For example, if you do:
<?php
// there's a space before the previous line
you'd get that space in the output.
What you can do is a bit of a hack, you include a header, for example:
header('Content-Type: text/html');
just before your success output, this will (yet again, probably) output something like:
Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23
(note the "output started" part) and now you know where to start looking.
HTH.