I have got some error ajax - php

I have an error where I can't proceed my login_process.php using ajax. I have stored all my files as a one folder. If I run my HTML log in page, the error is appeared. Below is my code. It is just a simple code. Before this, I have applied the similar code as below (except for login_process.php because I've put a few functions) as my homework. But when I've try to make it again, as i said, the browser, either in Chrome or Firefox, displays an error as I wrote in ajax below.
index.html(ajax part)
$(document).ready(function(){
$("#subBTN").click(function(){
var username = $("#username").val();
var password = $("#password").val();
var status = $("#statusAlert");
if(username === "" && password === ""){
status.html("<span>Username and password are both required!</span>");
}
else if(username === ""){
status.html("<span>What is your username?</span>");
}
else if(password === ""){
status.html("<span>What is your password?</span>");
}
else{
$.ajax({
url:'login_process.php',
type: 'post',
data: {"?admin_name=": username, "&admin_pass=": password},
dataType: 'html',
success: function(data){
//alert(data);
if(data.success){
status.html("<span>"+ data +"</span>");
}
else{
status.html("<span>error</span>");
return false;
}
}
});
}
});
});
login_process.php
<?php
session_start();
if($_POST):
$username = $_POST["username"];
$password = $_POST["password"];
if($username):
echo "Hi " . $username;
endif;
endif;
?>

You got a error in jQuery ajax call in passing data
You use :
data: {'admin_name':username, 'admin_pass': password},
instead of
data: {"?admin_name=": username, "&admin_pass=": password},
Or access in php code data to use:
$_POST['admin_name'] AND S_POST['admin_pass']

You should change this line of code
if(data.success){
status.html("<span>"+ data +"</span>");
}
else{
status.html("<span>error</span>");
return false;
}
To
if(data.Length > 0){
status.html("<span>"+ data +"</span>");
}
else{
status.html("<span>error</span>");
return false;
}

Related

Prevent Ajax from catching Link from a php header

I'am using ajax to receive result from validating Username and password from another PHP script, in that script i'am using header("location:...."); to redirect to the admin page, but ajax catch the link and showing it in the main Login form. Any ideas :).
PHP
<?php
...
...
if ( $username && $password )
{
$data['response'] = 'valid';
else
{
$data['response'] = 'invalid';
}
echo json_encode($response);
AJAX
$.ajax({
type: 'POST',
url: 'url',
data: {username : username, password: password},
success: function(response){
if(response.response === valid){
window.location.replace('admin-page');
}else{
//error
}
}
});

no response ajax request

I am trying to make a simple login with ajax. The problem i have is that i do not get any response from my request. When I try to use
myurl.com/login.php is_ajax=1&username=test&password=test
I get a succes message back.
$(document).ready(function(){
$("#submit").click(function(){
var form_data = {
usernm: $("#username").val(),
passwd: $("#password").val(),
is_ajax: 1
};
$.ajax({
type:"POST",
url: "myurl.php" ,
data: form_data,
succes: function (response)
{
if (response == 'succes'){
window.location="myurl.html";
}
else{
alert("wrong username password combination")
}
}
});
return false;
});
});
my php:
$is_ajax = $_REQUEST['is_ajax'];
if(isset($is_ajax) && $is_ajax)
{
$uName = $_REQUEST ['username'];
$pWord = $_REQUEST ['password'];
if($uName == 'test' && $pWord == 'test'){
echo 'succes';
}
else{
echo 'false';
}
}
you should use
$uName = $_REQUEST ['usernm'];
$pWord = $_REQUEST ['passwd'];
INSTEAD of
$uName = $_REQUEST ['username'];
$pWord = $_REQUEST ['password'];
in your php file and change succes to success
Replace succes with success
$.ajax({
type:"POST",
url: "myurl.php" ,
data: form_data,
success: function (response){
if (response == 'success'){
window.location="myurl.html";
}else{
alert("wrong username password combination");
}
}
});
also change the data attribute names
var form_data = {
username: $("#username").val(),
password: $("#password").val(),
is_ajax: 1
};
If you are doing it with $.ajax, then your datatype is wrong. It must be application/x-www-form-urlencoded.
So please change your JS part to this:
$(document).ready(function(){
$("#submit").click(function(){
var form_data = {
usernm: $("#username").val(),
passwd: $("#password").val(),
is_ajax: 1
};
$.ajax({
type:"application/x-www-form-urlencoded",
url: "myurl.php" ,
data: form_data,
success: function (response)
{
if (response == 'success'){
window.location="myurl.html";
}
else{
alert("wrong username password combination")
}
}
});
return false;
});
});
Or, if you are not sure about the correct MIME type, then just use this jQuery command:
$(document).ready(function(){
$("#submit").click(function(){
var form_data = {
usernm: $("#username").val(),
passwd: $("#password").val(),
is_ajax: 1
};
$.post("myurl.php",
form_data,
function (response)
{
if (response == 'success'){
window.location="myurl.html";
}
else{
alert("wrong username password combination")
}
});
return false;
});
});
And please change also the following lines of your PHP code
$uName = $_REQUEST ['username'];
$pWord = $_REQUEST ['password'];
To this:
$uName = $_REQUEST ['usernm'];
$pWord = $_REQUEST ['passwd'];
Because these are the correct keys, wich you send to your php server file. Also, thereĀ“s no need for defining an "is_ajax" key, because every XMLHttpRequest has set the "X_REQUESTED_WITH" header to "XMLHttpRequest". So, you can request it in your php server part e. g. with:
if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
// it was an ajax XHR request!
}

Check text field value with database

I am trying to check inserting username is correct or not using jquery and php.. if username is not match with the value from database, it should be trigger an alert saying 'your user name is wrong'.
I tried this but I couldn't figure this out. When I type an username alert message triggering for each letter. But I need to check given value with database after entering in text field.
This is my Jquery -
// --- Check Username Availability for successful login --- //
$('#loginusername').keyup(function() {
var checkname=$(this).val();
var availname=remove_whitespaces(checkname);
if(availname!=''){
var String = 'username='+ availname;
$.ajax({
type: "POST",
url: "emailCheck.php",
data: String,
cache: false,
success: function(result){
var result=remove_whitespaces(result);
if(result == $('#loginusername').val()){
alert('Your entered Username is ok');
} else {
alert('Your entered Username is wrong');
}
}
});
}
});
This is from emailCheck.php
if(isset($_POST['username']) && !empty($_POST['username'])){
$userName = mysqli_real_escape_string($dbc, $_POST['username']);
$q = "SELECT username FROM userlogin
WHERE username = '$userName'";
$r = mysqli_query($dbc, $q);
$count = mysqli_num_rows($r);
$HTML='';
if($count == 1){
$HTML='username exists';
}else{
$HTML='';
}
echo $HTML;
}
Because you are using keyup event of textbox, use blur OR change event of textbox.
Edit
Change
if(result == $('#loginusername').val())
to
if(result == '')
Because you are sending blank result when no match found.
Well, in your JS, you're comparing what the user entered to what the PHP script returns:
result == $('#loginusername').val()
But the only thing your PHP script can return is the string 'username exists' or an empty string:
if($count == 1){
$HTML='username exists';
}else{
$HTML='';
}
Try just using alert(result).
var timer;
var time = 2000;
$('input').keyup(function() {
// when user stop typing for {time} second, do next function
timer= setTimeout(doSomething, time);
)
$('input').keydown(function() {
// when user continue typing clear timer
clearTimeout(timer);
)
function doSomething() {
}
try this
Change echo $HTML; to echo '{"success":"true", "usernameExists":"' + $count + '"}';
Then amend your Javascript to this
...
$.ajax({
type: "POST",
url: "emailCheck.php",
data: {username: availname},
cache: false,
success: function(result){
if(result.usernameExists == 1){
alert('Your entered Username is ok');
} else {
alert('Your entered Username is wrong');
}
}
});
instead of using keyup use 'onchange'
You can use the .blur trigger. http://api.jquery.com/blur/
// --- Check Username Availability for successful login --- //
$('#loginusername').blur(function() {
var checkname=$(this).val();
var availname=remove_whitespaces(checkname);
if(availname!=''){
var String = 'username='+ availname;
$.ajax({
type: "POST",
url: "emailCheck.php",
data: String,
cache: false,
success: function(result){
var result=remove_whitespaces(result);
if(result == $('#loginusername').val()){
alert('Your entered Username is ok');
} else {
alert('Your entered Username is wrong');
}
}
});
}
});
first of all you should change the event that your firing your check code. right now your firing at every keyup. I suggest change this to change
$('#loginusername').change(function() {
second there is an issue with your json response. In your php side your responding with an empty string when username is not found and an error message when the username is found. But your javascript side is expecting the return value to be the same as the username the user typed in the textbox when the string is available.
To meet this requirement lets change your php side of the code.
$HTML='';
if($count == 1){
$HTML='username exists';
}else{
$HTML=$_POST['username'];
}

why does jquery ajax go to the url rather than load it?

What the heck is up with this code?
$(".submit").click(function(){
alert("clicked");
var name = $(".name").val();
var email = $(".email").val();
var comment = $(".comment").val();
var articleId = $(".articleId").val();
var dataString = 'name='+ name + '&email=' + email + '&comment=' + comment+ '&articleId=' + articleId;
if(name=='' || comment==''){
alert('Please Give Valid Details');
}
else{
alert('so far so good');
$.ajax({
type: "POST",
url: "../_includes/process.php",
data: dataString,
cache: false,
success: function(){
alert("succes");
$(".updating").fadeIn(400);
}
});
}
});
Everything works until $.ajax finds process.php and instead of reading and executing the code it actually goes to that page in the browser. I tried using return false after the ajax call but then the code in process.php never happens.
here is process.php
<?php
// code to establish connection first
if($_POST){
$name=$_POST['name'];
$name=mysql_real_escape_string($name);
$email=$_POST['email'];
$email=mysql_real_escape_string($email);
$comment=$_POST['comment'];
$comment=mysql_real_escape_string($comment);
$articleId=$_POST['articleId'];
$articleId=mysql_real_escape_string($articleId);
if(!empty($email)){
$lowercase = strtolower($email);
}
$result = mysql_query("INSERT INTO comments(name,email,comment,articleId) VALUES ('$name','$email','$comment','$articleId')");
if($result){
echo "success";
} else {
echo "there were erros" . mysql_error();
}
exit;
?>
Any help would be appreciated.
You have to prevent the default action of your submit button:
$(".submit").click(function(e) {
e.preventDefault();
alert("clicked");
...
});
You need to echo something out from process.php if you want to know it worked ok.
e.g
echo 'success';
exit; // just incase
then in your ajax request
success: function(response){
if (response == 'success') {
alert("success");
$(".updating").fadeIn(400);
}
else {
alert('error');
}
}
even if you aren't echoing out, process.php should still work.
try turning on error reporting if it still isn't working:
error_reporting(E_ALL);
ini_set('display_errors', 'On');

JQuery AJAX + PHP Login

I am using PHP + jQuery AJAX to log a user into my site. The PHP connects to the database and the jquery connects to the PHP file and everything works until it comes time to actually log in. When I type in my username and password, the file returns an error. I had this working about a week ago but I was doing some code cleanup and I accidentally deleted the script where it performed the log in and now I can't get it to work. Here is my PHP file:
<?php
include('.conf.php');
$user = $_POST['user'];
$pass = $_POST['pass'];
$result = mysql_query("SELECT * FROM accountController WHERE username = '$user'");while ($row = mysql_fetch_array($result)) {
if (sha1($user.$pass) == $row['pword']) {
setcookie('temp', $row['username']);
session_start();
$_SESSION['login'] = 1;
$_SESSION['uname'] = $row['username'];
echo "success";
}
}
?>
I do believe the PHP file is echoing the correct statement and yes, the passwords in the database are sha1 encrypted. Here is the jquery code:
$('.mainlogin').submit(function() {
$.ajax({
url: 'log.php',
type: 'POST',
data: {
user: username,
pass: password
},
success: function(response) {
if(response == 'success') {
window.location.reload();
} else {
$('.logerror').fadeIn(250);
}
}
});
return false;
});
Thanks for all the help!
EDIT: I am not sure what is wrong right now but it won't log me in no matter what I try. I have corrected everything you guys suggested below, but to no avail. Anything wrong in my PHP file possibly?
try this:
$('.mainlogin').submit(function() {
$.ajax({
url: 'log.php',
type: 'POST',
data: {
username: username,
password:password
},
success: function(response) {
if(response == 'success') {
window.location.reload();
} else {
$('.logerror').fadeIn(250);
}
}
});
return false;
});
or chaneg data params
data: 'username='+username+'&password='+password
AND USE &!!!!
You have a typo:
data: 'user='+username+'pass='+password,
should be:
data: 'user='+username+'&pass='+password,
or use #Olaf's alternative, which makes sure you don't make mistakes like that.
What others have said. The '&' is needed to separate your parameters.
On a somewhat related note, you might want to consider salting those passwords...

Categories