I'm making a login system to my website, but the browser says it is not secured: the browser's message
Heres is my html:
<div id="loginform">
Bejelentkezés
<input type="text" placeholder="E-mail" id="email"></input>
<input type="password" placeholder="Jelszó" id="password"></input>
<button id="loginbutton">Bejelentkezés</button>
<div id="errormsg"></div>
</div>
Here is my Ajax:
$("#loginbutton").click(function(){
var user ={
email: $('#email').val(),
password: $('#password').val()
};
$.ajax({
url: 'login.php',
type: 'POST',
dataType: "json",
data: {"user": JSON.stringify(user)},
success: function(data){
if(data.success){
alert(data.user_id);
}
else{
document.getElementById("errormsg").innerHTML = "A bejelentkezés sikertelen";
}
}
});
});
And my PHP:
<?php
session_start();
$conn = mysqli_connect("localhost", "root", "", "getpet");
$results = array(
'success' => false,
'user_id' => "azaz",
'fname' => "",
'lname' => ""
);
if(isset($_POST['user'])){
$user = json_decode($_POST['user']);
$email = $user->email;
$password = md5($user->password);
$sql= "SELECT * FROM users WHERE email = '".$email."' AND password = '".$password."'";
$rowsql = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($rowsql, MYSQLI_BOTH);
if(mysqli_num_rows($rowsql) == "1"){
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['fname'] = $row['fname'];
$_SESSION['lname'] = $row['lname'];
$results['success'] = true;
$results['user_id'] = $row['user_id'];
$results['fname'] = $row['fname'];
$results['lname'] = $row['lname'];
}
}
else{
$results['user_id']= "VAnbaj";
}
echo json_encode($results);
?>
It works, but i don't know how to make it safe.
I'd be glad if somebody can help me.
I you want to get rid of that warning message, you have to serve your site over https with a valid certificate.
Related
I am creating a booking system for a university project and I am trying to add an author to the table 'authors' for some reason when I add a field it returns as NULL in my database and undefined on my html page? Can anyone help me with this I have shown my HTML, Javascript and php code below.
Can anyone help me with this and guide me in the right direction. I have a feeling it is something to do with my names eg. authors or author
Thanks in advance.
HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="w3.js"></script>
<script src="https://scm.ulster.ac.uk/zhiwei.lin/js/jquery.tmpl.min.js"></script>
</head>
<body>
<div id="authors">
<ul id="authors_list"></ul>
</div>
<div class="mainArea">
<label>Author:</label>
<input type="text" id="author" name="name" required>
<button id="btnSave">Save</button>
<button id="btnUpdate">Update</button>
</div>
<p>Click Here to Delete Last Author
<button id="btnDelete">Delete</button></p>
</body>
</html>
Js
$(document).ready(function(){
$.ajax({
type: 'GET',
dataType: "json",
url: "api.php/authors",
success: showAllAuthors,
error: showError
});
});
function showAllAuthors(responseData) {
$.each(responseData.authors,function(index,authors){
$("#authors_list").append("<li type='square'> author:"+authors.author+"");
$("#authors_list").append("</li>");
});
}
function showError(){
alert("Sorry, there was a problem!");
}
$(document).ready(function(){
$("#btnSave").click(function(){
$.ajax({
type: 'POST',
dataType: "json",
url: "api.php/authors",
data:{author: $("#author").val()},
data:JSON.stringify(authors),
success: showResponse,
error: showError
});
});
});
function authors(Author){
this.author=Author;
}
function showResponse(responseData) {
console.log(responseData);
}
function showError() {
alert("Sorry, there was a problem!");
}
$(document).ready(function(){
$.ajax({
type: 'GET',
dataType: "json",
url: "api.php/authors/12",
success: showResponse,
error: showError
});
});
$(document).ready(function(){
$("#btnUpdate").click(function(){
$.ajax({
type: 'PUT',
dataType: "json",
url: "api.php/authors/12",
data:{author: $("#author").val()},
data:JSON.stringify(authors),
success: alert("Updated!")
});
});
});
$(document).ready(function(){
$("#btnDelete").click(function(){
$.ajax({
type: 'DELETE',
dataType: "json",
url: "api.php/authors/13",
data:{author: $("#author").val()},
data:JSON.stringify(authors),
success: alert("Deleted!")
});
});
});
PHP
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
use Slim\Slim;
$app=new Slim();
$app->get('/authors','getAuthors');
$app->post('/authors','addAuthor');
$app->get('/authors/:id','getAuthor');
$app->put('/authors/:id','updateAuthor');
$app->delete('/authors/:id', 'deleteAuthor');
$app->run();
function deleteAuthor($id) {
$sql = "DELETE FROM authors WHERE id=:id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$db = null;
responseJson("Deleted",200);
}catch(PDOException $e) {
responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
}
}
function updateAuthor($id) {
$request = Slim::getInstance()->request();
$body = $request->getBody();
$authors = json_decode($body);
$sql = "UPDATE authors SET author=:author WHERE id=:id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("author", $authors->author);
$stmt->bindParam("id", $id);
$stmt->execute();
$db = null;
responseJson("Updated",200);
} catch(PDOException $e) {
responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
}
}
function getAuthor($id) {
$sql = "SELECT * FROM authors WHERE id=:id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$authors = $stmt->fetchObject();
$db = null;
responseJson(json_encode($authors),200);
} catch(PDOException $e) {
responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
}
}
function getAuthors(){
$sql = "select * FROM authors ORDER BY id";
try {
$db = getConnection();
$stmt = $db->query($sql);
$authors = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
responseJson('{"authors":'.json_encode($authors).'}',200);
}catch(PDOException $e){
responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
}
}
function addAuthor(){
$request = Slim::getInstance()->request();
$authors=json_decode($request->getBody());
$sql= "INSERT INTO authors (author)
VALUES (:author)";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("author", $authors->author);
$stmt->execute();
$authors->id=$db->lastInsertId();
$db = null;
responseJson(json_encode($authors),201);
}catch(PDOException $e) {
responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
}
}
function getConnection(){
$dbhost="localhost";
$dbuser="B00657229";
$dbpass="9wz7Fr9J";
$dbname="B00657229";
$dbh= new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser,$dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $dbh;
}
function responseJson($responseBody,$statusCode){
$app = Slim::getInstance();
$response = $app->response();
$response['Content-Type']='application/json';
$response->status($statusCode);
$response->body($responseBody);
}
?>
There seems to be a mistake in your js code:
$(document).ready(function(){
$("#btnSave").click(function(){
$.ajax({
type: 'POST',
dataType: "json",
url: "api.php/authors",
data:{author: $("#author").val()},
data:JSON.stringify(authors),
success: showResponse,
error: showError
});
});
you set data two times, one time with
{author: $("#author").val()} and other time with JSON.stringify(authors) i don't think you need the second one, but I did not test this.
I send a jQuery request (incorporating a business_id) to a php file to retrieve all values in the database to populate the fields and selects that are in my form and correspond to this id. However, how am I able to retrieve the response from the database in pieces? So that I can provide the fields and selects that are in the form with the values from the database. My javascript function looks as follows:
businessselect: function(){
$('#busselect').change(function() {
opt = $(this).val();
if (opt=="new_bus") {
location.reload();
}
else
{
businessid = $(this).children(":selected").attr("id");
$.ajax({
url : "businessdata.php",
method : "post",
data : "business_id="+businessid,
success: function(response) {
$("#uitgevoerd_door_naam").val(response);
}
});
}
});
},
My businessdata.php looks as follows:
<?php
$mysqli = new mysqli("localhost", "root", "", "brandveiligheid");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($_POST)
{
$result = $mysqli->query("SELECT * from form WHERE ID ='$_POST[business_id]'");
while ($row = $result->fetch_assoc()) {
echo $row['uitgevoerd_door_naam'];
echo $row['hoev_gev_stof_score'];
}
}
mysqli_close($mysqli);
?>
What I want to achieve is:
$("#uitgevoerd_door_naam").val() == $row['uitgevoerd_door_naam'];
$("#hoev_gev_stof_score").val() == $row['hoev_gev_stof_score'];
etc.....
Fix:
Use json encode:
function:
businessselect: function(){
$('#busselect').change(function() {
opt = $(this).val();
if (opt=="new_bus") {
location.reload();
}
else
{
businessid = $(this).children(":selected").attr("id");
$.ajax({
url : "businessdata.php",
method : "post",
dataType: "json",
data : "business_id="+businessid,
success: function(response) {
$("#uitgevoerd_door_naam").val(response.a);
$("#riskpot_scorefield3").val(response.b);
}
});
}
});
},
php file:
<?php
$mysqli = new mysqli("localhost", "root", "", "brandveiligheid");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($_POST)
{
$result = $mysqli->query("SELECT * from form WHERE ID = '$_POST[business_id]'");
while ($row = $result->fetch_assoc()) {
echo json_encode(array("a" => $row['uitgevoerd_door_naam'], "b" => $row['hoev_gev_stof_score']));
}
}
mysqli_close($mysqli);
?>
Javascript
<script>
loginValidator = $('#login').validate({
errorClass: 'error1',
focusInvalid: false,
errorElement: "div",
rules: {
username: {
required: true,
email: true
},
password: "required"
},
messages: {
username: {
email: "Please Enter a Valid E-mail Id"
},
password: {
required: "Please Enter Your Password"
}
},
submitHandler: function (form) {
var email = $('#username').val();
var password = $('#password').val();
var url = "<pre> ?php echo site_url() ?></pre> /register/do_login";
$.ajax({
type: 'post',
url: url,
data: {'username': email, 'password': password},
dataType: 'html',
success: function (data) {
if (data == 0) {
$('.invalidlogin').html('Invalid Username or Password').css('color', 'red');
}
if (data == 1)
{
window.location.href = "<?php echo site_url(); ?>/home/landing_home";
return false;
}
if (data == 2)
{
window.location.href = "<?php echo site_url(); ?>/home/first_login_disclaimer";
}
}
});
}
});
</script>
Register.php-Controller
<?php
function do_login() {
echo $result = $this->obj_users->check_login();
exit;
}
?>
Registration.php-Model
<?php
function check_login() {
$username = $this->input->post('username');
$password = $this->input->post('password');
$last_logged = date('Y-m-d H:i:s');
$salt = sha1($password);
$password = md5($salt . $password);
$this->db->where(array('email' => $username, 'password' => $password, 'status' => '1'));
$query = $this->db->get('registration');
$result = $query->result();
if (count($result) > 0) {
$first_login_status = $result[0]->first_login;
if ($first_login_status == '1') {
$datas = array('last_logged' => $last_logged);
$this->db->where(array('email' => $username));
$this->db->update('registration', $datas);
$this->session->set_userdata('user_id', $result[0]->id);
$this->session->set_userdata('user_type', $result[0]->user_type);
$this->session->set_userdata('ADMIN_NAME', $result[0]->name);
return "1";
} else {
$this->db->where(array('email' => $username, 'password' => $password, 'first_login' => '0', 'status' => '1'));
$query = $this->db->get('registration');
$result = $query->result();
$this->session->set_userdata('first_login_user_id', $result[0]->id);
$this->session->set_userdata('first_login_user_type', $result[0]->user_type);
$this->session->set_userdata('FIRST_LOGIN_ADMIN_NAME', $result[0]->name);
if (count($result) > 0) {
return "2";
}
}
} else {
return "0";
}
}
?>
Here, the ajax request is taking more than 5 seconds to respond to the request and redirect to next page.. Please suggest me if there is any way to reduce Ajax response time. Thank you.
I applied some jquery on my paragraph fields and converted them in input fields.It works!! But when i post them to next page i.e address_update.php after giving some values through ajax it does not update the values in database. Any suggestions please.
html
<form method="post" action="">
<?php
$em=$_SESSION['login_email'];
$query = mysqli_query($con,"SELECT * FROM customers where email='$em'" );
while($row=mysqli_fetch_assoc($query)){
?>
<h5>Name:</h5><p id="name"><?= $row['name'] ?></p>
<h5>Email:</h5><p id="email"><?= $row['email'] ?></p>
<h5>Telephone:</h5><p id="phone"><?= $row['phone'] ?></p>
<h5>Address:</h5><p id="address"><?= $row['address'] ?></p>
<h5>City:</h5><p id="city"><?= $row['city'] ?></p>
<?php
}
?>
<input type="button" id="up" value="Update" >
<input type="submit" id="update" value="Update Address" >
</form>
Ajax
<script >
$(document).ready(function() {
$('#update').click(function(){
var name = $("#name").val(),
address = $("#address").val(),
phone = $("#phone").val(),
city = $("#city").val();
$.ajax({
url: "address_update.php",
type: "POST",
async: true,
data: { Name: name, Address: address, Phone: phone, City:city},
dataType: "json",
success: function(data) {
if(data)
{
$("#error").html("Done. ");
// $("body").load("index.php?page=form");//.hide();//.fadeIn(1500).delay(6000);
}
else
{
$("#error").html("<span style='color:#cc0000'>Error:</span> Cant update. ");
}
}
});
});
});
</script>
Js
<script>
$('#up').click(function() {
var $name = $('#name');
var $phone=$('#phone');
var $address = $('#address');
var $city=$('#city');
var $input_name = $("<input>", {value: $name.text(),type: "text", id:"name"});
var $input_phone = $("<input>", {value: $phone.text(),type: "text", id:"phone"});
var $input_address = $("<input>", {value: $address.text(),type: "text" ,id:"address"});
var $input_city = $("<input>", {value: $city.text(),type: "text",id:"city"});
$name.replaceWith($input_name);
$phone.replaceWith($input_phone);
$address.replaceWith($input_address);
$city.replaceWith($input_city);
document.getElementById("update").style.display="block";
document.getElementById("up").style.display="none";
$input_name.select();
$input_address.select();
$input_phone.select();
$input_city.select();
});
</script>
address_update.php
if(isset($_SESSION["login_email"]) || isset( $_SESSION["login_user"]))
{
$name=$_POST['Name'];
$address=$_POST['Address'];
$phone=$_POST['Phone'];
$city=$_POST['City'];
$email=$_SESSION['login_email'];
$sql=mysqli_query($con,"Update `customers` set `name`='".$name."',`address`='".$address."',`phone`='".$phone."',`city`='".$city."' where `email`='".$email."'");
if($sql)
{
echo "updated";
}
else{
echo "no";
}
}
You can not put the jquery selectors in the json array, but anyway supposig you have an "#add" element:
$(document).ready(function() {
$('#add').click(function()
{
var name = $("#name").val(),
address = $("#address").val(),
phone = $("#phone").val(),
city = $("#city").val(),
$.ajax({
url: "address_update.php",
type: "POST",
async: true,
data: { Name: name, Address: address, Phone: phone, City:city},
dataType: "json",
success: function(data) {
if(data)
{
$("#error").html("Done. ");
// $("body").load("index.php?page=form");//.hide();//.fadeIn(1500).delay(6000);
}
else
{
$("#error").html("<span style='color:#cc0000'>Error:</span> Cant update. ");
}
}
});
});
});
I have crated a sample web service to store and retrieve data. The PHP web service has 2 scripts called getData.php and saveData.php, getData returns a json response and saveData saves the json object to database.
getData.php
<?php
require_once ('../database.php');
mysqli_select_db($conn, $database);
$query = "SELECT * FROM user ORDER BY id ASC";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
$rows = array();
while($packages = mysqli_fetch_assoc($result)) {
array_push($rows, $packages);
}
header('Content-type: application/json');
echo json_encode($rows);
?>
saveData.php
<?php
require_once ('../database.php');
mysqli_select_db($conn, $database);
if (isset($_POST['json'])) {
$jsonObj = $_POST['json'];
$jsonObj = json_decode($jsonObj);
$query = "INSERT INTO user (first_name, last_name, description)"
. " VALUES ('".$jsonObj->{'first_name'}."', '".$jsonObj->{'last_name'}."', '".$jsonObj->{'description'}."')";
mysqli_query($conn, $query);
header('Content-type: application/json');
echo json_encode($_POST['json']);
}
?>
this is inside my wamp/www folder in a folder called testService. Then i have another folder called testConsume where it has the html page with a simple form that sends the data to the testService/saveData.php file.
HTML
<form role="form">
<div class="form-group">
<input name="first_name" id="txtFirstName" class="form-control" placeholder="First Name" type="text" />
</div>
<div class="form-group">
<input name="last_name" id="txtLastName" class="form-control" placeholder="Last Name" type="text" />
</div>
<div class="form-group">
<input name="description" id="txtDescription" class="form-control" placeholder="Description" type="text" />
</div>
<a id="submit" class="btn btn-success" onclick="sendData()">Submit</a>
</form>
in the script the sendData() function takes the data and send it as a json object
function sendData() {
var firstName = $('#txtFirstName').val();
var lastName = $('#txtLastName').val();
var description = $('#txtDescription').val();
var jqxhr = $.ajax({
url: 'http://localhost:8080/testService/json/saveData.php',
type: 'POST',
contentType: 'application/json',
data: { json: JSON.stringify({
first_name: firstName,
last_name: lastName,
description: description
})},
dataType: 'json'
});
jqxhr.done(function() {
alert("Success! " + firstName + " " + lastName + " is a " + description);
});
jqxhr.fail(function() {
alert("Failed");
});
}
When i run the testConsume/index.html and click on submit, the alert message Failed shows. And when i check the database there is no data added. What am i doing wrong?
Remove contentType: 'application/json'.
You are sending JSON embedded in application/x-www-form-urlencoded data, not plain JSON.
Alternatively. Send and parse actual plain JSON:
contentType: 'application/json',
data: JSON.stringify({
first_name: firstName,
last_name: lastName,
description: description
}),
And in your PHP:
if (stripos($_SERVER["HTTP_CONTENT_TYPE"], "application/json")===0) {
$jsonObj = json_decode(file_get_contents("php://input"));
}