Ajax- doesn't show message of validation during registration - ajax

What I am trying to do is to show a validation message when username or email exists while trying to register. I have used json_encode which has a message and status. What is happening is that when I type an username and email that exists it doesn't do anything neither shows a message or register.
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if($_POST["password"] !== $_POST["confirmation"])
{
echo json_encode(array('msg'=>"password and confirmation aren't equal.", 'url'=>"", 'status'=>false));
}
else if(($data['username']=== $_POST['username'] )|| ($data['email'] === $_POST['email'] ))
{
echo json_encode(array('msg'=>"Username or email exists.", 'url'=>"", 'status'=>false));
}
else
{
$result = query("INSERT INTO users (username, hash, email) VALUES (?,?,?)", $_POST["username"], crypt($_POST["password"]), $_POST["email"]);
$rows = query("SELECT LAST_INSERT_ID() AS id");
$id = $rows[0]["id"];
$_SESSION["id"] = $id;
echo json_encode(array('msg'=>"Success.", 'url'=>"/kinema/html/index.php", 'status'=>true));
}
}
scripts.js
$('#register_form').on('submit', function(e) {
e.preventDefault();
var name = $('#register_form input[name=username]').val();
var email = $('#register_form input[name=email]').val();
$.ajax({
url: "register.php",
type: "POST",
data: {
username: name,
email: email
},
dataType: 'json',
success: function(response) {
if(response.status){
console.log(response);
window.location = response.url;
}
else
{
$('#invalid_register').html(response.msg);
}
}
});
});

You are not posting a password or confirmation value this wil throw an undefined index error.
And for what I can tell the $data array does not exist or the code you posted is incomplete.

Related

Wordpress Ajax call returns empty

I have a trouble with wordpress ajax call.
Action for admin-ajax.php has been defined correctly.
It returns correct result when user logged in, but it returns empty when user didn't log in.
Here is code for it.
add_action('wp_ajax_thwepo_calculate_extra_cost', array($this, 'wp_ajax_action_calculate_extra_cost_handler'), 10);
add_action('wp_ajax_nopriv_thwepo_calculate_extra_cost', array($this, 'wp_ajax_action_calculate_extra_cost_handler'), 10);
public function wp_ajax_action_calculate_extra_cost_handler() {
$return = array(
'code' => 'E001',
'message' => ''
);
echo json_encode($return);
exit;
}
And here is javascript code.
var data = {
action: "thwepo_calculate_extra_cost",
price_info: JSON.stringify(requestData)
};
currRequest = $.ajax({
type: "POST",
url: args.ajax_url,
data: data,
beforeSend: function() {
null != currRequest && currRequest.abort()
},
success: function(rslt) {
if ("E000" === rslt.code) {
var result = rslt.result;
result && display_new_price(args, result.display_price, isVariableProduct)
} else "E002" === rslt.code && display_new_price(args, rslt.result, isVariableProduct)
},
error: function(data) {
console.log(data);
}
});
Here is screenshot of ajax call.
It returns correct result when page loaded first time.
But when select option (i.e. Classes), it returns empty.
Why is this happened?
Is there anyone who have any idea?
Please let me know if needed any other information.
Page url is https://www.ivybound.net/classes/isee-prep-middle-level/
It can be checked by selecting "What do you need?" select option.

ajax - request error with status code 200

From client side, I wanna send some data to server and receive some <div> tags which responding from View (another controller).
My ajax code looks like this:
var sortTopic = function () {
var $list = [],
$address = '',
$formData = new FormData();
/* do something here to set value to $list and $address */
$formData.append('Category', $list);
$formData.append('Address', $address);
$formData.append('Tags', '[KM]');
$formData.append('Skip', 0);
$.ajax({
url: '/Topic/Sort',
type: 'POST',
data: $formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (data) {
if (!data.success) {
$('.jumbotron').html(data.ex);
} else {
$('.jumbotron').html(data);
}
},
error: function (xhr) {
alert(xhr.status); //xhr.status: 200
}
});
};
In TopicController, action Sort was:
[AllowAnonymous]
[HttpPost]
public ActionResult Sort(SortTopicViewModel model)
{
try
{
if (model.IsValidSortTopicModel())
{
return PartialView("../Home/_Timeline", new TopicMaster().Sort(model));
}
return Json(new { success = false, ex = "Invalid model." });
}
catch (Exception e) { return Json(new { success = false, ex = e.Message }); }
}
I'm sure that the model is valid and method new TopicMaster().Sort(model) was working fine (because I had put breakpoint to view the return data). And the partial view _Timeline is a partial view of HomeController.
My problem is: I don't understand why I get error with status code 200 in ajax:
error: function (xhr) {
alert(xhr.status); //xhr.status: 200
}
Can you explain to me?
Thank you!
as you told you receive <div> in response that is not json and you mention dataType:"json" in your ajax just remove it. this will solve your problem. error 200 occur when you did not get valid response which is you mention in ajax.
for mor information you can read it documentation

refresh Page after logged in

in the index Page, the user needs to login..
after login,
<?php
include("dbinit.php");
$text="";
$eadd = $_POST['eadd'];
$pass = $_POST['pass'];
if (filter_var($eadd, FILTER_VALIDATE_EMAIL)) {
$result = mysqli_query($link,"SELECT * FROM account WHERE Eadd='".$eadd."'");
if (mysqli_num_rows($result)<=0){
$text = "<font color=red>Invalid Emailaddress and Password Combination!</font>";
}
else
{
while($row = mysqli_fetch_array($result)){
$passH = $row['Pass'];
$passS = $row['hash'];
}
if(md5($pass.$passS) == $passH){
$_SESSION['account'] = $eadd;
$text = "<font color=red>Login Successful!</font>";
}else{
$text = "<font color=red>Invalid Emailaddress and Password Combination!</font>";
}
}
mysqli_free_result($result);
} else {
$text = "<font color=red>Invalid Emailaddress!</font>";
}
mysqli_close($link);
echo $text;
?>
in the index Page,
function login(){
var eadd = $('#eadd').val();
var pass = $('#pass').val();
$.ajax({
type: "POST",
url: "login.php",
data: {eadd:eadd, pass:pass}
}).done(function( result ) {
$("#loginMsg").html(result);
});
}
how can i redirect or refresh the Page after he logged in?
after loggedin, the index page must refresh..
do i need to Put window.history.pushState("", "", '/newpage');?
how to use it?
window.top.location.reload();
Use that in your ajax success callback
To redirect instead to a differnt page use:
window.top.location = '/some/page/withcats';
Use:
function login(){
var eadd = $('#eadd').val();
var pass = $('#pass').val();
$.ajax({
type: "POST",
url: "login.php",
data: {eadd:eadd, pass:pass}
}).done(function( result ) {
$("#loginMsg").html(result);
//you may want to check result has no errors or something
window.top.location.reload();
});
}
Error handling:
You might want to check for an error, so that if the login is unsuccessful you do not want to refresh the page. To do that relies on knowing what you php function will return E.g.:
function login(){
var eadd = $('#eadd').val();
var pass = $('#pass').val();
$.ajax({
type: "POST",
url: "login.php",
data: {eadd:eadd, pass:pass}
}).done(function( result ) {
//this will make sure the page only refreshes if login is succesful, if not display error
if(result === "<font color=red>Login Successful!</font>"){
window.top.location.reload();
}else{
$("#loginMsg").html(result);
}
});
}
how can i redirect or refresh the Page after he logged in?
by using a regular form submission instead of Ajax.

Ajax simple login

I have this simple Ajax code, my question is only, what does data.logged return, and what i need to have in the logged.php file...
I'm new to ajax, sorry for the dumb question...
$.ajax('logged.php', {
data: {
login: login,
pass: pass
},
success: function(data)
{
if (data.logged)
{
setTimeout(function() {
document.location.href = 'index.php'
}, 2000);
}
else
{
setTimeout(function() {
formLogin.clearMessages();
displayError('Utilizador ou password errados');
}, 2000);
}
},
error: function()
{
formLogin.clearMessages();
displayError('Error while contacting server, please try again');
}
});
On the client side, adding dataType : 'json' worked for me.
$.ajax('handler.php', {
data: {
login: login,
pass: pass
},
dataType : 'json',
success: function(data)
{
//code here
}
//more code here
}
And then on the server side:
$user = $_GET['login'];
$pass = $_GET['pass'];
$result = array();
if( /* login logic here */) {
$result['logged'] = 'true';
} else {
$result['logged'] = false;
}
header('Content-type: application/json');
echo json_encode($result);
That's a jQuery AJAX request which will be expecting responseText in JSON format. In this case, it seems like the JSON returned by your PHP file only needs to have a single property logged which will be either true or false depending on whether or not the login was successful.

JQuery Validation Plugin: Use Custom Ajax Method

Looking for some assistance with the Jquery form validation plugin if possible.
I am validating the email field of my form on blur by making an ajax call to my database, which checks if the text in the email field is currently in the database.
// Check email validity on Blur
$('#sEmail').blur(function(){
// Grab Email From Form
var itemValue = $('#sEmail').val();
// Serialise data for ajax processing
var emailData = {
sEmail: itemValue
}
// Do Ajax Call
$.getJSON('http://localhost:8501/ems/trunk/www/cfcs/admin_user_service.cfc?method=getAdminUserEmail&returnFormat=json&queryformat=column', emailData, function(data){
if (data != false) {
var errorMessage = 'This email address has already been registered';
}
else {
var errorMessage = 'Good'
}
})
});
What I would like to do, is encorporate this call into the rules of my JQuery Validation Plugin...e.g
$("#setAdminUser").validate({
rules:{
sEmail: {
required: function(){
// Replicate my on blur ajax email call here
}
},
messages:{
sEmail: {
required: "this email already exists"
}
});
Wondering if there is anyway of achieving this? Many thanks
You are doing an AJAX request, ergo: the validation is already finished working when your custom validator returns either true or false.
You will need to work with async. See also this post: How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
Lets say we have a custom validation to check the Unique Mobile, So we will add a new method as follows to check the unqiue Mobile no :
jQuery.validator.addMethod("uniqueMobile", function(value, element) {
var response;
$.ajax({
type: "POST",
url: <YOUR SERVER SCRIPT/METHOD>,
data:"mobile="+value,
async:false,
success:function(data){
response = data;
}
});
if(response == 0)
{
return true;
}
else if(response == 1)
{
return false;
}
else if(response == 'logout')
{
return false;
}
}, "Mobile is Already Taken");
You can add a custom validation method like this
$.validator.addMethod('unique',
function(value) {
$.get('http://localhost:8501/ems/trunk/www/cfcs/admin_user_service.cfc','?method=getAdminUserEmail&returnFormat=json&queryformat=column&emailData='+ value,
function(return_data) {
return return_data;
})
}
, "this email already exists"
);
then add the unique class to your email field or you can use something like this
$.validator.addClassRules("unique-email", {
unique: true
});
Try this:
$.validator.addMethod('unique',
function(value) {
var result = $.ajax({
async:false,
url:"http://yoursamedomain.com/checkemail",
data:'email='+ value,
dataType:"text" });
if(result .responseText) return true; else return false;
} , "This email address has already been registered");
For serverside AJAX validation use remote rule. This is same as standard jQuery AJAX request object. Your server must returns string "true" for valid value or "false" for invalid, also it can passes some string "This email was already taken", and this will be perceived as invalid, and render as an error message:
$( "#myform" ).validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
username: function() {
return $( "#username" ).val();
}
}
}
}
}
});
Read documentation here remote-method

Resources