When the AJAX is called I always get these errors:
net::ERR_EMPTY_RESPONSE or net::ERR_CONNECTION_RESET
I also tryed different browsers (Chrome and Edge) but it is only working on localhost.
Thanks for all your help and support.
My PHP code (register.php):
require_once 'mysql_conn.php';
// username and password sent from form
$myUsername = mysqli_real_escape_string($db,$_POST['username']);
$myPassword = mysqli_real_escape_string($db,$_POST['password']);
$myRepPassword = mysqli_real_escape_string($db,$_POST['rep_password']);
if($myPassword == $myRepPassword && strlen($myUsername) >= 3 && strlen($myPassword) >= 8)
{
$userCheck = "SELECT id FROM users WHERE username = '$myUsername'";
$result = mysqli_query($db,$userCheck);
$count = mysqli_num_rows($result);
if($count > 0)
{
echo "This user already exists";
}
else
{
$sql = "INSERT INTO users (username, password) VALUES ('$myUsername', '$myPassword')";
if ($db->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
}
}
else
{
echo "Please check the values you inserted";
}
and the AJAX call:
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'register.php',
data: {username:username, password:password, rep_password:rep_password},
success: function (data) {
errorHandling(data);
}
});
});
});
I don't know how, but I solved it by deleting and re-creating the register.php file
Related
I have a problem with my login form. Every time when i write (correct or incorrect) login and password in my login form, my JS script return error and when i try to print "response" it is empty.
Can anyone help?
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
var name = $("#name").val().trim();
var paw = $("#paw").val().trim();
$.ajax({
url: 'check.php',
type: 'POST',
data: {name:name, paw:paw},
success: function(response){
if(response == 1){
window.location= "home.php";
}
else{
alert("error");
}
}
});
});
});
<?php
session_start();
require_once 'dbconfig.php';
error_reporting(E_ALL ^ E_NOTICE);
if(isset($_POST['submit']))
{
$name = trim($_POST['name']);
$paw1 = trim($_POST['paw']);
$paw = md5($paw1);
try {
$stmt = $pdo->prepare("SELECT * FROM user WHERE login=:nazwa and haslo=:has");
$stmt->execute(array(':nazwa'=>$name, ':has'=>$paw));
$count = $stmt->rowCount();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['haslo']==$paw){
echo 1;
$_SESSION['user_session'] = $row['login'];
}
else {
echo 0;
}
} catch (\Exception $e) {
echo $e->getMessage();
}
}
?>
Remove the if(isset($_POST['submit'])) line. The reason is that the button key value is not sent via the AJAX call. To verify, do a print_r($_POST);
instead verify that name and password variables are not empty()
if (!empty($_POST['name']) && !empty($_POST['paw'])) {
}
Also do not use md5() for your passwords. use php's password_hash() to hash and password_verify() to verify that the posted password via the form matches the hash stored in the database for that user.
code from action.php
if(isset($_POST["username"]))
{
$query = "
SELECT * FROM Admin
WHERE Username = '".$_POST["username"]."'
AND Password = '".$_POST["password"]."'
";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
$_SESSION['username'] = $_POST['username'];
echo 'Yes';
}
else
{
echo 'No';
}
}
if(isset($_POST["action"]))
{
unset($_SESSION["username"]);
}
code from index.php
$(document).ready(function(){
$('#login_button').click(function(){
var username = $('#username').val();
var password = $('#password').val();
if(username != '' && password != '')
{
$.ajax({
url:"action.php",
method:"POST",
data: {username:username, password:password},
success:function(data)
{
//alert(data);
if(data == 'No')
{
alert("Wrong Data");
}
else
{
$('#loginModal').hide();
location.reload();
}
}
});
}
In the above index.php code always else part is executed. so I believe the data is not received from action.php code But $_SESSION['username'] = $_POST['username']; part of the code in action.php code is executed.
so my question is why 'Yes' or 'No' is not sent as it is expected.
any kind of help will be greatly appreciated;
use 'datas' in the alert.. You misspelled them
I have a an ajax post method that if success will alert "account successfully created". my problem is when it's not created it should alert account already exists, But what the problem it still alert the same.
script code:
$(document).ready(function(){
$("#btn-register").click(function(){
var regaccount = $("#regaccount").val();
var regpass = $("#regpass").val();
if((regaccount == "") || (regpass == "")){
alert("Information required!");
}else {
$.ajax({
type: "POST",
url: "register.php",
data: "regaccount="+regaccount+"®pass="+regpass,
success: function(data){
alert("account successfully created!");
},
error:function(){
alert("account already exists");
}
});
}
$("#regaccount").val('');
$("#regpass").val('');
return false;
});
});
register.php
<?php
include 'function.php';
session_start();
ob_start();
$userid = rand(100000, 999999);
$regaccount = $_POST['regaccount'];
$regpass = $_POST['regpass'];
$regaccount = stripslashes($regaccount);
$regpass = stripcslashes($regpass);
$salt = "dctech2015ABcRXd";
$regpass = md5($regpass) . $salt;
$regpass = sha1($regpass);
$con = new Functions();
$con = $con->db;
$stmt = $con->query("SELECT * FROM users WHERE username = '$regaccount'");
$count = $stmt->rowCount();
if($count != 1){
$con = new Functions();
$con = $con->db;
$status="Offline";
$stmt = $con->prepare("INSERT INTO users(user_id, username, password, status)VALUES(:userid, :account, :password, :status)");
$stmt->bindValue(':userid', $userid);
$stmt->bindValue(':account', $regaccount);
$stmt->bindValue(':password', $regpass);
$stmt->bindValue(':status', $status);
$stmt->execute();
}else{
echo '<script>alert("account name already exists");</script>';
}
ob_end_flush();
?>
You need to do following changes to make this work:
1) In your PHP code, do not write any alert.
2) Whether user exists in database or newly inserted, AJAX request will fetch only data. We have to handle the logic.
3) AJAX error method will be called only when AJAX request is failed (either request not sent or response status is not 200 OK).
4) In your case, error method will never be called if user already exists or even user is inserted as data is being correctly transferred from JavaScript to PHP.
if($count != 1){
$con = new Functions();
$con = $con->db;
$status="Offline";
$stmt = $con->prepare("INSERT INTO users(user_id, username, password, status)VALUES(:userid, :account, :password, :status)");
$stmt->bindValue(':userid', $userid);
$stmt->bindValue(':account', $regaccount);
$stmt->bindValue(':password', $regpass);
$stmt->bindValue(':status', $status);
$stmt->execute();
echo 'success';
}
else{
echo 'exists';
}
AND
$.ajax({
type: "POST",
url: "register.php",
data: "regaccount="+regaccount+"®pass="+regpass,
success: function(data){
if (data == 'success') {
alert("account successfully created!");
}
else if (data == 'exists') {
alert("account already exists");
}
},
error:function(){
alert("Unknown problem occured.");
}
});
Here you are trying to prompt message into AJAX error section which is wrong. You need to handle both into success section.
The very simple example is, return $count and check that value if greater then 0 means record is exist.
Changes in register.php code:
if($count != 1){
$con = new Functions();
$con = $con->db;
$status="Offline";
$stmt = $con->prepare("INSERT INTO users(user_id, username, password, status)VALUES(:userid, :account, :password, :status)");
$stmt->bindValue(':userid', $userid);
$stmt->bindValue(':account', $regaccount);
$stmt->bindValue(':password', $regpass);
$stmt->bindValue(':status', $status);
$stmt->execute();
}
echo $count;
I remove else part which is not require. And use $count for AJAX response.
And make correspond change into AJAX part also:
$.ajax({
type: "POST",
url: "register.php",
data: "regaccount="+regaccount+"®pass="+regpass,
success: function(data){
//If record exist...
if(data > 0){
alert("account name already exists");
}
else {
alert("account successfully created!");
}
},
error:function(){
alert("There is some error, Please try after some time OR contact site admin.");
}
});
Hope this is very easy to understand and help to other user also.
im not so sure how this works, but where does my success(data) value come from?
must I return a value in url: php/login.php?
$.ajax({
url: 'php/login.php', //must i return a value in login.php?
data: {username:username,password:password},
type: "POST",
dataType: 'json',
success: function(data)
{
if(data == true){
console.log("sdfsdfs " + data);
login.submit();
}
else{
console.log("NO DATA PRESENT");
}
}
//else do an alert("please lgo in again");
});
in php/login.php i query the DB to see if such a user exists and if password match
part of my login.php
<?php
echo $username = $_POST['username']; //not echo-ing
echo $password = $_POST['password'];
if ($_POST['login']) //check if the submit button is pressed
{
$remember = $_POST['remember'];
if ($username&&$password) //check if the field username and password have values
{
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$connect=mysqli_connect($dbhost,$dbuser,$dbpass) or die("Unable to Connect");
mysqli_select_db($connect,"clients") or die("Could not open the db");
$sql = "SELECT * FROM clients.users WHERE username='$username'";
$login = mysqli_query($connect, $sql);
if (mysqli_num_rows($login))
{
while ($row = mysqli_fetch_assoc($login))
{
$db_password = $row['password'];
if ($password==$db_password)
{
$loginok = TRUE;
echo json_encode( true );
} else {
echo json_encode( false );
echo "Please re-enter username and password, they did not match";
header("Location: ../login.php");
}
?>
When you want to return some data using ajax, you need to echo data in your script that will be called by ajax. If the request is successful, it will return everything you echoed in your script into your parameter you specified in success function.
success: function(data)
{
// code...
}
so "data" will contain result from your script, then you can do whatever you want.
EDIT:
Well, i would solve it like this
$db_password = $row['password'];
if ($password==$db_password)
{
echo json_encode(array("status" => "ok", "message" => "Login successful!"));
} else {
echo json_encode(array("status" => "error", "message" => "Please re-enter username and password, they did not match!"));
//header("Location: ../login.php"); you don't need this
}
you can't echo json, then some text after it. You can, but it is not recommended at all.
Apparently my POST requests are being cancelled?
http://puu.sh/d73LC/c6062c8c07.png
and also, mysqli_result object has all null values when i query the database with a select query:
object(mysqli_result)[2]
public 'current_field' => null
public 'field_count' => null
public 'lengths' => null
public 'num_rows' => null
public 'type' => null
here is my php file:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "uoitlol";
$name = "test1"; //this should be $_POST['name']; test1 is just to test if it works.
$err = false;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_errno > 0) {
echo 'connerr';
die();
}
$sql = "INSERT INTO summoners (name) VALUES (?)";
$getname = "SELECT name FROM summoners";
$result = $conn->query($getname);
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
if ($err === false) {
if (!$stmt->execute()) {
echo 'sqlerr';
} else {
echo 'success';
}
}
$stmt->close();
mysqli_close($conn);
here is my javascript file, which calls the php file with ajax whenever i click submit on my form (in a different html file)
$(document).ready(function () {
$("#modalClose").click(function () {
document.getElementById("signupInfo").className = "";
document.getElementById("signupInfo").innerHTML = "";
});
$("#formSubmit").click(function () {
var name = $("#name").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = {'name' :name};
if (name === '')
{
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>Please enter a summoner name!</b>";
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "submitName.php",
data: dataString,
cache: false,
success: function (msg) {
if (msg === 'error'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>That summoner name is already in the database!</b>";
} else if (msg === 'sqlerror'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>SQL error, contact the administrator.</b>";
} else if (msg === 'success'){
document.getElementById("signupInfo").className = "alert alert-success";
document.getElementById("signupInfo").innerHTML = "<b>Summoner successfully added!</b>";
}
}
});
}
return false;
});
});
I'm getting these errors everytime I click my button that submits my form:
Failed to load resource: Unexpected end of file from server (19:41:35:538 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:35:723 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:36:062 | error, network)
at public_html/submitName.php
I'm using Netbeans IDE, if that matters.
puu.sh/d6YXP/05b5f3dc06.png - screenshot of the IDE, with the output log errors.
Remove this from your submitName.php, unless there really is HTML in it.
<!DOCTYPE html>
If there is HTML in it, do this instead.
<?php
//your PHP code//
?>
<!DOCTYPE html>
//your HTML here//
</html>
Also, if submitName.php contains no HTML, make sure there is no blank line after ?> at the bottom.
EDIT: In regards to your query failing, try this code.
if (!empty($name) { //verify the form value was received before running query//
$getname = "SELECT name FROM summoners WHERE name = $name";
$result = $conn->query($getname);
$count = $getname->num_rows; //verify a record was selected//
if ($count != 0) {
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
} else {
echo "no record found for name";
exit;
}
}
Drop the ?> at the end of the php file and instead of using var dataString = 'name=' + name; use this instead:
var data = { "name" : name};
jQuery will automagically do the dirty stuff for you so that you don't have to special text-escape it and stuff.
That's as far as I can help without any log files and just a quick skim of your code.