php validation using jquery and ajax - php

i have a jquery ajax form.
i have validation at server side for repeated username and email ID.
which works fine without jquery/ajax.
in my php code i have used die() to return if any error occurs. my main problem is at ajax
here is the code
$(document).ready(function () {
$("form#regist").submit(function () {
var str = $("#regist").serialize();
$.ajax({
type: "POST",
url: "submit1.php",
data: $("#regist").serialize(),
success: function () {
$("#loading").append("<h2>you are here</h2>");
}
});
return false;
});
});
The success function works properly. if my data is valid then it is added in the db, if my data is repeated then it is not added in the db. Now what i want to know is how do i return the error from my php file and use it at success event. Thanks in advance..
edit : this is how my php script looks
$query = "SELECT username from userdetails WHERE username = '$username'";
$q = mysql_query($query) or die("error" . mysql_error());
$numrows = mysql_num_rows($q);
if($numrows > 0)
{
die("username already exixt");
//should i put something like this
//$error = "username already exists";
//return $error; --->> i am not sure about this..
}
thanks in advance

Php side:
if($numrows > 0)
{
echo "username already exist";
}
Javascript side:
success: function(msg)
{
if(msg == 'username already exist') alert(msg);
}
But this is so crude, If you plan to develop this further try to read some articles on JSON, so you can use json to communicate to server side. And also you should try to use some default error controlling, like return an array with php:
echo json_encode(array('error' => true, 'notice' => 'username exists'));
Then on the javascript side (jquery), use json ajax request and always check if error variable is true or not, if it is maybe you can use a default function for error controlling.
Hope this helped.

In the function definition which you have done like:
success: function(){
introduce a parameter like: success: function(retVal){
Now in the function you can check for the value of retVal.
Say, you return from your PHP script, "successful" for success case and "this email exists" for failure.
Now you can directly compare this here and do whatever you want to, like:
if(retVal == 'this email exists')
{
window.alert('please re-enter the email, this record exists!');
}
and so on...
Hope this helps.

$(document).ready(function () {
$("form#regist").submit(function () {
var str = $("#regist").serialize();
$.ajax({
type: "POST",
url: "submit1.php",
data: $("#regist").serialize(),
success: function (msg) {
alert(msg);
}
});
return false;
});
});
Here from server side send the message and show it, how i have shown it :)

Related

Ajax post does not give value to php file, post becomes get

I have this ajax function for login.
Edit: I just noticed that this server runs php7 while other server where the login does work uses php5. What has changed in php that this script doesn't work anymore?
Edit 2: Looks like the server request method isn't post but changed to get, why?
Solution: needed to remove the .php from url: "./ajaxcall/login.php", because I use pretty url htaccess.😅
var InName = $('#InName').val();
var InPass = $('#InPass').val();
alert(InName);
$.ajax({
type: "POST",
url: "./ajaxcall/login.php",
dataType: "json",
data: {InName:InName, InPass:InPass},
error: function (request, error) {
console.log(arguments);
alert("Inlog Can't do because: " + error);
},
success : function(data){
if (data.code == "200"){
$("#InErEr").html(data.msg);
//window.location.reload(true);
} else {
$("#InErEr").html(data.msg);
$('.lds-dual-ring').animate({opacity: 0}, 300);
}
}
});
On the alert(InName); I get the correct value of the username. But when I check in my php file $_POST['InName'] it is empty.
Part of php file
include('../config.php');
if(empty($_POST['InName'])) {
$Ierror = 'Username is required.';
}
if($_POST['InPass'] == '') {
$Ierror = 'Password is required.';
}
$username = $_POST['InName'];
$passwordL = $_POST['InPass'];
// count user in between //
if($Inlognumber_of_rows == 0) {
$Ierror = 'Username not found.';
} else {
// password check //
if(password_verify($salty_pass, $hashed_password)) {
} else {
$Ierror = 'Password incorrect.';
}
}
if ($Ierror == '') {
// do login //
} else {
$showerror = '<span style="color:#F00;">'.$Ierror.$username.$passwordL.$_POST['InName'].$_POST['InPass'].'</span>';
echo json_encode(['code'=>404, 'msg'=>$showerror]);
exit;
}
In the return message, $showerror I only get, Username not found, without the posted values. So the login is not working because of empty values? User is also present in the database of course. I also don't get the empty $_POST errors. So to cap up, in javascript I get the correct value for InName but not in php.
You are close but your error catch is not correct ... try this (Jquery):
var InName = 'something';
var InPass = 'morething';
$.post("./ajaxcall/login.php", {
InName: InName,
InPass: InPass
}, function(data, status) {
console.log(data, status);
}).done(function() {
alert("second success");
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});
on your php file just do print_r($_POST); and you will receive this in your console...:
Array
(
[InName] => something
[InPass] => morething
)
success
Basically you were trying to print the error where you should have consoled log the request.responeText...
A good trick to know if posts arrived to the php even if the console.log won't show is doing this in the php file:
<?php
print_r($_POST) ;
$newfile = fopen('newfile.txt','a');
fwrite($newfile,json_encode($_POST));
fclose($newfile);
This will print and also store on a local file the post data....
Solution: needed to remove the .php from url: "./ajaxcall/login.php", because I use pretty url htaccess.😅

How to send data from one page to another and upon success show a modal

This is my page from where I want to send data to dashboard/fpass.php page and upon success show a modal.
<script>
$(document).ready(function () {
$('#fmodal').click(function () {
$.ajax({
type: "POST",
url: "dashboard/fpass.php",
data: { name: "fpass" }
})
success: function(data) {
$("#myModal").modal();
}
});
});
</script>
And here is my next page where I want to get my data and send a mail.
<?php
if(($_POST['name'])=='fpass')
{
/*add sql connection*/
require('../includes/dbconfig.php');
/*get the image file name from the table*/
$sql="select * from admin";
$res=mysqli_query($con,$sql);
$row=mysqli_fetch_array($res);
$email=$row['email'];
$password=$row['password'];
$bemail=$row['bemail'];
$sub="dashboard login password is < ".$password." >";
/*send mail to the sql entry*/
mail($email,"Forget Password Request",$sub,$bemail);
}
?>
Try changing your AJAX:
<script>
$(document).ready(function(){
$('#fmodal').click(function(){
var name = 'fpass';
$.ajax({
type: "POST",
url: "dashboard/fpass.php",
data: { name: name },
success: function(data) {
$("#myModal").modal('show');
}
});
});
});
</script>
Man, the problem that I see is in the receiving code. AJAX needs to get some response from that file, you are not sending anything back, that's why. When you execute the mail() function, if CORRECT, then return true, 1 or any message that you want referring to the successful operation.
Try this:
if (mail($email,"Forget Password Request",$sub,$bemail))
echo true; //or echo 1, something referring to successful execution
else {
/**
* If you want to use the error{} part of the AJAX, you need to send different headers
* header('HTTP/1.1 500 Internal Server Error');
*/
// And then the echo, or just the echo is fine if you want to use it in the success section
echo false; // or echo 0, somtehing referring to a failed execution
}
In the AJAX side, you get the response, and evaluate if is true or false and then you decide what to do.
Hope that can help. J.C!
Your JS code is not valid. Have a look here, to see how $.ajax(...) is used:

check username exists using ajax

I use this code to check username exists in database before or not. code works good and shows available or taken username. now i want to submit button should be disable when user select username that was taken befor and enable when username available . please guide me how.
$(document).ready(function() {
$('#username').keyup(function() {
$.post('adm/chk_uname_avail.php', {
uname : changeuser.username.value
}, function(result){
$('#available').html(result);
})
})
})
I'm using the old $.ajax function and make sure you have a data keyed taken (as example) with boolean type on adm/chk_uname_avail.php and notice that you should return JSON data type from it.
Example of adm/chk_uname_avail.php
<?php
//return response as JSON
header('Content-type:application/json;charset=utf-8');
....
....
....
$data['taken'] = true; //show this response to ajax
echo json_encode($data);
?>
Ajax
$(document).ready(function() {
$('#username').on('keyup', function() {
$.ajax({
type: 'POST',
url: 'adm/chk_uname_avail.php',
data: {uname : changeuser.username.value},
success: function(result) {
var $btn = $('#submiButton');
if (result.taken) {
$btn.prop('disabled', true);
} else {
$btn.prop('disabled', false);
}
//As #Mikey notice, You can just use this as simply as
//$('#submiButton').prop('disabled', result.taken);
}
});
});
});
Use .attr() method of jQuery to make the submit disabled on certain condition.
So you can update your jQuery like this,
$.post('adm/chk_uname_avail.php', {
uname : changeuser.username.value
}, function(result){
$('#available').html(result);
if(/* CHECK FOR CERTAIN CONDITION */) {
$('#submit_btn').attr('disabled','disabled');
}
});
To remove the disabled attribute you can use removeAttr() method of jQuery. Like this,
$('#submit_btn').removeAttr('disabled');
http://api.jquery.com/attr/
https://api.jquery.com/removeAttr/

jQuery JSON PHP Request

I've been trying to figure out what I have done wrong but when I use my JavaScript Console it shows me this error : Cannot read property 'success' of null.
JavaScript
<script>
$(document).ready(function() {
$("#submitBtn").click(function() {
loginToWebsite();
})
});
</script>
<script type="text/javascript">
function loginToWebsite(){
var username = $("username").serialize();
var password = $("password").serialize();
$.ajax({
type: 'POST', url: 'secure/check_login.php', dataType: "json", data: { username: username, password: password, },
datatype:"json",
success: function(result) {
if (result.success != true){
alert("ERROR");
}
else
{
alert("SUCCESS");
}
}
});
}
</script>
PHP
$session_id = rand();
loginCheck($username,$password);
function loginCheck($username,$password)
{
$password = encryptPassword($password);
if (getUser($username,$password) == 1)
{
refreshUID($session_id);
$data = array("success" => true);
echo json_encode($data);
}
else
{
$data = array("success" => false);
echo json_encode($data);
}
}
function refreshUID($session_id)
{
#Update User Session To Database
session_start($session_id);
}
function encryptPassword($password)
{
$password = $encyPass = md5($password);
return $password;
}
function getUser($username,$password)
{
$sql="SELECT * FROM webManager WHERE username='".$username."' and password='".$password."'";
$result= mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result) or die(mysql_error());
if ($count = 1)
{
return 1;
}
else
{
return 0;;
}
}
?>
I'm attempting to create a login form which will provide the user with information telling him if his username and password are correct or not.
There are several critical syntax problems in your code causing invalid data to be sent to server. This means your php may not be responding with JSON if the empty fields cause problems in your php functions.
No data returned would mean result.success doesn't exist...which is likely the error you see.
First the selectors: $("username") & $("password") are invalid so your data params will be undefined. Assuming these are element ID's you are missing # prefix. EDIT: turns out these are not the ID's but selectors are invalid regardless
You don't want to use serialize() if you are creating a data object to have jQuery parse into formData. Use one or the other.
to make it simple try using var username = $("#inputUsername").val(). You can fix ID for password field accordingly
dataType is in your options object twice, one with a typo. Remove datatype:"json", which is not camelCase
Learn how to inspect an AJAX request in your browser console. You would have realized that the data params had no values in very short time. At that point a little debugging in console would have lead you to some immediate points to troubleshoot.
Also inspecting request you would likely see no json was returned
EDIT: Also seems you will need to do some validation in your php as input data is obviously causing a failure to return any response data
Try to add this in back-end process:
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/json');
header('Content-type: text/json');
hope this help !
i testet on your page. You have other problems. Your postvaribales in your ajax call are missing, because your selectors are wrong!
You are trying to select the input's name attribute via ID selector. The ID of your input['name'] is "inputUsername"
So you have to select it this way
$('#inputUsername').val();
// or
$('input[name="username"]').val();
I tried it again. You PHP script is responsing nothing. Just a 200.
$.ajax({
type: 'POST',
url: 'secure/check_login.php',
dataType: "json",
data: 'username='+$("#inputUsername").val()+'&password='+$("#inputPassword").val(),
success: function(result) {
if (result.success != true){
alert("ERROR");
} else {
alert("HEHEHE");
}
}
});
Try to add following code on the top of your PHP script.
header("Content-type: appliation/json");
echo '{"success":true}';
exit;
You need to convert the string returned by the PHP script, (see this question) for this you need to use the $.parseJSON() (see more in the jQuery API).

jQuery.ajax / CodeIgniter (PHP) : Returning TRUE/FALSE in PHP, how can I get jQuery to see this?

I've built a function for checking a username. I'm using it as a callback for form validation in CodeIgniter, and it works nicely. However, I'd like to also use it with AJAX to check on the fly if the user has JS enabled. So my controller has this:
function check_username($s = FALSE)
{
if ($s):
$this->db_common->like('username', $s);
$query = $this->db_common->get('users');
if ($query->num_rows() > 0):
$this->form_validation->set_message('check_username', 'Username taken. Choose another!');
return FALSE;
else:
return TRUE;
endif;
else:
echo 'Username required';
endif;
}
And my HTML/JS is this:
$(document).ready(function()
{
var delayed;
$("#username").keyup(function()
{
clearTimeout(delayed);
var value = this.value;
if (value)
{
delayed = setTimeout(function() {
$.ajax
({
type: "POST",
url: "<?php echo base_url(); ?>auth/check_username/",
data: $("#username").val(),
success: function(html)
{
$("#username_check").html(html);
}
});
}, 100);
}
});
});
Basically, I'm returning FALSE if the username exists and TRUE if it does exist. How do I get my jQuery AJAX to see that? Basically, I want jQuery to check if it's false, then say 'username exists' and if it's true, then 'username is okay'.
Do something like the following:
echo 'ok';
return TRUE;
The reason for this is that jQuery can't see the boolean values returned by PHP as they're not send to the browser's output.
Basically, I'm returning FALSE if the username exists and TRUE if it does exist. How do I get my jQuery AJAX to see that?
You can't directly. I would output 0 or 1 instead.
I would return true or false as JSON boolean from your PHP script and use javascript's eval() function to evaluate that to a javascript var.
There is a way to do it with PHP and jQuery. Here is an example...
simply have your php script echo back true or false.
PHP-> echo true; or echo false;
$.post("your_url/your_class/your_method", { } ,
function(data) {
if(data) alert('true');
else alert('false');
}, "json")
.error(function() { //alert("an AJAX error occurred!");
});

Categories