Throw PHP variable back to Ajax on submit form data - javascript

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);
}
});

Related

Ajax is skipping success:function call

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

showing message after email generation or sending through ajax

function registration_ajax(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email','email','required|is_unique[register.email]');
if($this->form_validation->run() == FALSE){
$data = '{"status":"false","message":"Email already exists"}';
}
else
{
$email=$this->input->post('email');
$data= array(
'email'=>$email
);
$last_id = $this->model->registeration($data);
if ($last_id>0) {
$this->send_email($email);
$data = '{"status":"true","message":"Email Created successfully"}';
}
}
echo $data;
}
public function send_email($to='',$username="",$from='khadija#precisetech.com.pk')
///function send_mail()
{
$this->load->library('encrypt');
$toEmail = $this->encrypt->encode($to);
$toEmail = str_replace('/','forwardSlash',$toEmail);
$toEmail = str_replace('=','equalSign',$toEmail);
$toEmail = str_replace('+', 'plusSign', $toEmail);
$this->load->library('email');
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'sadasds';//pust mail.com.pk
$config['smtp_port'] = '25334';
$config['smtp_user'] = 'example';
$config['smtp_pass'] = 'example1';
$config['charset'] = 'utf-8';
$config['mailtype'] = 'html';
$config['validation'] = FALSE; // bool whether to validate email or not
$this->email->initialize($config);
$message = '<h1 align="center">Hellow</h1>';
$message = '<html><body style="color:#000; font-weight:normal; font-size:13/14px;"><p style="color:#000;">Hi!</p>';
$message .= '<table rules="all">';
$message .= "<p>Congratulations! You have almost completed your registration on Electronic Mall.<br><br>Click on link here to confirm your email address<br> 10.10.10.44<br><br>Thank you for joining us and becoming part of world's largest local classified sites.In our website, you can enjoy simple ad posting, easy searching and endless local listing for products.We appreciate you for choosing us in online market place.<br> Wishing you alot of success on your classified journey.Get started now!<br><br></p>";
$message .= "<p>Regards,<br>The Electronic Mall Team</p>";
$message .= "</table>";
$message .= "</body></html>";
$this->email->from($from);
$this->email->to($to);
$this->email->subject('Confirmation Email');
$this->email->message($message);
if(!$this->email->send()){
echo $this->email->print_debugger();
die();
}else{
}
}
////ajx code
//////////////////
<script>
$(document).ready(function(){
$('#registration_form').on('submit',function(e){
var email = $('#email').val();
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
// url: "<?=base_url('controller/register')?>",
type: "POST",
datatype: "JSON",
data: {email: email},
success: function(res){
var data = $.parseJSON(res);
var status = data.status;
var message = data.message;
if(status == 'true'){
/// $('#myModal').modal('hide');
$('#message_sent').html(message);
}
else{
$('#message').html(message);
}
}
});
e.preventDefault();
});
});
</script>
I want that after email is sent successfully then this message should be displayed
$data = '{"status":"true","message":"Email Created successfully"}';
When I commented the mail sending function then it display the successful message, I want that the message should be display after sending email.
have you tried returning a value from your send_email function?
if(!$this->email->send()){
return 'success';
}else{
$this->session->set_flashdata('message', 'To complete registration, click the link in email we just send you at khadija#precisetech.com.pk');
redirect('controller/login_register','refresh');
die();
}
then in your :
if ($last_id>0) {
$res = $this->send_email($email);
if($res === 'success'){
$data = '{"status":"true","message":"Email Created successfully"}';
}
}

"\r\n\" in alert for jquery ajax html

I have an ajax request that looks like this
$(document).ready(function() {
$(document).on('click', '#submit', function() {
var UserName = $('#username').val();
var PassWord = $('#password').val();
console.log(UserName);
$.ajax({
type: 'POST',
url: 'ajax/Login.php',
dataType: "text",
data: {
username: UserName,
password: PassWord
},
success: function(data) {
alert(JSON.stringify(data));
window.location='pages/mainpage.php';
},
error: function(data) {
alert('Login Error');
//window.location='../index.php';
}
});
});
});
and my php is like this
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
if (isset($username)) {
$stmt = $dbh->prepare("SELECT * FROM userlist_tbl WHERE username = ? ");
$stmt->bindValue(1, $username);
$stmt->execute();
$selected_row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($selected_row['username'] === $username) {
if ($selected_row['password'] === $password) {
$_SESSION['login_user'] = $username;
echo "Welcome ".$username;
}else{
echo "Password incorrect";
}
}
}else{
echo "Username is empty";
}
When i dont put anything in username i am expecting that the alert will be Username is empty same as when password is empty alert should be Password incorrect but i am getting "\r\n\" but if put some in username like John it will alert Welcome John"\r\n\" why is this happening?how to make it alert Username is empty when username is empty same with password?any idea is accepted..
Try this: in ajax section, dataType: "text", change to dataType: "json", and server php code is following: it may work
//put this function top of this page
ob_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$json="";
if (isset($username)) {
$stmt = $dbh->prepare("SELECT * FROM userlist_tbl WHERE username = ? ");
$stmt->bindValue(1, $username);
$stmt->execute();
$selected_row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($selected_row['username'] === $username) {
if ($selected_row['password'] === $password) {
$_SESSION['login_user'] = $username;
$json.="Welcome ".$username;
}else{
$json.="Password incorrect";
}
}
}else{
$json.="Username is empty";
}
ob_end_clean();
echo json_encode($json);
?>
I change isset to !empty fixed the problem

How to connect correct link directory files

I wanted to do is connect some files in different folder inside elogFiles folder. My problem is i dont know how to connect the files inside of another folder files.
here is the family tree of my files:
http://s38.photobucket.com/user/eloginko/media/folder_zpsa156e2a5.png.html
My problem the links is not correct.
Both code are not related. And the user.php is asking for connection from inside the dbc folder database.php and myScript.js wants to find user.php where is located inside the view folder.
myScript.js: " url: 'js/../view/user.php',"
user.php: "include_once('view/../dbc/database.php');"
can anyone help me correct the correct directory links.
user.php
<?php
include_once('../dbc/database.php');
$db = new Connection();
$db = $db->dbConnect();
$email = $_POST['email'];
$pass = $_POST['password'];
if(!empty($email) && !empty($pass)){
$st = $db->prepare("SELECT * from user WHERE email=? AND password=?");
$st->bindParam(1, $email);
$st->bindParam(2, $pass);
$st->execute();
if($st->rowCount() == 1){
echo "1";
exit;
} else {
echo "Incorrect Email or Password";
}
}else{
echo "Please enter Email and Password";
}
?>
myScript.js
$(document).ready(function() {
$('div#show:empty').hide();
$('#login').click(function(){
var email = $('#lemail').val();
var password = $('#lpassword').val();
$.ajax({
data: {
email : email, password : password
},
type: "POST",
url: 'js/../view/user.php',
success: function(data)
{
if (Number(data) == 1)
{
$(".show-page[data-page=progBar]").trigger("click");
$('#myModal').modal('hide');
}
else
{
$('div#show:empty').show();
$('#show').html(data);
}
}
});
return false;
});
});
As your hierarchy is presently, provided, if you are on your http://localhost/elogFiles/view/user.php, you just need to go level one up ../
user.php
<?php
include_once('../dbc/database.php');
$db = new Connection();
$db = $db->dbConnect();
$email = $_POST['email'];
$pass = $_POST['password'];
$response['status'] = '';
$response['message'] = '';
if(!empty($email) && !empty($pass)){
$st = $db->prepare("SELECT * from user WHERE email=? AND password=?");
$st->bindParam(1, $email);
$st->bindParam(2, $pass);
$st->execute();
if($st->rowCount() == 1){
$response['status'] = 'OK';
} else {
$response['status'] = 'ERROR';
$response['message'] = 'Username/Password not found';
}
}else {
$response['status'] = 'ERROR';
$response['message'] = 'Please input username/password';
}
echo json_encode($response);
exit;
?>
Since, user.php processes the AJAX request, point the AJAX url attribute to this file. Consider this example:
myScript.js
$.ajax({
data: {
email : email, password : password
},
type: "POST",
url: 'http://localhost/elogFiles/view/user.php',
dataType: 'JSON',
success: function(data) {
if (data.status == 'OK') {
$(".show-page[data-page=progBar]").trigger("click");
$('#myModal').modal('hide');
} else {
$('div#show:empty').show();
$('#show').html(data.message);
}
}
});

ajax cannot pass datastring to php

I can't receive the data value on my php script, the ajax success fires but the data on my database is not changed when I send this.
$.ajax({
type: "POST",
url: "database/clientpanel/agent_panel/notiffolder/notifedit.php",
data: {
email: email,
number: number,
emailon: emailon,
texton: texton,
email_delay: emaildel,
ext_delay: textdel,
timezone1: zone1,
timezone2: zone2
},
cache: false,
success: function(html){
$("#upnotif").show();
$("#errnotif").hide();
$("#errnotif1").hide();
$("#errnotif2").hide();
}
});
php
<?php
session_start();
include("../../../dbinfo.inc.php");
$query=" select * from tele_panel_notification where client='".$mysqli->real_escape_string($_SESSION['clientid'])."'";
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
$client = $row['client'];
if($client == ""){
$query = "insert into tele_panel_notification set
emailon = '".$mysqli->real_escape_string($_POST['emailon'])."',
texton = '".$mysqli->real_escape_string($_POST['texton'])."',
timezone = '".$mysqli->real_escape_string($_POST['timezone'])."',
timezone2 = '".$mysqli->real_escape_string($_POST['timezone2'])."',
email = '".$mysqli->real_escape_string($_POST['email'])."',
email_delay = '".$mysqli->real_escape_string($_POST['email_delay'])."',
text_delay = '".$mysqli->real_escape_string($_POST['text_delay'])."',
number = '".$mysqli->real_escape_string($_POST['number'])."',
client='".$mysqli->real_escape_string($_SESSION['clientid'])."'";
//execute the query
if( $mysqli->query($query) ) {
//if saving success
echo "true";
}else{
//if unable to create new record
printf("Errormessage: %s\n", $mysqli->error);
}
}
else{
$query = "UPDATE tele_panel_note SET
emailon = '".$mysqli->real_escape_string($_POST['emailon'])."',
texton = '".$mysqli->real_escape_string($_POST['texton'])."',
timezone = '".$mysqli->real_escape_string($_POST['timezone'])."',
timezone2 = '".$mysqli->real_escape_string($_POST['timezone2'])."',
email = '".$mysqli->real_escape_string($_POST['email'])."',
email_delay = '".$mysqli->real_escape_string($_POST['email_delay'])."',
text_delay = '".$mysqli->real_escape_string($_POST['text_delay'])."',
number = '".$mysqli->real_escape_string($_POST['number'])."'
where client='".$mysqli->real_escape_string($_SESSION['clientid'])."'";
//execute the query
if( $mysqli->query($query) ) {
//if saving success
echo "true";
}else{
//if unable to create new record
printf("Errormessage: %s\n", $mysqli->error);
}
}
//close database connection
$mysqli->close();
?>
Take a look at your PHP part,
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
$client = $row['client'];
if($client == ""){
You should verify directly with your row if you want to be able to know if the row already exists:
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
//$client = $row['client'];
if(!$row){
And then your client variable is useless.

Categories

Resources