My problem is that I have two messages:
error message
success message
Here with the help of jQuery, I fetch the email field value and want to check whether email exits in the database or not.
If exits then show success message, otherwise show error message.
$('#email').blur(function(){
var err_msg_css={"background-color":"#FDE4E1","border":"1px solid #FBD3C6","border-radius":"10px 4px 4px 10px","color":"#CB4721","font-size": "14px","float":"left","font-family":"Arial, Helvetica, sans-serif","font-size":"small","font-style":"oblique","height":"22px","margin-left":"6px","padding":"3px","width":"196px"};
var sucess_msg_css={"background-color":"#D5FFC6","border":"1px solid #C0F0B9","border-radius":"10px 4px 4px 10px","color":"#48A41C","font-size": "14px","float":"left","font-family":"Arial, Helvetica, sans-serif","font-size":"small","font-style":"oblique","height":"22px","margin-left":"6px","padding":"3px","width":"196px"};
var text = /[a-z]$/;
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
var email=$('#email').val();
if(!$('#email').val()){
$('#err_msg_9').html('<img src="css/images/error.jpg">email field is empty').css(err_msg_css).show();
return false;
}else{
if(!pattern.test(email)){
//console.log('qwerty')
$('#err_msg_9').html('<img src="css/images/error.jpg">email is not valid').css(err_msg_css).show();
return false;
}else{
var Email=$("#email").val();
var datatype = 'email='+ Email;
$.ajax
({
type: "POST",
url: "ajax_centre.php",
data: datatype,
cache: false,
success: function(html)
{
$("#err_msg_9").html(html);
}
});
//$('#err_msg_9').html('<img src="css/images/success.jpg">sucessful').css(sucess_msg_css).show();
//
return false;
}
}
//$('#err_msg_1').hide();
return true;
});
PHP
if($_POST['email'])
{
$email=$_POST['email'];
$counter=0;
$sql=mysql_query("SELECT `email` FROM `form_value` WHERE `email`='$email'");
while($row = mysql_fetch_array($sql)){
if($email == $row['email']){
$counter = 1;
//echo "email is already in use";
}else{
//echo "email is unique";
}
}
}
//error message
$('#err_msg_9').html('<img src="css/images/error.jpg">email is not valid').css(err_msg_css).show();
//success message
$('#err_msg_8').html('<img src="css/images/success.jpg">sucessful').css(sucess_msg_css).show();
JSON is useful for this time.
Client code:
$.ajax
({
type: "POST",
url: "ajax_centre.php",
data: datatype,
cache: false,
success: function(html)
{
try{
json = $.parseJSON(html);
}catch(e){}
if( typeof json !== 'object' ){
alert(html);
return false;
}
if( ! json.success ){
var html = '<img src="css/images/error.jpg">' + json.message;
$("#err_msg_9").html(html).css(err_msg_css).show();
}else{
var html = '<img src="css/images/success.jpg">' + json.message;
$("#err_msg_8").html(html).css(sucess_msg_css).show();
}
}
});
Server Code:
$row = mysql_fetch_array($sql);
$response = array();
if( !empty($row) && $email === $row['email']){
$counter = 1;
$response['success'] = false;
$response['message'] = "email is already in use";
}else{
$response['success'] = true;
$response['message'] = "email is unique";
}
echo json_encode($response);
Related
i want to validate login form using ajax success response is working but if all goods it should be redirect to index page but it's not working , i don't understand what's wrong please help. thanks in advance..
$(document).ready(function(){
var response;
$('#submit').click(function(e){
e.preventDefault();
$('.alert-box').html('<div id="loading" style="margin: 0 auto;" >
</div>');
var action = 'ajax_validation';
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url:"do_login.php",
method:"POST",
data:{action:action, username:username, password:password},
success:function(data){
response = data;
if(response === 1){
window.location.href = "http://stackoverflow.com";
}else{
$('.alert-box').addClass("alert alert-warning");
$('.alert-box').html(response);
}
}
});
});
});
above these ajax request
this is action page code
include('includes/db.php');
if(isset($_POST["action"])){
$check_username = $_POST['username'];
$check_password = $_POST['password'];
if(empty($check_username) && empty($check_password)){
echo "Please fill all field";
}else{
$query = "SELECT * FROM user WHERE email = '{$check_username}' AND password = '{$check_password}' ";
$select_query=mysqli_query($connection,$query);
if(!$select_query){
die("QUERY FAILED".mysqli_error($select_query));
}
if(mysqli_num_rows($select_query)==0){
echo "Username or password are incorrect!";
}else{
while ($row=mysqli_fetch_assoc($select_query)) {
$_SESSION['username'] = $row['email'];
echo $row['email'];
}
}
}
}
In your resposne you are echoing
echo $row['email'];
This should be:
echo 1;
Your problem is that you are checking if value is 1 in ajax:
success:function(data){
response = data;
if(response === 1){ //<- there you are checking if your echo is 1 but you are trying to echo $row['email'];
window.location.href = "http://stackoverflow.com";
}else{
$('.alert-box').addClass("alert alert-warning");
$('.alert-box').html(response);
}
}
change your echo from $row['email'] to 1
I think that the problem is response checking condition in ajax success.
You're checking if a string (email or error message) is equal and the same type of 1.
...
dataType: 'json',
success:function(data){
response = data;
if(response === 1){
...
You can use a json response with status/error code:
...
success:function(data){
response = JSON.parse(data);
if(response.status === 1){
window.location.href = "http://stackoverflow.com";
}else{
$('.alert-box').addClass("alert alert-warning");
$('.alert-box').html(response.data);
}
}
...
$check_username = $_POST['username'];
$check_password = $_POST['password'];
$res = array('status'=> 0, 'data' => '');
if(empty($check_username) && empty($check_password)){
$res['status'] = 0;
$res['data'] = "Please fill all field";
}else{
$query = "SELECT * FROM user WHERE email = '{$check_username}' AND password = '{$check_password}' ";
$select_query=mysqli_query($connection,$query);
if(!$select_query){
$res['status'] = 0;
$res['data'] = "QUERY FAILED".mysqli_error($select_query);
echo json_encode($res);
return;
}
if(mysqli_num_rows($select_query)==0){
$res['status'] = 0;
$res['data'] = "Username or password are incorrect!";
}else{
while ($row=mysqli_fetch_assoc($select_query)) {
$_SESSION['username'] = $row['email'];
$res['status'] = 1;
$res['data'] = "".$row['email'];
}
}
}
echo json_encode($res);
In addition i suggest to put only the username in query where condition and check if the password match with php.
I don't really understand why this does not work - I have read a whole lot about this specific problem, but I must be missing something.
I want to alert the "echo" from the PHP - which it doesn't.
AJAX:
$("#SaveChangesEmail").click(function() {
var newemail = $("#mynewemail").val();
$.ajax({
type: "POST",
url: "checkemail.php",
data: {newemail:newemail},
datatype: "json",
success: function(data){
alert(data);
}
});
});
PHP (checkemail.php)
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if($email == $row['myemail']){
echo "This is your current email";
}
else if($email != $row['myemail']){
$results = $con->query("
UPDATE members SET
myemail='".$email."'
WHERE m_id = '".$m_id."'") or die(mysqli_error($con));
echo "Your email is changed";
}
} else {
echo "Please provide a correct email";
}
The database is updating, do the script itself runs perfectly, but after the "success" - it doesn't alert anything.
UPDATE
I have now tried this:
AJAX:
$("#SaveChangesEmail").click(function() {
var newemail = $("#mynewemail").val();
$.ajax({
type: "POST",
url: "checkemail.php",
data: {newemail:newemail},
datatype: "text",
success: function(data){
if(data == 1) {
alert("This is your current email");
}
else if(data == 2) {
alert("Your email is changed");
}
else if(data == 3) {
alert("Please provide a correct email");
}
}
});
});
PHP (checkemail.php)
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if($email == $row['myemail']){
echo "1";
}
else if($email != $row['myemail']){
$results = $con->query("
UPDATE members SET
myemail='".$email."'
WHERE m_id = '".$m_id."'") or die(mysqli_error($con));
echo "2";
}
} else {
echo "3";
}
The console is returning the raw data (1,2,3) but the alert is still not showing!
After send my form data to php file its return if any error found. But its also return success before ajax redirect page. I want display error message only and if success, redirect another page.
ajax:
$("#msform").submit(function(){
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
dataType : 'json',
success: function(data){
if ( ! data.success) {
$(".help-block").fadeIn().html(data.error);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});
php:
include_once ("db.php");
global $dbh;
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
$error ="* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
$error ="* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
$error ="* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}
$data = array();
$data['error'] = $error;
$data['success'] = $success;
if (!empty($data)) {
echo json_encode($data);
}
Solved the problem, in this way:
Ajax:
$("#msform").submit(function(){
// collect input name
ver name = var catag=$('#name').val();
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
success: function(data){
if ( data != 'success') {
$(".help-block").fadeIn().html(data);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + name;
}
}
});
});
php:
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
echo "* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
echo "* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
echo "* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
echo 'success';
}
EDIT
Set your variables $success and $error
$success = "";
$error= "";
If you doesn't init them, you cannot use them and the .=operator is for concatenation not for set.
Then you should encode the response in php in JSON.
Something like
$response = json_encode(
array(
'success'=> true,
'route' => "mypage/info?user=$_SESSION['username']"
)
);
And return this, then access your response like you already do :
var success = response.success;
UPDATE
change this code to add an else statement :
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}else{
$success = 'error';
}
and this line :
else {
return 1;
}
to :
else {
$error = 'none';
}
and in your javascript :
$("#msform").submit(function(){
$.ajax({
type :"post",
url :"pagesubmit.php",
data : $("#msform").serialize(),
dataType : 'json',
success : function(data){
if(data.success == 'error') {
$(".help-block").fadeIn().html(data.error);
}else{
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});
After submitting a form with ajax the returned result appears on a new page. The chrome console returns me an error in almost every element: it is not a function validates, but php insert them and shows the result displayed in this new page.
$(document).ready(function () {
$('#newsletter').submit(function(e){
var $this = $(this);
e.preventDefault();
$response = $('#response'),
$mail = $('#email'),
testmail = /^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/,
hasError = false;
$response.find('p').remove();
if (!testmail.test($mail.val())) {
$response.html('<p class="error">Please enter a valid email</p>');
hasError = true;
}
if (hasError === false) {
$response.find('p').remove();
$response.addClass('loading');
$.ajax({
type: "POST",
dataType: 'json',
cache: false,
url: $this.attr('action'),
data: $this.serialize()
}).done(function (data) {
console.log(data);
$response.removeClass('loading');
$response.html('<p>'+data.message+'</p>');
}).fail(function() {
$response.removeClass('loading');
$response.html('<p>An error occurred, please try again</p>');
})
}
return false;
});
});
php code
<?php
$host = "";
$dbname = "";
$user = "";
$pass = "";
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$datetime = date('Y-m-d H:i:s');
try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
if (empty($email)) {
$status = "error";
$message = "The email address field must not be blank";
} else if (!preg_match('/^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/', $email)) {
$status = "error";
$message = "You must fill the field with a valid email address";
} else {
$existingSignup = $db->prepare("SELECT COUNT(*) FROM signups WHERE signup_email_address='$email'");
$existingSignup->execute();
$data_exists = ($existingSignup->fetchColumn() > 0) ? true : false;
if (!$data_exists) {
$sql = "INSERT INTO signups (signup_email_address, signup_date) VALUES (:email, :datetime)";
$q = $db->prepare($sql);
$q->execute(
array(
':email' => $email,
':datetime' => $datetime
));
if ($q) {
$status = "success";
$message = "You have been successfully subscribed";
} else {
$status = "error";
$message = "An error occurred, please try again";
}
} else {
$status = "error";
$message = "This email is already subscribed";
}
}
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
$db = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
The error displayed: undefinied is not a function in
$response = $('#response'),
$mail = $('#email'),
var $this = $(this);
Message displayed in blank page:
{"status":"success","message":"You have been successfully subscribed"}
Solved. Now works fine in another way, but I would like to know the mistake.
This works
(function ($, window, document, undefined) {
'use strict';
var $form = $('#newsletter');
var $response = $('#response');
$form.submit(function (e) {
var formData = {
'news' : $('input[name="news"]').val(),
'email' : $('input[name="email"]').val(),
};
$.ajax({
type : 'POST',
url : 'news.php',
data : formData,
dataType : 'json',
encode : true
}).done(function (data) {
if (!data.success) {
$('#response').html(data);
$response.html('<div class="alert alert"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
} else {
$('#response').html(data);
$response.html('<div class="alert alert"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
}
}).fail(function (data) {
response.html('<div class="alert alert-error"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
// for debug
console.log(data)
});
e.preventDefault();
});
}(jQuery, window, document));
i want to make login form with session (with PHP + ajax), i send username from controller with json but it doesn't work. i don't know whats wrong, please help
this is the function in controller :
public function actionLogin()
{
$username = isset($_POST['username'])?$_POST['username']:null;
$password = isset($_POST['password'])?sha1($_POST['password']):null;
$json = new JsonHelper();
$result = array();
if($username && $password !=''){
$checkLogin = Administrator::model()->findByAttributes(
array('username'=>$username, 'password'=>$password));
$checkUser = Administrator::model()->findByAttributes(
array('username'=>$username));
$checkPass = Administrator::model()->findByAttributes(
array('password'=>$password));
$login = count($checkLogin);
$user = count($checkUser);
$pass= count($checkPass);
if($login==1)
{
$result['status'] = 'success';
$result['username'] = $username;
$json->addData('ajax', $result);
}
elseif($user == 1 && $pass == 0)
{
$result['status'] = 'wrongPass';
$json->addData('ajax', $result);
}
elseif($user == 0 && $pass == 1)
{
$result['status'] = 'wrongUser';
$json->addData('ajax', $result);
}
}
echo json_encode($json->getJson());
}
and this is the form_login.js file :
function login(){
var form = $('#login-form');
var formId = form.attr('id');
var action = form.attr('data-action');
var method = form.attr('data-method');
var formData = serializer(form); //don't mind this function
$.ajax(
{
url: action,
cache: false,
processData: false,
contentType: false,
type: method,
data: formData,
success: function(json)
{
// AJAX SUCCESS
var json = JSON.parse(result);
if(json['result']['ajax']['status']=='success')
{
//$_SESSION['username'] =json['username'];
window.location = baseUrl + "/appsterize/dashboard/index";
}
else if(json['result']['ajax']['status']=='wrongPass')
{
// Password wrong
alert("The password you entered is incorrect.");
}
else if(json['result']['ajax']['status']=='wrongUser')
{
// Username isn't exist
alert("Username isn't exist");
}
},
error: function(xhr, status, error)
{
// AJAX ERROR
var string = "<strong>Error!</strong> " + xhr['responseText'];
$(alertError).attr('data-text', string);
$(alertError).click();
},
});
}
some error is 'Uncaught ReferenceError: alertError is not defined'
Have an element with id = 'alertError'?
Could this be the solution:
$("#alertError").attr('data-text', string);
...
Basically, what #serakfalcon said above:
...
error: function(xhr, status, error)
{
// AJAX ERROR
var errorMsg = "<strong>Error!</strong> " + xhr['responseText'];
alert(errorMsg);
},
...