Returning variables PHP, MySQL and JS - javascript

I'm developing an PHP-MySQL-JS platorm. I'm doing now the profile page and there the user can update his info.
My code is:
HTML
<form>
//rest of the form.
//The submit button.
<button id="profile_submit" style="margin-left: 500px; margin-top: 10px;" class="logout" type="submit"><b>Guardar cambios</b></button>
</form>
JavaScript
$( document ).ready(function() {
$('#profile_submit').click(function(){
var name1 = $('#name1').val();
var name2 = $('#name2').val();
var user = $('#user').val();
var email = $('#email').val();
if(name1 != '' && name2 != '' && user != '' && email != '' ){
$.ajax({
url: '../controller/updateuser.php',
method: 'POST',
data: {name1: name1, name2: name2, user: user, email: email},
success: function(msg){
if (msg == '1'){
//Error
alert("Another user is using this email already");
} else {
//Se registro
alert("Updated");
setTimeout(function(){location.href= "workspace.php"} , 1000);
}
}
});
}
});
});
PHP - general
public function update_user($name1, $name2, $user, $email){
$res = $this->conexion->query("select USR_EMAIL from usr_usuario where USR_EMAIL = '".$email."' and USR_DELETE = '0' and USR_ID <> '".$_COOKIE['USR_ID']."' ");
if(mysqli_num_rows($res)>0)
{
//Email used
echo '1';
}else{
//Update user
$this->conexion->query("UPDATE usr_usuario SET USR_USERNAME = '".$user."', USR_NAME = '".$name1."', USR_NAME2 = '".$name2."', USR_EMAIL = '".$email."' WHERE USR_ID = '".$_COOKIE['USR_ID']."' ");
}
}
PHP - update.php
<?php
require("../modelo/conexion.php");
$name1 = $_POST['name1'];
$name2 = $_POST['name2'];
$user = $_POST['user'];
$email = $_POST['email'];
$object = new conexion();
$object -> actualizar_usuario($name1, $name2, $user, $email);
$object -> cerrar();
?>
Well, when the user clicks on the button with id="profile_submit", the JS read the info in the inputs and sends it to update.php and it calls the update_user in general php file.
When the user insert an email used already it works perfectly, but, when all is okay, the sql UPDATE works but the rest of the code(PHP and JS) don't sends nothing to the user.
I don't know why this happens...
Help please.

Related

Throw PHP variable back to Ajax on submit form data

Okay so I have an ajax function which sends data to register-process.php. I want the register-process.php to send the PHP value $msg back to ajax. I tried using $('.message').html("<?php $msg; ?>").fadeIn(500); on success but it does not seems to work. Is there any way to do it?
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var email = $("#email").val();
var cpass = $("#cpass").val();
var dataString = {
username: $("#username").val(),
password: $("#password").val(),
email: $("#email").val(),
cpass: $("#cpass").val()
};
$.ajax({
type: "POST",
url: "register-process.php",
data: dataString,
cache: true,
success: function(html){
$('.message').html("<?php $msg; ?>").fadeIn(500);
}
});
return false;
});
});
</script>
register-process.php
<?php
include'config/db.php';
$msg = null;
$date = date('Y-m-d H:i:s');
$uname = (!empty($_POST['username']))?$_POST['username']:null;
$pass = (!empty($_POST['password']))?$_POST['password']:null;
$cpass = (!empty($_POST['cpass']))?$_POST['cpass']:null;
$email = (!empty($_POST['email']))?$_POST['email']:null;
if($_POST){
$stmt = "SELECT COUNT(*) FROM members WHERE mem_uname = :uname";
$stmt = $pdo->prepare($stmt);
$stmt-> bindValue(':uname', $uname);
$stmt-> execute();
$checkunm = $stmt->fetchColumn();
$stmt = "SELECT COUNT(*) FROM members WHERE mem_email = :email";
$stmt = $pdo->prepare($stmt);
$stmt->bindValue(':email', $email);
$stmt->execute();
$checkeml = $stmt->fetchColumn();
if($uname == '' or $pass == '' or $cpass == '' or $email == ''){
$msg = "<div class='message-error'>Fields cannot be left empty. Please fill up all the fields.</div>";
}else if($checkunm > 0){
$msg = "<div class='message-error'>This username is already registered. Please use a different username.</div>";
}else if($checkeml > 0){
$msg = "<div class='message-error'>This Email ID is already registered. Please use a different Email ID.</div>";
}else if($pass != $cpass){
$msg = "<div class='message-error'>Passwords are not matching.</div>";
}else if(strlen($uname) > 12){
$msg = "<div class='message-error'>Username should not be more than 12 characters long.</div>";
}else if(strlen($uname) < 6){
$msg = "<div class='message-error'>Username must be at least 6 characters long.</div>";
}else if(strlen($pass) < 6){
$msg = "<div class='message-error'>Password must be at least 6 characters long.</div>";
}else{
// If everything is ok, insert user into the database
$stmt = "INSERT INTO members(mem_uname, mem_pass, mem_email)VALUES(:uname, :pass, :email)";
$stmt = $pdo->prepare($stmt);
$stmt-> bindValue(':uname', $uname);
$stmt-> bindValue(':pass', password_hash($pass, PASSWORD_BCRYPT));
$stmt-> bindValue(':email', $email);
$stmt-> execute();
if($meq){
$msg = "<div class='message-success'>Congratulations! You have been registered successfully. You can now login!</div>";
}else{
$msg = "<div class='message-error'>Server Error! Please try again later. If problem persists, please contact support.</div>";
}
}
}
echo $msg;
?>
In your Ajax function no need to echo the php variable.Just map response to your html element like below:
$.ajax({
type: "POST",
url: "register-process.php",
data: dataString,
cache: true,
success: function(html){
console.log(html);//see output on browser console
$('.message').html(html).fadeIn(500);
}
});

PHP code works when called with form action but not with ajax

The PHP code for login validation works properly when run from the html page by using form action but when run using ajax script it fails to load.
PHP code not involving database seems to run fine though.
JavaScript
< script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" > < /script> <
script >
$(document).ready(function() {
$("#login").submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
$('#success').empty();
var postForm = { //Fetch form data
'name': $('input[name=name]').val(),
'password': $('input[name=password]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type: 'POST', //Method type
url: '.php', //Your form processing file url
data: postForm, //Forms name
dataType: 'json',
success: function(data) {
if (!data.success) { //If fails
if (data.errors.name) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors.name).append('<p>' + data.error + '</p>'); //Throw relevant error
alert("Nope");
}
} else {
$('#success').fadeIn(1000).append('<p>' + data.name + '</p>'); //If successful, than throw a success message
alert("yes");
}
}
});
event.preventDefault(); //Prevent the default submit
});
}); < /script>
PHP Code
<?php
$errors = array();
$form_data = array();
include("config.php");
if (session_status() == PHP_SESSION_NONE) {
session_start();}
else{
$_SESSION['ses']="Already in session":
/* Write already in session code */
}
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT * FROM users WHERE user_name = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if (empty($_POST['name'])) { //Name cannot be empty
$errors['name'] = 'Name cannot be blank';
}
if (!empty($errors)) { //If errors in validation
$form_data['success'] = false;
$form_data['errors'] = $errors;
}
else{
if($count == 1) {
$_SESSION['login_user'] = $myusername;
}else {
$error = "Your Login Name or Password is invalid";
$_SESSION["error"] = $error;
}
}
}
echo json_encode($form_data);
?>

PHP post request unidentified index error

I'm trying to write a page to make a POST request to a php script and I feel like I've done it right, it's worked everywhere else so it seems but I keep getting a "unidentified error" and it won't work, how can I get this to work?
Javascript:
$(document).ready(function() {
$("#x").click(function() {
var email = $("email").val();
var pass = $("password").val();
var confirmPass = $("confirmPassword").val();
var name = $("name").val();
var question = $("question").val();
var answer = $("answer").val();
if(pass != confirmPass) {
alert("Passwords do not match!");
return;
}
var stuff = {email: email, pass: pass, name: name, question: question, answer: answer};
$.ajax({method: "POST", url: "addAccount.php", data: stuff, success: function(result) {
alert(result);
window.location.href = "../Dashboard";
}});
});
});
PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "*********";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$email = $_POST["email"];
$pass = $_POST["pass"];
$name = $_POST["name"];
$question = $_POST["question"];
$answer = $_POST["answer"];
$sql = "INSERT INTO accounts (accountEmail, accountPassword, accountName, accountQuestion, accountRecover) VALUES ('$email', '$pass', '$name', '$question', '$answer')";
$conn->close();
if(mysql_affected_rows() > 0) {
$response = "Account added successfully!";
}
else {
$response = "Couldn't add account!";
}
$pre = array("Response" => $response);
echo json_encode($pre);
?>
You need to properly use jquery.
For example
var email = $("email").val(); //IS WRONG
Should be (if you have input id="email")
var email = $("#email").val();
If you have only name you can use
var email = $("[name='email']").val();
A bit offtopic:
If you are using form ajax submit consider jquery method serialize https://api.jquery.com/serialize/ for getting all form values (or some jquery ajaxform plugin).
And please! don't make insecure mysql statements. For gods sake use prepared statements.
If you need very basic stuff just use prepared statements or consider https://phpdelusions.net/pdo/pdo_wrapper
Also a small tip: before echo json make json header
<?php
header('Content-type:application/json;charset=utf-8');
I think you are mistaken with your jquery data, they should have identifier like id denoted by '#' and classes denoted by '.', do it this is you have id="name of the field" among the input parameters:
$(document).ready(function() {
$("#x").click(function() {
var email = $("#email").val();
var pass = $("#password").val();
var confirmPass = $("#confirmPassword").val();
var name = $("#name").val();
var question = $("#question").val();
var answer = $("#answer").val();
if(pass != confirmPass) {
alert("Passwords do not match!");
return;
}
var stuff = {email: email, pass: pass, name: name, question: question, answer: answer};
$.ajax({method: "POST", url: "addAccount.php", data: stuff, success: function(result) {
alert(result);
window.location.href = "../Dashboard";
}});
});
});
OR like this is you have class="name of the field" among the input parameters:
$(document).ready(function() {
$("#x").click(function() {
var email = $(".email").val();
var pass = $(".password").val();
var confirmPass = $(".confirmPassword").val();
var name = $(".name").val();
var question = $(".question").val();
var answer = $(".answer").val();
if(pass != confirmPass) {
alert("Passwords do not match!");
return;
}
var stuff = {email: email, pass: pass, name: name, question: question, answer: answer};
$.ajax({method: "POST", url: "addAccount.php", data: stuff, success: function(result) {
alert(result);
window.location.href = "../Dashboard";
}});
});
});
OR if you want to use the name directly follow this:
$(document).ready(function() {
$("#x").click(function() {
var email = $("input[name='email']").val();
var pass = $("input[name='pasword']").val();
var confirmPass = $("input[name='confirmPassword']").val();
var name = $("input[name='name']").val();
var question = $("input[name='question']").val();
var answer = $("input[name='answer']").val();
if(pass != confirmPass) {
alert("Passwords do not match!");
return;
}
var stuff = {email: email, pass: pass, name: name, question: question, answer: answer};
$.ajax({method: "POST", url: "addAccount.php", data: stuff, success: function(result) {
alert(result);
window.location.href = "../Dashboard";
}});
});
});
I hope this helps you
There are lots of reasons your code is not working. #AucT and #gentle have addressed your Javascript side issues so I'll focus on PHP. Your query code is:
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "...";
$conn->close();
Notice that:
you never execute you query. $sql is just a string held in memory.
you're mixing mysqli function with mysql_ function (mysql_affected_rows); that won't work
You're inserting POST data directly into your queries, so you are very vulnerable to SQL injection
At the end, you echo JSON, but you haven't told the browser to expect this format
Do this instead:
$conn = new mysqli(...);
//SQL with ? in place of values is safe against SQL injection attacks
$sql = "INSERT INTO accounts (accountEmail, accountPassword,
accountName, accountQuestion, accountRecover) VALUES (?, ?, ?, ?, ?)";
$error = null;
//prepare query and bind params. save any error
$stmt = $conn->prepare($sql);
$stmt->bind_param('sssss',$email,$pass,$name,$question,$answer)
or $error = $stmt->error;
//run query. save any error
if(!$error) $stmt->execute() or $error = $stmt->error;
//error details are in $error
if($error) $response = "Error creating new account";
else $response = "Successfully created new account";
//set content-type header to tell the browser to expect JSON
header('Content-type: application/json');
$pre = ['Response' => $response];
echo json_encode($pre);

Ajax database insert isnt working

I am trying to insert values from an input field into a database with ajax as part of a conversation system.I am using an input form as follows.
<input data-statusid="' .$statuscommentid. '" id="reply_'.$statusreplyid.'" class="inputReply" placeholder="Write a comment..."/>
with the following jquery I carry out a function when the enter key is pressed by the user.
$(document).ready(function(){
$('.inputReply').keyup(function (e) {
if (e.keyCode === 13) {
replyToStatus($(this).attr('data-statusid'), '1',$(this).attr("id"));
}
});
});
within this function is where I am having the problem ,I have no problems calling the function with jquery but I have done something wrong with the ajax and I don't know what?
$.ajax({ type: "POST", url: $(location).attr('href');, data: dataString, cache: false, success: function(){ $('#'+ta).val(""); } });
Additionally this is the php I am using to insert into the database
<?php //status reply input/insert
//action=status_reply&osid="+osid+"&user="+user+"&data="+data
if (isset($_POST['action']) && $_POST['action'] == "status_reply"){
// Make sure data is not empty
if(strlen(trim($_POST['data'])) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Clean the posted variables
$osid = preg_replace('#[^0-9]#', '', $_POST['sid']);
$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Make sure account name exists (the profile being posted on)
$sql = "SELECT COUNT(userid) FROM user WHERE userid='$userid' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
if($row[0] < 1){
mysqli_close($db_conx);
echo "$account_no_exist";
exit();
}
// Insert the status reply post into the database now
$sql = "INSERT INTO conversation(osid, userid, postuserid, type, pagetext, postdate)
VALUES('$osid','$userid','$postuserid','b','$pagetext',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
// Insert notifications for everybody in the conversation except this author
$sql = "SELECT authorid FROM conversation WHERE osid='$osid' AND postuserid!='$log_username' GROUP BY postuserid";///change log_username
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$participant = $row["postuserid"];
$app = "Status Reply";
$note = $log_username.' commented here:<br />Click here to view the conversation';
mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time)
VALUES('$participant','$log_username','$app','$note',now())");
}
mysqli_close($db_conx);
echo "reply_ok|$id";
exit();
}
?>
Thanks in advance for any help it will be much appreciated
Why didn't you set the proper URL for Ajax calls instead of using location.href?
var ajax = ajaxObj("POST", location.href);
In additional, I guess ajaxObj is not defined or well coded. You are using, jQuery, why don't you try jQuery ajax?
http://api.jquery.com/jquery.ajax/
var ajax = ajaxObj("POST", location.href);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "reply_ok"){
var rid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
_("status_"+sid).innerHTML += '<div id="reply_'+rid+'" class="reply_boxes"><div><b>Reply by you just now:</b><span id="srdb_'+rid+'">remove</span><br />'+data+'</div></div>';
_("replyBtn_"+sid).disabled = false;
_(ta).value = "";
alert("reply ok!");
} else {
alert(ajax.responseText);
}
ajax.send("action=status_reply_ok&sid="+sid+"&user="+user+"&data="+data);
}
}

If statement not working in javascript/ajax

Ok so this is driving me mad. I've got 2 modal forms - login and register. Javascript does the client side validation and then an ajax call runs either a registration php file or a login php file which returns OK if successful or a specific error message indicating what was wrong (incorrect password, username already taken,etc). There is an If Then statement that checks if the return message is OK and if it is then a success message is displayed and the other fields hidden.
The register form works perfectly. I get my OK back and fields get hidden and the success message displays.
The login form however doesn't work. A successful login returns an OK but the if statement fails and instead of a nicely formatted success message I just get the OK displayed without the username and password fields being hidden which is what makes me think the IF is failing although I cannot see why it would.
I've been staring at this code for hours now and all I can see is the same code for both and no idea why one is working and one is not ....
On to the code...Here is the Login javascript:
$("#ajax-login-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/login.php",
data: str,
success: function(msg) {
$("#logNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">You have succesfully logged in.</div>';
$("#ajax-login-form").hide();
$("#swaptoreg").hide();
$("#resetpassword").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
and here is the register javascript:
$("#ajax-register-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/register.php",
data: str,
success: function(msg) {
$("#regNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">Thank you! Your account has been created.</div>';
$("#ajax-register-form").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
I don't think I need to add the php here since both just end with an echo 'OK'; if successful and since I'm seeing the OK instead of the nicely formatted success message I'm confident that it is working.
Any suggestions?
EDIT: Here's the login php:
<?php
require("common.php");
$submitted_username = '';
$user = stripslashes($_POST['logUser']);
$pass = stripslashes($_POST['logPass']);
if(!empty($_POST))
{
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $user
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query ");
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $pass . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?> <!------- There is a space here! -->
There is a space after the closing ?> which is being sent to the user. The closing ?> is optional, and it is highly recommended to NOT include it, for just this reason. Get rid of that ?>.

Categories

Resources