I've been working on a website for quite some time, but it was all done on localhost. After making login form work properly I decided to upload it to hosting.
Issue is that callback functions of ajax don't seem to work if I use method: POST
If I change POST to GET it will work...
Ajax code:
$.ajax({
method: 'POST',
url: "php/login.php",
data: { username: val_username, password: val_password },
success: function(response) {
if (response == 0) {
location.reload();
} else {
alert("Wrong username or password. Error #"+response);
}
}
});
login.php
<?php
session_start();
require "../php_includes/mysql.php";
// Create connection
$conn = new mysqli($db_server, $db_user, $db_pass, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// escape your parameters to prevent sql injection
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$sql = "SELECT * FROM korisnici WHERE username='$username'";
$sql_result = $conn->query($sql);
if ($sql_result->num_rows > 0) {
$row = $sql_result->fetch_assoc();
if (password_verify($password, $row["password"])) {
$_SESSION["loggedin"] = true;
$_SESSION["userid"] = $row["id"];
echo 0;
} else echo 2;
} else echo 1;
?>
I have checked all the file locations, no issue there, since everything works if I change method to GET.
I tried changing datatypes in ajax, tried adding some headers to php file that I've found searching around stackoverflow, but nothing helps...
Make sure you have the same version of PHP on the hosting server (at least PHP 5.5 since you're using password_verify() which is for >= PHP 5.5).
Related
I've tried to pass the "hide" value for delete a record. But the JS function send the data but the mysql code don't work.
With the "insert to" it works, for this it's strange that the same code don't work.
This is my code.
<script type="text/javascript">
function invia()
{
var hides = document.getElementById('hide').value;
$.ajax({
type: 'POST',
url: "note_db_php/delete_db_note.php",
data: {"hide": hides},
success: function(data){
console.log("Dati inviati");
},
error: function(data) {
console.log("Dati non inviati");
}
});
};
</script>
and this is the delete page;
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
$hide = $_POST["hide"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql = "DELETE FROM note WHERE id='$hide'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
The console.log it work, and print "Dati inviati". So really, I don't understand. I have not error's message. But still don't work.
I have no idea why your code is not working -- you haven't described in any detail what error messages you are getting. But what other problem you have is that you are leaving yourself open to SQL Injection attacks and so you should be using a prepared statement. If this also corrects your problem (doubtful), that's a bonus:
$stmt = $conn->prepare("DELETE FROM note WHERE id=?");
/* Bind our parameter: */
$stmt->bind_param('i', $hide); // assuming $hide is an integer value, else use 's' for string
$success = $stmt->execute(); // execute the statement
if (!$success) {
error code here
}
$stmt->close();
I think the issue is with the sql query - $sql = "DELETE FROM note WHERE id=$hide";
Can you put the $hide in single quotes and try?
$sql = "DELETE FROM note WHERE id='$hide'"; // this will work
here your problem in sql syntax, and one line
enter code here
after else open on your code that causing error
updated query here , its working
// sql to delete a record
$sql = "DELETE FROM note WHERE id='$hide'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
The attribute dataType is missing and type should be method.
$.ajax({
url:"note_db_php/delete_db_note.php",
method:'POST',
dataType:'json',
data:{
"hide": hides
},
success:function(data) {
console.log("Dati inviati");
},
error: function (request, status, error) {
console.log("Dati non inviati");
}
});
Replace your query -
$sql = "DELETE FROM note WHERE id='$hide'";
With below one -
$sql = "DELETE FROM note WHERE id = ".$hide;
And on the ajax end please console your data. If it is giving error then please echo your query (echo $sql), and copy and run the query in PHPMyAdmin.
The Problem:
When I put a PHP file link in the browser, it works perfectly fine and updates my database as expected.
When I call it with ajax from node.js, it echoes the success message but the DB does not update.
The Session variables are undefined, so when I changed them to real numbers the code still did not work. What is going wrong?
My PHP Code:
subtract5.php:
<?php
header('Access-Control-Allow-Origin: http://cashballz.net:3000', false);
include 'mysql.php';
session_start();
$cash_amount = $_SESSION['cash_amount'];
$userid = $_SESSION['id'];
$_SESSION['cash_amount'] -= 0.05;
$mysql = new Mysql();
$result = $mysql->setCashAmount($cash_amount,$userid);
if($result)
{
echo $cash_amount;
}
else
{
session_start();
session_unset();
session_destroy();
}
?>
mysql.php:
<?php
class Mysql
{
protected $dsn;
protected $username;
protected $password;
public $db;
function __construct()
{
//change this to your info (myDBname, myName, myPass)
$this->dns= 'mysql:dbname=cashball_accounts;host=localhost;charset=utf8';
$this->username= 'myUser';
$this->password= 'myPass';
$this->db = new PDO($this->dns, $this->username, $this->password);
}
public function setCashAmount($cash_amount, $id)
{
$sql = "UPDATE users SET cash_amount = :cash_amount - 0.05 WHERE id = :id";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':cash_amount', $cash_amount, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_STR);
$result = $stmt->execute();
return $result;
}
}
?>
My node.js (app.js) AJAX:
//cut 5 cents from account - php function
$.ajax({
type: "POST",
url: 'http://cashballz.net/game/5game/subtract5.php',
data: {},
success: function (data) {
alert(data);
}
});
Recap:
PHP File works from site.com with the same AJAX code, and by putting its link in the browser.
PHP File is executed from node, but does not update the DB
PHP File has undefined $_SESSION variables but when replaced, the DB still does not update
Possible solutions:
Is there extra code i can put in AJAX to tell it to "pipe" the call to site.com to call the file instead of calling it straight from node?
Extra Info:
No errors in error logs or console
I need to use AJAX to input data into the file later on
Solution must be secure
Thanks for the help!
I'm trying to validate the form using AJAX. This is what I've done so far:
$('#login-form').submit(function(e) {
e.preventDefault();
var user = username.value;
var pass = password.value;
if (user != '' && pass != '') {
$('#login').html('Proccessing...');
$.ajax({
url: 'login.php',
type: 'POST',
data: {
username: user,
password: pass
},
processData: false,
contentType: false,
success: function(response) {
if (response == 'success') {
window.location.href = 'admin.php';
} else {
$('.login_message').html('Incorrect Credentails');
$('#login').html('Login');
}
}
});
} else {
$('.login_message').html('Fill All Fields');
$('#login').html('Login');
}
})
and it seems like response doesn't return success. Below is the login.php file
<?php
session_start();
$password = $username = '';
$_SESSION['user'] = $_SESSION['error'] = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['login'])) {
include_once('db.php');
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$password = md5($password);
echo 'username: ' . $username . ' and ' . ' password: ' . $password;
$sql = "select * from users where username = '" . $username . "' limit 1";
$query = mysql_query($sql);
if ($query) {
$row = mysql_fetch_assoc($query);
$dbpass = $row['password'];
if ($password == $dbpass) {
;
$_SESSION['user'] = $username;
header('Location: admin.php');
} else {
$_SESSION['error'] = 'Wrong username or password!';
}
} else {
echo mysql_error();
}
}
}
?>
If it happens you have found the solution, please explain to me how you find the solution and what I've done wrong.
Thank you in advance.
Since this is ajax request,we need to send some response from server. As you did in your question check if(response=='success'). To do that, you need to send success to your client. If everything is ok (data send to server and query) then in your login.php edit this line
if($password == $dbpass) {
$_SESSION['user'] = $username;
//comment this line
//header('Location: admin.php');
echo "success";
} else {
$_SESSION['error'] = 'Wrong username or password!';
}
Here I put one line code echo "success"; and I believe this will resolve your issue.
Returning values from PHP back to JS
When using AJAX, I believe if you do echo in the PHP target file (here login.php) it will act as a return. Therefore the code after a echo will not run as you might expect.
Also in your code you have: echo $_SESSION['error'] = '';
Use == to compare two object, = is the assignment operator.
Retrieving AJAX data in PHP file
The use of the ajax() method from jQuery in your code looks correct to me. So when the call is made the information is sent asynchronously to the server. More precisely it will send the parameters to the PHP file you've specified in the ajax object properties: login.php.
In login.php you can access your passed parameters in the $_POST array.
You would have the following:
$username = $_POST['username'];
$password = $_POST['password'];
// process information...
$state = 'success'
// now you can return a JSON object back to your page
// I strongly recommend using a PHP array and converting it to JSON
// this way it's very easy to access it back with JS
$response = array(state=$state)
echo json_encode($response);
And back in your jQuery code you access the state value with response.state
if(response.state == 'success') {
alert('It is a succcess!');
}
Debugging PHP target files
Now you generally have problems in the code in this PHP files. And it's not an easy thing to debug it. So the way I proceed is: I set the parameters in stone in login.php for instance:
$username = 'usernameTest'; // $username = $_POST['username'];
$password = 'passwordTest'; // $password = $_POST['password'];
Then I would open the PHP file in a browser and run it do see if it echoes the object and if there are any bugs.
Then you can put back $username = $_POST['username']; and $password = $_POST['password'];.
Actual code
<?php
session_start();
if (isset($_POST['username'], $_POST['password']) {
include_once('db.php');
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$password = md5($password);
$sql = "select * from users where username = '" . $username . "' limit 1";
$query = mysql_query($sql);
if ($query) {
$row = mysql_fetch_assoc($query);
$dbpass = $row['password'];
if ($password == $dbpass) {
$state = 'success';
} else {
$state = 'failed';
}
} else {
echo mysql_error();
}
}
Warning mysql(), md5() and SQL injections
Don't use the deprecated and insecure mysql_* functions. They have been deprecated since PHP 5.5 (in 2013) and were completely removed in PHP 7 (in 2015). Use MySQLi or PDO instead.
You are wide open to SQL Injections and should really use Prepared Statements instead of concatenating your queries. Using strip_tags() is far from a safe way to escape data.
Don't use md5() for password hashing. It's very insecure. Use PHP's password_hash() and password_verify() instead. If you're running a PHP version lower than 5.5 (which I really hope you aren't), you can use the password_compat library to get the same functionality.
- Magnus Eriksson
I have written a script i JQuery and PHP,
After the success return from PHP, AJAX function should catch a success response but I am not getting that.
Below is the code:
$.ajax({
url :"script_admin-add-category.php",
method :"POST",
data :{lExpensesId:lcl_ExpensesId},
success:function(data){
//if(data=="ok"){
if(data=="YES"){
alert("EMAIL");
}else{
alert(data);
}
//}
//if(data=="ok"){
//alert("Expenses Id already exists!");
//}else{
//alert(data);
//}
}
});
and here is the php code
//Check connection
if(!$conn){
die("Connection Failed: " .mysqli_connect_error());
}else{
//echo "helloooo";
if(isset($_POST["lExpensesId"])){
$lExpensesId = $_POST["lExpensesId"];
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId = '$lExpensesId'";
if($query_result = mysqli_query($conn, $Lquery)){
if(mysqli_num_rows($query_result )){
echo 'YES';
}else{
//echo "Proceed";
}
}else{
echo "Not Okay";
}
}else{
}
}
I can see the echo value on browser and alert value also. But if condition is not working for success function???
Try set correct data type for returned data.
$.ajax({
url: 'script_admin-add-category.php',
method: 'POST',
data: {lExpensesId: lcl_ExpensesId},
dataType: 'text',
success: function (data) {
if (data === 'YES') {
alert('EMAIL')
} else {
alert(data)
}
}
})
#J Salaria as i understood your question you are having problem with jquery AJAX and PHP code as you are not getting you desired result. There are different ways to send the data through jquery ajax which i will be explain in detail.
$_POST["lExpensesId"] are you getting this ID from a HTML <form> ?.Because here i'll be showing you 3 different practiced ways to send data through ajax..
NOTE: YOUR CODE IS VULNERABLE TO SQL INJECION. I'LL BE ALSO SHOWING YOU THE METHODS TO OVERCOME.IF YOU WANT TO LEARN MORE ABOUT SQL INJECTION CLICK ON THIS LINK SQL INJECTION LINK
HTML FORM CODE :
<form action="" id="send_lExpensesId_form" method="post">
<input type="text" name="lExpensesId" id="lExpensesId" >
<input type="submit" name="submit" >
</form>
FIRST WAY FOR SENDING DATA THIS IS THOUGH HTML <FORM>
<script>
$(document).ready(function(){
$("#send_lExpensesId_form").submit(function(e){
e.preventDefault();
var form_serialize = $(this).serialize();
$.ajax({
type:'POST',
url:'script_admin-add-category.php',
data:form_serialize,
success:function(data){
if(data == "YES"){
alert("EMAIL");
}else{
alert(data);
}
}
});
});
});
</script>
SECOND WAY FOR SENDING DATA THIS IS THOUGH HTML <FORM>
<script>
$(document).ready(function(){
$("#send_lExpensesId_form").submit(function(e){
e.preventDefault();
var form_serialize = new FormData($(this)[0]);
$.ajax({
type:'POST',
url:'script_admin-add-category.php',
data:form_serialize,
contentType: false,
processData: false,
success:function(data){
if(data == "YES"){
alert("EMAIL");
}else{
alert(data);
}
}
});
});
});
</script>
THIRD WAY FOR SENDING DATA THIS IS USED WHEN A LINK CLICKED OR TO DELETED THROUGH ID OR CLASS
<script>
$(document).ready(function(){
$("#send_lExpensesId_form").submit(function(e){
e.preventDefault();
var lcl_ExpensesId = $("#lExpensesId").val();
$.ajax({
type:'POST',
url:'script_admin-add-category.php',
data:{lExpensesId:lcl_ExpensesId},
success:function(data){
if(data == "YES"){
alert("EMAIL");
}else{
alert(data);
}
}
});
});
});
</script>
HERE IT THE PHP CODE WITH mysqli_real_escape_string(); AGAINST SQL INJECTION
<?php
$servername = "localhost";
$username = "root";
$password = "admin";
$dbname = "demo";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST["lExpensesId"])){
$lExpensesId = mysqli_real_escape_string($conn, $_POST["lExpensesId"]);
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId = '$lExpensesId'";
if($query_result = mysqli_query($conn, $Lquery)){
if(mysqli_num_rows($query_result )){
echo 'YES';
}else{
echo "Proceed";
}
}else{
echo "Error".mysqli_connect_error();
}
}
?>
HERE IT THE OTHER PHP CODE WITH MYSQLI->PREPARED WHICH IS BETTER AGAINST SQL INJECTION
<?php
// WITH MYSQLI PREPARED STATEMENT AGAINST SQL INJECTION
$sql = $conn->stmt_init();
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId =?";
if($sql->prepare($Lquery)){
$sql->bind_param('i',$lExpensesId);
$sql->execute();
$sql->store_result();
if($sql->num_rows > 0){
echo 'YES';
}else{
echo "Proceed";
}
}
else
{
echo "Error".mysqli_connect_error();
}
?>
I HOPE YOU GOT ANSWERE FOR YOU QUESTION IF YOU HAVE OTHER DOUBTS FEEL FREE AND COMMENT BELOW
All methods are known and many thanks for assistance. My question is that Why I am not able to get proper return from PHP. Below is my code:
var lcl_ExpensesId = $("#IExpensesId").val();
//alert(lcl_ExpensesId);
$.ajax({
url :"script_admin-add-category.php",
method :"POST",
data :{lExpensesId:lcl_ExpensesId},
success:function(data){
if(data=="ok"){
alert("Inserted");
}else{
alert(data);
}
}
});
ob_start();
/------------------FUNCTION TO READ ACCOUNTS DROPDOWN EXPENSES LIST -----------------------/
require_once 'db_config.php';
$newlist = fxn_CONFIGURATION();
$HOST = $newlist[0];
$DBNAME = $newlist[1];
$UNAME = $newlist[2];
$PSWD = $newlist[3];
$conn = mysqli_connect($HOST, $UNAME, $PSWD, $DBNAME);
//Check connection
if(!$conn){
die("Connection Failed: " .mysqli_connect_error());
}else{
if(isset($_POST["lExpensesId"])){
$lExpensesId = $_POST["lExpensesId"];
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId = '$lExpensesId'";
$query_result = mysqli_query($conn, $Lquery);
if(mysqli_num_rows($query_result) > 0){
echo "ok";
}else{
echo "Proceed";
}
}
}
mysqli_close($conn);
ob_flush();
As, i am using this AJAX in my one of input keyup method so whatever I will type, each and everytime, it will execute PHP script. I am having a item as FOOD in databse. When i type "F", I got Proceed, "O" - Proceed, "O" - Proceed, "D" - ok....
When I type D, i should get "Inserted" instead of Ok....
This is my doubt that why i m getting this????
The above problem is resolved by using exit() statement in PHP as I am getting five ↵↵↵↵↵ after my values and it means I am having 5 lines of html without closing ?>. So the best way to resolve the issue is to use exit() in PHP as per need
i use the following script to start a long poll with the php file.. it checks if any results are updated and sends a response ..
For some reason when this javascript is inserted all other scripts hangs on a long poll on fire bug
function waitForMsg(){
$.ajax({
type: "GET",
url: "auth/classes/getdata.php",
async: true,
cache: false,
success: function(data){
console.log(data)
setTimeout("waitForMsg()",1000);
},
error: function(XMLHttpRequest,textStatus,errorThrown) {
// alert("error: "+textStatus + " "+ errorThrown );
setTimeout("waitForMsg()",15000);
}
});
}
$(document).ready(
function()
{
waitForMsg();
});
This is the php file getdata.php
require_once($_SERVER['DOCUMENT_ROOT'].'/auth/config/db.php');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$user_id = $_SESSION['user_id'];
$lastmodif = time();
$update = 1;
while ($update <= $lastmodif) {
usleep(10000);
clearstatcache();
$sql = "select ua.user_id as member,ua.post_id,pa.user_id,pa.type,pa.time,CONCAT(u.first_name,' ',u.last_name) as
name,u.thumbnail from user_activity ua right join post_activity pa on
ua.post_id=pa.post_id right join users u on pa.user_id=u.user_id where
ua.user_id=".$user_id." and pa.time > FROM_UNIXTIME('".$lastmodif."')";
$result = $conn->query($sql) or die(mysqli_error());
if ($conn->affected_rows > 0) {
$update=$lastmodif;
$response = array();
$response['msg'] ='update';
echo json_encode($response);
}
}
Pretty sure your problem is
usleep(10000);
this will effectively stop execution and the ajax-cycle you try to initiate with setTimeout("waitForMsg()",1000); - usleep blocks for the execution logic.
<?
if(!define("_IS_GET"))
exit("Use another form to get get awww");
else
{
ignore_user_abort(TRUE);
set_time_limit(0); // adjust this to trap long time load
//...your lame process here
//sample you wanna dogetdata.php
$prId = shell_exec("nohup -f php '/path/to/your/getdata.php' /dev/null 2&<1 & $!",$display);
while(exec("$prId -s"))
echo $display."\n<BR>";
// note killing your jobs can be done using prId so its your initiative to store it and keep it ?
}
?>