All I want to do is print 'win!' if they log in with their details in the Database (working correctly) and 'loss' if for some reason their info was not found in the DB.
So my issue is that for some reason my line of code 'echo $email;' doesn't work. It seems be set to NULL.
At the moment it only ever prints 'loss' regardless what i enter, but, if I add a row in the database that has a blank email and password (email = "", password="") then the php script returns 'win!'.
PHP CODE:
<?php
// echo "php test";
//server info
$servername = "localhost";
$username = "root";
$dbpassword = "root";
$dbname = "personal_data";
//Establish server connection
$conn = new mysqli($servername, $username, $dbpassword, $dbname);
//Check connection for failure
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//Read in email & password
echo "reading in email & password...";
$email = mysqli_real_escape_string($conn, $_POST['email1']);
$password = mysqli_real_escape_string($conn, $_POST['password1']);
echo $email; //this prints blank
echo $password; //this also prints blank
$sql = "SELECT Name FROM personal_data WHERE Email='$email' AND Password='$password' LIMIT 1";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
echo "win!!";
} else {
echo "loss";
}
mysqli_close($conn);
?>
JS CODE:
$(document).ready(function(){
// alert("js working");
$('#login_button').click(function(){
var email = $('#email').val(); //prints the correct value
var password = $('#password').val(); //prints the correct value
var dataString = 'email1=' + email
+ '&password1=' + password;
$.ajax({
type: "POST",
url: "http://localhost:8888/php/login.php",
data: dataString, //posts to PHP script
success: success()
});
});//eo login_button
function success(){
alert("success");
}
});//eof
Apart from the fact that that is completely, insanely useless and with no security whatsoever, you can just exchange $.ajax() for $.post() and do like this:
var loginEmail = $('#email').val();
var loginPassword = $('#password').val();
$.post('login.php',{email:loginEmail,password1:loginPassword},function(data) {
console.log(data);
})
Related
I want to display the array data that I have called in getword.php into the text field in index.php using AJAX. but how ?
this is the index.php
<body>
<div class="container" >
<h2>View data</h2>
<h4>Word List : </h4>
<div class="form-group">
<input id="wordlist" type="text" class="form-control" name="wordlist">
</div><br>
<button id="display" title="Generate Word">Generate</button>
<div class="input-single">
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({
type: "POST",
url: "getword.php",
dataType: "json",
success: function($result){
$('#wordlist').val('');
}
});
});
})
</script>
and this is the sql query to get data from database into array (getword.php)
<?php
$host = "localhost";
$user = "root";
$password = "";
$dbname = "wordlist";
$con = mysqli_connect($host, $user, $password, $dbname);
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "select kata from word";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
$result[]= $row[0];
}
echo json_encode(array('kata'=>$result));
mysqli_close($con);
?>
I would suggest you write PHP code as below it will be lot more simple
<?php
$host = "localhost";
$user = "root";
$password = "";
$dbname = "wordlist";
$con = mysqli_connect($host, $user, $password, $dbname);
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT kata FROM word";
$res = $con->query($sql);
while($row = mysqli_fetch_array($res)){
$dataToSend = $row[0];
}
mysqli_close($con);
echo json_encode($dataToSend);
?>
Now the script be like this to place the result in the text box
$.ajax({
type: "POST",
url: "getword.php",
dataType: "json",
success: function($result) {
var val = JSON.parse($result);
console.log(val); // see console in browser to check what is sent back
var txtBox = docuent.getElementById('wordlist');
txtBox.value = val;
}
});
Here I guess the data from the PHP file will be a single value since you are using a single text box. if multiple values are there then use an array to store data in PHP and send it in json_encode() itself.
hope that this becomes helpful to you.
I'm doing a login with ajax, html and php.
I've already debbuged the php, it's ok and it's returning the json variable I need in the ajax call.
I have this ajax function:
$(document).ready(function(){
$('#login').submit(function() {
var username=$("#username").val();
var password=$("#password").val();
$.ajax({
url: 'login.php',
data: {
username: username,
password: password
},
type: 'post',
dataType: 'json',
success:function(response){
alert(response);
if(response.validacion == "ok"){
alert("Bienvenidos"),
localStorage.loginstatus = "true",
window.location.assign("home.php");
}
if(response.validacion == "error"){
window.location.assign("login.html"),
alert("Datos de usuario incorrectos, inténtelo nuevamente");
}
}
});
});
});
This is the login.php code: (I know it's really bad save password in cookies, but this is my solution for now)
<?php
session_start();
?>
<?php
include 'conexion.php';
if(isset($_POST['username'] && $_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
}
$sql = "SELECT * FROM User WHERE username = '$username' OR Email ='$username'";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_array(MYSQLI_ASSOC);
$hash = $row['password'];
if (password_verify($password, $hash)) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['start'] = time();
setcookie("COOKIE_INDEFINED_SESSION", TRUE, time()+31622400);
setcookie("COOKIE_DATA_INDEFINED_SESSION[username]", $username, time()+31622400);
setcookie("COOKIE_DATA_INDEFINED_SESSION[password]", $password, time()+31622400);
echo "Sesión abierta indefinidamente.<br/>";
$respuesta["validacion"] = "ok";
$respuesta["id"] = $row["idUser"];
$respuesta["username"] = $row["username"];
}else{
$respuesta["validacion"] = "error";
$respuesta["mensaje"] = "Contraseña incorrecta";
}mysqli_close($connection);
}else{
$respuesta["validacion"] = "error";
$respuesta["mensaje"] = "Usuario incorrecto";
}mysqli_close($connection);
// encoding array to json format
echo json_encode($respuesta);
?>
I did and inspect element, the username and password are ok, login.php is called, but when I continue the inspection from the line 20, this works until the line 25 aprox and skips to the line 44, the success:function(function) is skipped and the "response" variable is undefined but the login.php is returnint this variable ok:
What am I doing wrong? (sorry for my english, I'm spanish speaker)
Ok, I've solved the problem so I'm going to post what I've done for those who have the same problem:
the function success:function(response) is taking ALL the "echo" from the login.php, so the first "echo" when the login is ok, is the trouble and response become an undefined var.
When I post with the wrong credentials, I only have one echo (the json_encode) and I had not problem with the ajax. So the solution will be this, in the php, after the if(password_verify):
if (password_verify($password, $hash)) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['start'] = time();
setcookie("COOKIE_INDEFINED_SESSION", TRUE, time()+31622400);
setcookie("COOKIE_DATA_INDEFINED_SESSION[username]", $username, time()+31622400);
setcookie("COOKIE_DATA_INDEFINED_SESSION[password]", $password, time()+31622400);
$respuesta["validacion"] = "ok";
$respuesta["id"] = $row["idUser"];
$respuesta["username"] = $row["username"];
}else{
$respuesta["validacion"] = "error";
$respuesta["mensaje"] = "Contraseña incorrecta";
}
}else{
$respuesta["validacion"] = "error";
$respuesta["mensaje"] = "Usuario incorrecto";
}
mysqli_close($connection);
// encoding array to json format
echo json_encode($respuesta);
?>
In order to get the value from the response, you need to JSON.parse() it first to allow your self to use response.validacion
I stuck in the following process:
Here is the well known "Facebook Login for the Web with the JavaScript SDK example":
https://developers.facebook.com/docs/facebook-login/web
I want to get the Facebook USERID as a simple string to pass it to a PHP variable. Altough the USERID is shown when I print the $fbID, but it's not a string.
How can I get the USERID as a simple string (or a number)...?
Here is my code:
<?php
$fbID = "<script>
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML = response.id;
});
}
</script>";
?>
</script>
<div id="status">
</div>
<?php
echo $fbID;
$sql = "select id from customer where fbid = '$fbID' and status = '1'";
$table = mysqli_query($conn,$sql);
list($realid) = mysqli_fetch_array($table,MYSQLI_BOTH);
echo $realid;
?>
Thank you in advance for your answers!
Use ajax to persist the ID in your database. Add the following code to your FB.api('/me', function(response) { } function:
$.ajax({
url: 'persistID.php',
type: "POST",
dataType:'json',
data: ({id: response.id}),
success: function(data){
console.log(data);
}
});
And create a seperate persistID.php file where you persist the FacebookID:
<?php
$ID = $_POST['id'];
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO customer (fbid) VALUES ($ID)";
// Persist userid
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
how can I save all my datatable data to my database?, im using jquery and php to do this dynamic.
$('#bot_guar').click( function () {
//var rows = $("#tabla1").dataTable().fnGetNodes();
var oTable = $('#tabla1').DataTable();
var data1 = oTable.rows().data();
//alert(data1.length);
$.ajax({
type:"POST",
dataType:'json',
url: "<?= Router::Url(['controller' => 'cab_facturas', 'action' => 'addDetFac'], TRUE); ?>/",//teacher//getdata/3
data:data1,
success: function(data){
alert(data);
}//success
});
});
this is what I had to POST the data from datatable, but I dunno why is the function to send to my php function that will insert.
You can consume the data object sent from your AJAX call as POST parameters or query string parameters depending on your settings. Consider you want to access firstname, lastname and email from your server side script. It can be done using:
$firstname = _POST['firstname'];
$lastname = _POST['lastname'];
$email = _POST['email'];
Now, Connect to your database and insert this data through your php script:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Its good practice to send a response to your call back functions so you can do this:
echo json_encode(array('status'=>"Success", message=""));
Your call back function will contain the data sent back from the php file. Since we are sending back a json string, we can make an object of it like this:
var myCallbackFunction = function(data){
var d = $.parseJSON(data)[0];
if(d.Status=="Success"){
//reload your datatable ajax
}else{
alert(d.message);
}
}
I hope that helped!
I have a question re. receiving data from php-function to ajax.
Ajax (in html-file):
function showUser(name) {
$.ajax({
type: 'POST',
url: '/api.php',
data: {
name : "\""+name+"\"",
func_id : "1"
},
dataType: 'json',
success: function(data)
{
if (data == null) {
console.log("Something went wrong..");
} else {
console.log(data);
Php (separate php-file):
<?php
error_reporting(E_ALL);
//MySQL Database connect start
$host = "localhost";
$user = "root";
$pass = "root";
$databaseName = "TFD";
$con = mysqli_connect($host, $user, $pass);
if (mysqli_connect_errno()) {
echo "Failed to connect to database: " . mysqli_connect_error();
}
$dbs = mysqli_select_db($con, $databaseName);
//MySQL Database connect end
$func_id = $_POST['func_id'];
function showUser() {
global $con;
$name = $_POST['name'];
$sql = "SELECT * FROM users WHERE first_name=$name";
$result = mysqli_query($con, $sql);
$array = mysqli_fetch_row($result);
mysqli_close($con);
echo json_encode($array);
}
if ($func_id == "1") {
showUser();
}
?>
The question: Everything works if I don't have the showUser-function in the php, i.e. I receive correct output to ajax if I have all php code in the "root" directly, but when I put that part in a function I don't get anything sent to ajax. The Network-panel in Chrome shows correct query from the sql so $array contains correct data, but I don't receive it in ajax.
Is there a fix for this?
Thanks!
The reason may be that the variables inside a function're visible only for function itself. Try this way:
$name = $_POST['name'];
function showUser($name) {
global $con;
$sql = "SELECT * FROM users WHERE first_name=$name";
$result = mysqli_query($con, $sql);
$array = mysqli_fetch_row($result);
mysqli_close($con);
echo json_encode($array);
}
Note: If you'll use 'mysql_escape_string' to prevent sql injections, don't forget to connect to db first, otherwise 'mysql_escape_string' will return empty string.