I have registration module and I already done so far the validation of all fields(fields are: name, email, username and password),check if the email and username is already existing.
And trying to add a suggestion if the username is already existing. I am done in adding a prefix in the username but having a problem to pass the variable to javascript and display it in my view
This is my Controller
$get_username = clean_data($_POST['username']);
$where = array(
"username" => $get_username
);
$check_username = $this->Crud_model->count_result('username','users',$where);
if($check_username > 0)
{
$fetch_username = $this->Crud_model->user_exists('users',$where);
$last_username = strrev((int)strrev($fetch_username)); // returns last numeric value of username
if($last_username){
$count = count($last_username);//counts number of digit
$str = substr($username, 0, -($count));;// subtract numeric value from last of username
}
$newstr = $last_username+1;
$username= $get_username.$newstr;
echo json_encode("existing");
// echo "var username = ". json_encode($username).";";
}
else
{
$insert_user = array(
'first_name' => clean_data(ucwords($_POST['first_name'])),
'last_name' => clean_data(ucwords($_POST['last_name'])),
'profile_picture' => "profile-picture.jpg",
'username' => $get_username,
'email' => $_POST['email'],
'password' => hash_password($_POST['password']),
'status' => 1,
);
$this->Crud_model->insert('users',$insert_user);
echo json_encode("success");
}
this is My javascript with ajax
$(document).ready(function(){
$("#registration-form").on('submit',function(e){
$.ajax({
url: base_url+"formsubmit/new_form_submit",
type: "POST",
data: $(this).serialize(),
success:function(data)
{
var result = JSON.parse(data);
if(result === "success")
{
$("h5").html("");
success_message("#success-message-new-account","Create Successful!");
window.setTimeout(function(){location.href=base_url},2000);
}
else if(result === "existing")
{
$("h5").html("");
success_message("#existing-message-account","You may use!".$username);
// window.setTimeout(function(){location.href=base_url},2000);
}
else{
$("#first_name_error").html(result.first_name_error);
$("#last_name_error").html(result.last_name_error);
$("#username_error").html(result.username_error);
$("#email_error").html(result.email_error);
$("#password_error").html(result.password_error);
}
},
error: function(data) {
alert('error');
}
})
e.preventDefault();
})
})
This is my My View
<div id="existing-message-account"></div>
<div class="wrap-input100 validate-input">
<input class="input100" type="text" name="first_name" id="first_name">
<span class="label-input100">First</span>
</div>
<div class="wrap-input100 validate-input">
<input class="input100" type="text" name="last_name" id="last_name">
<span class="label-input100">Last</span>
</div>
After the user fill up the registration form. It will be process in my javascript, now it will be check if the username registered is already existing or not. if it is not then it will be save in my table. If it is existing then it will add a number prefix.
Example
In my table users. I have existing username abcd, if the user register abcd then there would be a message "Username is already taken, you may use abcd1"
Question: How do I pass the variable $username into my javascript?
NOTE: I tried this approach, changing echo json_encode("existing"); into this echo json_encode($username). My javascript else if(result === $username)... The message will not work anymore.
Hope this will help you :
For the existing status record do like this :
$data['username'] = $username;
$data['status'] = 'existing';
echo json_encode($data);
exit;
For the success status record return like this
$data['username'] = $username;
$data['status'] = 'success';
echo json_encode($data);
exit;
Your ajax success part should have code like this :
var result = JSON.parse(data);
if(result.status === "success")
{
$("h5").html("");
success_message("#success-message-new-account","Create Successful!");
window.setTimeout(function(){location.href=base_url},2000);
}
else if(result.status === "existing")
{
$("h5").html("");
success_message("#existing-message-account","You may use!" + result.username);
// window.setTimeout(function(){location.href=base_url},2000);
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
User inputs his phone number in an HTML form and then fills the google recaptcha, and presses a button. If the phone number section and recaptcha section are successfully completed, then a function named "sendOTP" is called from a javascript file, which uses the phone number to send an OTP to that number. Everything seems to be working, [except that I get this error]. I believe the phone number(which is represented as $_SESSION['Telephone'] is not passed successfully on to the javascript file to be used.
In this case, how can I pass on the variable to the javascript so that it can successfully send an OTP to the number?
Here is the validate-captcha.php code which validates the captcha, and if successful, it sends calls the sendOTP():
<?php
session_start();
$ph_number = '';
if (isset($_POST['g-recaptcha-response']))
{
$secret = "key1";
$ip = $_SERVER['REMOTE_ADDR'];
//echo $ip;
$response = $_POST['g-recaptcha-response'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$ip";
$fire = file_get_contents($url);
//echo $fire;
$numero = $_SESSION['Telephone'];
$data = json_decode($fire);
if ($data->success == true)
{
echo '<script type="text/javascript">
var $("#mobile").val() = "<?php echo"$numero"?>";
</script>';
echo '<script src="jquery-3.2.1.min.js" type="text/javascript"></script>';
echo '<script src="verification.js">
</script>';
echo '<script>sendOTP()</script>';
return 1;
}
else
{
echo "Please fill captcha";
echo $numero;
}
}
?>
Here's the javascript (verification.js) code:
function sendOTP() {
$(".error").html("").hide();
var number = $("#mobile").val();
if (number.length == 8 && number != null && (number.indexOf(5)==0 || number.indexOf(6)==0 || number.indexOf(9)==0)) {
var input = {
"mobile_number" : number,
"action" : "send_otp"
};
$.ajax({
url : 'controller.php',
type : 'POST',
data : input,
success : function(response) {
$(".container").html(response);
}
});
} else {
$(".error").html('Please enter a valid Hong Kong number!')
$(".error").show();
}
}
async function verifyOTP() {
var that = this;
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#mobileOtp").val();
var input = {
"otp" : otp,
"action" : "verify_otp"
};
if (otp.length == 6 && otp != null) {
const handlerA = async function() {
var res = false
try {
await $.ajax({
url : 'controller.php',
type : 'POST',
dataType : "json",
data : input,
success : function(response) {
$("." + response.type).html(response.message);
$("." + response.type).show();
if (response.type=='success') {
res = true
} else if (response.type == 'error') {
res = false
}
},
error : function(response) {
console.log ('fail')
//console.log(data)
alert("Error encountered. Please try again later.");
}
});
return res;
} catch (err) {
console.error( err )
}
}
const handlerB = async function () {
await $.ajax({
url : 'submission.php',
type : 'POST',
data : input,
dataType : "json",
success : function(response) {
$(".container").html(response);
}
})
}
let $resultA = await handlerA()
// Now exec B
if ($resultA == true) {
let $resultB = await handlerB();
$resultB;
}
} else {
$(".error").html('You have entered wrong OTP.')
$(".error").show();
}
}
If necessary, then here is the PHP file(controller.php) where the sendOTP() function is defined:
<?php
session_start();
error_reporting(E_ALL & ~ E_NOTICE);
require ('textlocal.class.php');
include('config/db_connect.php');
class Controller
{
function __construct() {
$this->processMobileVerification();
}
function processMobileVerification()
{
switch ($_POST["action"]) {
case "send_otp":
$mobile_number = $_POST['mobile_number'];
$sender = 'me';
$otp = rand(100000, 999999);
$_SESSION['session_otp'] = $otp;
$message = "Your One Time Password is " . $otp;
$numbers = array(
$mobile_number
);
$url = 'https://www.something.hk/s.php';
$data = array(
"user" => "user",
"pass" => "password",
"to" => $mobile_number,
"from" => $sender,
"unicode" => 0,
"mess" => $message,
"otp" => 1,
"schtime" => 0
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
require_once ("verification-form.php");
break;
case "verify_otp":
$otp = $_POST['otp'];
$MPF_account = $_SESSION['MPF_account'];
$Telephone = $_SESSION['Telephone'];
$Gender = $_SESSION['Gender'];
$Job = $_SESSION['Job'];
$Monthly_salary = $_SESSION['Monthly_salary'];
$Existing_loan = $_SESSION['Existing_loan'];
$Residential_Type = $_SESSION['Residential_Type'];
$Existing_loan = $_SESSION['Existing_loan'];
$Job_Type = $_SESSION['Job_Type'];
$Existing_loan_amount = $_SESSION['Existing_loan_amount'];
if ($otp == $_SESSION['session_otp']) {
unset($_SESSION['session_otp']);
echo json_encode(array("type"=>"success", "message"=>"Thank You! Your form has been successfully submitted." ,"MPF_account"=>$MPF_account,
"Telephone"=>$Telephone,"Gender"=>$Gender,"Job"=>$Job,"Monthly_salary"=>$Monthly_salary,"Existing_loan"=>$Existing_loan,
"Residential_Type"=>$Residential_Type,"Existing_loan"=>$Existing_loan,"Job_Type"=>$Job_Type,"Existing_loan_amount"=>$Existing_loan_amount
));
}
else {
echo json_encode(array("type"=>"error", "message"=>"Mobile number verification failed"));
}
break;
}
}
}
$controller = new Controller();
?>
Also, here is the HTML form that was used at the first stage:
<!DOCTYPE html>
<html>
<head>
<title>OTP SMS</title>
<link href="style.css" type="text/css" rel="stylesheet" />
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="verification.js"></script>
<?=(isset($_POST['g-recaptcha-response']) && $data->success) ? "<script>sendOTP()</script>" : ""?>
</head>
<body>
<div class="container">
<div class="error"></div>
<form action="validate-captcha.php" id="frm-mobile-verification" method="POST">
<div class="form-heading">Mobile Number Verification</div>
<div class="form-row">
<input type="number" id="mobile" class="form-input" placeholder="Enter the 8 digit mobile" value="<?php echo $_SESSION['Telephone'] ?>">
</div>
<div method="post" class="g-recaptcha" data-sitekey="key2"></div>
<input type="submit" name="submit" value="Submit" class="btn brand z-depth-0">
</form>
</div>
<script src="jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="verification.js"></script>
</body>
</html>
Fixing JavaScript output by PHP
You have this in your code:
var $("#mobile").val() = "<?php echo"$numero"?>";
This is not valid JavaScript you are outputting.
var must be used with a variable name. That is what the syntax error is supposed to tell you.
What you intended is to set the value. Look at the jQuery documentation on how to do that:
https://api.jquery.com/val/#val2
That leaves us with this solution...
$("#mobile").val("' . $numero . '");
...which puts the value for $numero from the PHP variable into the input field with id mobile.
Fixing the order of JavaScript
Your PHP code now outputs this:
echo '<script type="text/javascript">
var $("#mobile").val() = "' . $numero . '";
</script>';
echo '<script src="jquery-3.2.1.min.js" type="text/javascript"></script>';
Notice you add jQuery after you do $("#mobile").val(), which requires jQuery. So you have to add jQuery first (includes the fix from before):
echo '<script src="jquery-3.2.1.min.js" type="text/javascript"></script>';
echo '<script type="text/javascript">
$(document).ready(function(){
$("#mobile").val("' . $numero . '");
});
</script>';
Notice I also added a document.ready handler to load the HTML document first before calling the JavaScript.
Please respect the comments
Please read the comments again. They were trying to help you discover the JavaScript error there. You were insisting your code is okay - or at least your wording indicated you don't see the problem at all - you "just need the solution".
They were hinting you should rethink and you were showing no signs of understanding the syntax error is fault of your code.
You are supposed to go "Oh maybe the syntax is wrong, I will check the documentation again how to do that".
My PHP username validation with Ajax duplicates my html page inside of html div(this is for showing ajax error) element. I tried some solutions and google it bu can't find anything else for solution. Maybe the problem is about the $_POST but I also separated them in php (all the inputs validation).
Here is PHP code
<?php
if(isset($_POST['username'])){
//username validation
$username = $_POST['username'];
if (! $user->isValidUsername($username)){
$infoun[] = 'Your username has at least 6 alphanumeric characters';
} else {
$stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
$stmt->execute(array(':username' => $username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (! empty($row['username'])){
$errorun[] = 'This username is already in use';
}
}
}
if(isset($_POST['fullname'])){
//fullname validation
$fullname = $_POST['fullname'];
if (! $user->isValidFullname($fullname)){
$infofn[] = 'Your name must be alphabetical characters';
}
}
if(isset($_POST['password'])){
if (strlen($_POST['password']) < 6){
$warningpw[] = 'Your password must be at least 6 characters long';
}
}
if(isset($_POST['email'])){
//email validation
$email = htmlspecialchars_decode($_POST['email'], ENT_QUOTES);
if (! filter_var($email, FILTER_VALIDATE_EMAIL)){
$warningm[] = 'Please enter a valid email address';
} else {
$stmt = $db->prepare('SELECT email FROM members WHERE email = :email');
$stmt->execute(array(':email' => $email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (! empty($row['email'])){
$errorm[] = 'This email is already in use';
}
}
}
?>
Here is Javascript
<script type="text/javascript">
$(document).ready(function(){
$("#username").keyup(function(event){
event.preventDefault();
var username = $(this).val().trim();
if(username.length >= 3){
$.ajax({
url: 'register.php',
type: 'post',
data: {username:username},
success: function(response){
// Show response
$("#uname_response").html(response);
}
});
}else{
$("#uname_response").html("");
}
});
});
</script>
<input type="text" name="username" id="username" class="form-control form-control-user" placeholder="Kullanıcı Adınız" value="<?php if(isset($error)){ echo htmlspecialchars($_POST['username'], ENT_QUOTES); } ?>" tabindex="2" required>
<div id="uname_response" ></div>
Here is the screenshot:
form duplicate screenshot
The only code in your PHP file should be within the <?php ?> tags. You need to seperate your PHP code into another file.
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.
Im all new to ajax and jquery so iam asking u guys for some help. I have to forms that one creates a new user and second logs the user in.
The functions work greate, but i want to create alert boxes for success or failure of the functions.
And i dont know how... Here is my code
HTML
<!-- Formular for signing up -->
<h4 class="form-headline"> Not a member? Sign up here </h4>
<form method="post">
<div class="form-group">
<label> Username </label>
<input type="text" class="form-control" id="newusername">
</div>
<div class="form-group">
<label> Password </label>
<input type="password" class="form-control" id="newpassword">
</div>
<div class="form-group">
<label> Your club </label>
<input type="text" class="form-control" id="newclub">
</div>
<input type="button" id="btn-reg" class="btn btn-success" value="Sign up!">
</form>
Script
// -----------------Registration of new user----------------------
console.log('Script loaded...');
// Calling for the method - reg
$("#btn-reg").on("click", reg);
function reg(e) {
e.preventDefault();
console.log('Klick, klick...');
// Declaring variables
var newusername=$("#newusername").val();
var newpassword=$("#newpassword").val();
var newclub=$("#newclub").val();
$.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
},
function(data){
console.log(data);
});
}
PHP
// Creating instance of the class userClass.php
var_dump($_POST);
if(isset($_POST['newusername'])){
// Defining variables
$newusername = $_POST['newusername'];
$newpassword = $_POST['newpassword'];
$newclub = $_POST['newclub'];
// Password hash
$hashpassword = sha1($newpassword);
$user = new User();
$user->newUsers($newusername, $hashpassword, $newclub);
} else {
}?>
OOP
// >>>>>>>>>>>>>>>> Function for saving new user to database
public function newUsers($newusername, $hashpassword, $newclub) {
// Using prepared statement to prevent mysql injections.
$stmt = $this->db->prepare("INSERT INTO users(username, password, club)VALUES(?, ?, ?);");
$stmt->bind_param("sss", $newusername, $hashpassword, $newclub);
if($stmt->execute()) {
echo "<h3 class='usercreated'>Created</h3>";
} else {
echo "<h3 class='usercreated'> Failed </h3>";
}
}
Just noticed that you are using function to create a new user, my bad again
if(isset($_POST['newusername'])){
// Defining variables
$newusername = $_POST['newusername'];
$newpassword = $_POST['newpassword'];
$newclub = $_POST['newclub'];
// Password hash
$hashpassword = sha1($newpassword);
$user = new User();
$status = $user->newUsers($newusername, $hashpassword, $newclub);
if($status) {
echo json_encode(array("status" : "success"));
}else {
echo json_encode(array("status" : "failed"));
}
}
Make a return from this function
public function newUsers($newusername, $hashpassword, $newclub) {
// Using prepared statement to prevent mysql injections.
$stmt = $this->db->prepare("INSERT INTO users(username, password, club)VALUES(?, ?, ?);");
$stmt->bind_param("sss", $newusername, $hashpassword, $newclub);
if($stmt->execute()) {
return true;
}else {
return false
}
}
this will be the same
$.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
},
function(data){
var object = JSON.parse(data);
alert(object.status);
// or you can add if else by using the status
});
}
You could just echo the script tag.
if($stmt->execute()) {
echo "<h3 class='usercreated'>Created</h3>";
echo "<script type="text/javascript">";
echo "alert("Hello World!")";
echo "</script>";
} else {
echo "<h3 class='usercreated'> Failed </h3>";
echo "<script type="text/javascript">";
echo "alert("Hello World!")";
echo "</script>";
}
}
For the Script block.
var posting = $.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
});
posting.done(function( data ) {
alert( "Data Loaded Ok");
});
posting.fail(function( data ) {
alert( "Error loading data");
});
Hope this helps you.
I have the following code that I thought worked correctly, but it turns out the users session is not being sent correctly. Let's say I was on trying to make a post, it does not take my id, it takes the id of the last user who registered for my site. Why would this be?
I have this as my $userid variable and it should be taking my session. I am initializing the session at the top of the page.
What am I doing wrong?
$(document).ready(function(){
$("#submit_announcement").on("click", function () {
var user_message = $("#announcement_message").val();
//$user = this.value;
$user = $("#approved_id").val();
$.ajax({
url: "insert_announcements.php",
type: "POST",
data: {
"user_id": $user,
//"message": user_message
"user_message": user_message
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to get user info!");
alert(data);
} else {
$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html('Announcement Successfully Added!');
$('.announcement_success').delay(5000).fadeOut(400);
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + "|" + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
});
PHP and Form
$userid = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
try {
//Prepare
$con = mysqli_connect("localhost", "", "", "");
if ($user_stmt = $con->prepare("SELECT `id` FROM users")) {
$user_stmt->execute();
$user_stmt->bind_result($user_id);
if (!$user_stmt) {
throw new Exception($con->error);
}
}
$user_stmt->store_result();
$user_result = array();
?>
<div class="announcement_success"></div>
<p>Add New Announcement</p>
<form action="" method="POST" id="insert_announcements">
<input type="hidden" value="<?php echo $userid; ?>" id="approved_id" name="user_id" />
<textarea rows="4" cols="50" id="announcement_message" name="message" class="inputbarmessage" placeholder="Message" required></textarea>
<label for="contactButton">
<button type="button" class="contactButton" id="submit_announcement">Add Announcement</button>
</label>
</form>
UPDATE: PHP file to show an example
// $announcement_user_id= $_POST['user_id'];
$userid = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
$announcement_message= $_POST['user_message'];
$test = print_r($_POST, true);
file_put_contents('test.txt', $test);
//var_dump($announcement_user_id);
$con = mysqli_connect("localhost", "", "", "");
$stmt2 = $con->prepare("INSERT INTO announcements (user_id, message, date) VALUES (?, ?, NOW())");
if ( !$stmt2 || $con->error ) {
// Check Errors for prepare
die('Announcement INSERT prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt2->bind_param('is', $userid, $announcement_message)) {
// Check errors for binding parameters
die('Announcement INSERT bind_param() failed: ' . htmlspecialchars($stmt2->error));
}
if(!$stmt2->execute()) {
die('Announcement INSERT execute() failed: ' . htmlspecialchars($stmt2->error));
}
//echo "Announcement was added successfully!";
else
{
echo "Announcement Failed!";
}
You're selecting all of the users:
SELECT `id` FROM users
So when you get one record from that result, it's probably going to coincidentally be the latest record in the table.
You're trying to bind a parameter to i:
$user_stmt->bind_result($user_id);
so maybe you meant to have a WHERE clause?
SELECT `id` FROM users WHERE `id` = ?
Though, that seems... unnecessary. Since you already have the ID. You seem to be posting the ID from client-side, and keeping it in session state, and getting it from the database. So it's not entirely clear what you're even trying to do here. But one thing that is clear is that query is going to return every record from that table.