I'm not able to connect with database using jquery ajax - php

I'm not able to connect with database using jquery ajax.
The below is the login1.html page
<form method='POST'>
<div class="username">
<input type="text" id='name' name="name" class="form-control" placeholder="Enter your username">
<i class="glyphicon glyphicon-user"></i>
</div>
<div class="password">
<input type="password" id='password' name='password' class="form-control" placeholder="Enter your password">
<i class="glyphicon glyphicon-lock"></i>
</div>
<div id="error"></div>
<div class="custom-radio-checkbox">
<input tabindex="1" type="checkbox" class="bluecheckradios">
<label>Remember me</label>
</div>
<script>
$(document).ready(function(){
$('.bluecheckradios').iCheck({
checkboxClass: 'icheckbox_flat-blue',
radioClass: 'iradio_flat-blue',
increaseArea: '20%' // optional
});
});
</script>
<input type="submit" class="btn btn-primary style2" name='submit' id="submit" value="Sign In">
</form>
The form value is transferred through jquery ajax
<script>
$(document).ready(function(){
// jQuery methods go here...
$('#submit').click(function(){
var username = $('#name').val();
var pass = $('#password').val();
var datastring = {username:username,pass:pass};
if($.trim(username).length>0 && $.trim(pass).length>0){
$.ajax({
type: "POST",
url : "process/login.php",
data : datastring,
cache: false,
beforeSend : function(){
$("#submit").val('Connectiing...');
},
success:function(data){
if(data){
window.location.href('http://www.google.com');
}
else{
$('#loginone').shake();
$('#submit').val('Login')
$("#error").html("<span style='color:red'>Error:</span>Invalid Username or Password");
}
}
});
}
return false;
});
});
</script>
** This is the data connection page process/login.php**
<?php
include_once('config.php');
if(isset($_POST['submit'])){
$username = $_POST['username'];
$pass = $_POST['pass'];
$sql = "select id from login where login_name = '".$username."' and login_password = '".$pass."' ";
$result = $conn->query($sql);
if($result->num_row > 0){
echo "connected";
}
}//EOF SUBMIT
?>
When ever i pass the correct credentials i get an error for wrong username and password.

You are not sending the value of the submit over the ajax change your if to
if(isset($_POST['username']) && isset($_POST['pass']) ){
or add the value to the ajax:
datastring = {username:username,pass:pass,submit:"true"};

You are getting wrong username and password because your PHP not returning anything in ajax success.
Whats wrong here:
You are sending username and password in ajax request but checking by using submit input which is wrong because submit is not the part of ajax data.
You can also check what are you getting in ajax request in php as:
print_r($_POST);
Here, you can solve the problem as:
if(count($_POST) > 0) // check $_POST array > 0 or not..
instead of:
if(isset($_POST['submit'])){ // submit not available in $_POST

The object data you are sending through Ajax to the PHP script does not have a key called "submit" and hence this part of the code will fail
if(isset($_POST['submit'])){
Just remove that if statement and you will be fine... You can equally check whether you have data within the $_POST super global like devpro suggested in the comment below your question or just check for only the fields you sent within the $_POST variable.

Related

showing toastr after checking if the password and user name is correct from database

as a practice i made a log in form and linked it with a MySQL database and am trying to show a toastr according to to the result that is if the username and password are correct or not so when the input fields are empty it's showing the error toaster but when i add any thing in the fields it always shows the success toastr i don't know how to fix that
here is my html code
<form class="sing_in_form " method="POST" action="#">
<input id="email" type="text" name="username" placeholder="Email">
<input id="password" type="text" name="password" placeholder="password">
<!--log in button-->
<button type="submit" id="btn" name="submit " value="LOGIN" class="btn-login">Sign In</button>
<p class="sign_up">Don't have account? Sign up</p>
</form>
php
if(isset($_POST['username'])){ //username from the form
$uname=$_POST['username'];//username from the form
$pass_word=$_POST['password'];
$sql="SELECT * FROM `loginform2` WHERE user='".$uname."' And Pass='".$pass_word."' limit 1";
$result= $con->query($sql);
}
and my js code
$(document).ready(function(){
$("#btn").click(function(){
var name = $("#email").val();
var password = $("#password").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'username='+ name + '&password='+ password;
if(name==''||password=='')
{
toastr.error("fill the feilds");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "login(2).php",
data: dataString,
cache: false,
success: function(){
toastr.success("logged in");
}
});
}
return false;
});
});
Do something like this.
Put if(mysqli_num_rows($result) ===1 {echo 1}; after $result= $con->query($sql);
And then edit your ajax request as
success: function(data){
if(data ==1){
toastr.success("logged in");
}else{
//error message goes here
}
}

Submit form using ajax: Was working, now not working?

I have the following HTML form in signup.php:
<form id="signup" action="" method="POST" autocomplete="off" autocomplete="false">
<div class="signup_row action">
<input type="text" placeholder="What's your Name?" name="name" id="name" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<input type="text" placeholder="Got an Email?" name="email" id="email" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<div class="g-recaptcha" style="margin-top:30px;" data-sitekey="6LeCkZkUAAAAAOeokX86JWQxuS6E7jWHEC61tS9T"></div>
<input type="submit" class="signup_bt" name="submit" id="submt" value="Create My Account">
</div>
</form>
I am trying to submit the form using ajax, without page refresh:
<!-- include files -->
<?php include 'assets/config.php';?>
<?php if(isset($_SESSION["CUSTOMER_ID"])){
header('Location: myaccount.php'); } ?>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'do_signup_check.php',
data:{"name":name,"email":email},
success: function () {
if(result == 0){
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('do_signup.php',function(){}).hide().fadeIn(500);
});
}else{
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('assets/login.php',function(){}).hide().fadeIn(500);
}
});
});
});
</script>
I am posting the form to do_signup_check.php and running a query to see if the user is already registered. echo 1 for a positive result and 0 for a negative result:
Do_Signup_Check.php:
<?php
session_start();
require 'assets/connect.php';
$myName=$_POST["name"];
$myEmail=$_POST["email"];
$check = mysqli_query($conn, "SELECT * FROM user_verification WHERE email='".$myEmail."'");
if (!$check) {
die('Error: ' . mysqli_error($conn)); }
if(mysqli_num_rows($check) > 0){
echo '1';
}else{
echo '0';
}
?>
If the result is 0 then the ajax should load my page do_signup.php.
But alas it is not getting this far. It was working and then i switched off the computer and came back to it and now it won't work.
Please can someone show me where I've gone wrong?
if(result == 0){ here result is not using in success function:
you must need to pass resultant variable here:
success: function () {
as:
success: function (result) {
Now, you can use your condition if(result == 0){
Second, i suggest you to pass dataType: 'html' in your ajax request.
Edit:
You are using <?php if(isset($_SESSION["CUSTOMER_ID"])){ line in your code, if you are not using session_start() in your code then this check will not work.
For this line data:{"name":name,"email":email}, i didnt see name and email in your code, where you define these 2 variables which you are using in your ajax params.

login with ajax issue

I am trying to create on-page login.
without ajax it works very well. Here is my login.php;
if($_POST)
{
$username =$_POST["username"];
$password =$_POST["password"];
$query = $handler->query("SELECT * FROM members WHERE username='$username' && password='$password'",PDO::FETCH_ASSOC);
if ( $say = $query -> rowCount() ){
if( $say > 0 ){
session_start();
$_SESSION['session']=true;
$_SESSION['username']=$username;
$_SESSION['password']=$password;
echo "ok";
}else{
echo "Couldn't login.";
}
}else{
echo "Wrong username or password.";
}
}
Anyway, here is my java script code;
$(function(){
$("#loginbutton").click(function(){
var username = $("#username").val();
var password = $("#password").val();
if(username != "" && password != ""){
$.ajax("login.php",{
type : "POST",
data : "username="+username+"&password="+password,
success : function(data){
if(data == "ok"){
$("#message").html(data);
}else{
$("#fail").fadeIn();
}
}
});
}
});
});
Even though I put correct login information (when I get "ok" response from login.php, it always outputs $("#fail").fadeIn(); . instead of $("#message").html(data); I couldn't figure out where I am mistaken.
and here is login form:
<div id="login">
<form action="" onsubmit="return false;" method="post">
<input type="text" class="form-control" id="username" name="username" placeholder="Username" autocomplete="off"><br>
<input type="password" class="form-control" id="password" name="password" placeholder="Password" autocomplete="off"><br>
<input class="btn btn-success" type="submit" id="loginbutton" value="Login">
</form>
<div id="message"> </div>
<div id="fail" style="display: none;">failed.</div>
</div>
You are using type as post, but sending parameters as get.Change your ajax like this,
$.ajax("login.php",{
type : "POST",
data : {username:username,password:password},// only this line is changed.
success : function(data){
if(data == "ok"){
$("#message").html(data);
}else{
$("#fail").fadeIn();
}
}
});
Here is a quick example of using post with JQuery AJAX.
$(document).ready(function(){
$.post("login.php", {username:username, password:password}, function(data){
if(data == 'ok'){
$("#message").html(data);
}else{
alert(data);//alert the data you receive. It alerts you if there is any error in php file.
$("#fail").fadeIn();
}
});
});
Hope that was helpful!
Firstly, debug your code like this:
1) On button click you will put alert function inside javascript code. if it is working then move second step.
2) use alert function to print username and password if it comes inside your javascript code and correct as you put into input fields then move third step.
3) use serialize method in javascript.
I hope its help you to get your solution.

Won't run ajax if I change input type..?

I have a form for user to update their info using jquery + Ajax. Everything is working great so far, but WHen i change input type="email" to input type="text" in the fullname section of the form and click update. It got error??? It won't run the php file in ajax. I don't see any connection which causes this error? Anyone please sugguest why? But if I change input type in the fullname section back to "email". It works! This is so weird!
Here is my form:
<div id="changeuserinfo_result"></div>
<form role="form" method="post">
<div class="form-group">
<label>Fullname</label>
<input type="text" class="form-control" id="changename" name="changename" value="<?php echo $_SESSION['name'] ?>">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" id="changepass" name="changepass" value="<?php echo $_SESSION['pass'] ?>">
</div>
<button class="btn btn-default" id="changeuserinfo">Update</button>
</form>
Here is my jquery code:
$(document).ready(function(){
$('#changename').focus();
$('#changeuserinfo').click(function(){
var changename = $('#changename');
var changepass = $('#changepass');
var changeuserinfo_result = $('#changeuserinfo_result');
changeuserinfo_result.html('loading...');
if(changename.val() == ''){
changename.focus();
changeuserinfo_result.html('<span class="errorss"> * Empty fullname</span>');
return false;
}
else if(changepass.val() == ''){
changepass.focus();
changeuserinfo_result.html('<span class="errorss">* Empty password</span>');
return false;
}
else {
var UrlToPass = {changename:changename.val(),changepass:changepass.val()} ;
$.ajax({
type : 'POST',
cache: false,
data : UrlToPass,
url : 'changeuserinfo.php',
success: function(responseText){
if(responseText == 1){
$('#changeuserinfo_result').html('<span style="color:green"> Update OK</span>');
}
else{
$('#changeuserinfo_result').html('<span class="errorss"> Update fail. Try again</span>');
}
}
});
}
});
});
You have no closing tags on your inputs.
It should be <input type="text"... />
Also set the doctype of the page to HTML5.
<!DOCTYPE HTML>
....
</html>

No alert in success function

I am trying to insert value in database from jquery ajax and i want whenever data insertion is successfull, a result output comes true other wise "error:failed". My entry in database successfully updated, but when i alert(msg), its doesnt give me message.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<body>
<div class="wrapper">
<div id="main" style="padding:50px 0 0 0;">
<!-- Form -->
<form id="contact-form" method="post">
<h3>Paypal Payment Details</h3>
<div class="controls">
<label>
<span>TagId</span>
<input placeholder="Please enter TagId" id="tagid" type="text" tabindex="1" >
</label>
</div>
<div class="controls">
<label>
<span>Paypal Email: (required)</span>
<input placeholder="All Payment will be collected in this email address" id="email" type="email" tabindex="2">
</label>
</div>
<div class="controls">
<label>
<span>Amount</span>
<input placeholder="Amount you would like to charged in GBP" id="amount" type="tel" tabindex="3">
</label>
</div>
<div class="controls">
<div id="error_div"></div>
</div>
<div>
<button name="submit" type="submit" id="form-submit">Submit Detail</button>
</div>
</form>
<!-- /Form -->
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#form-submit').click(function()
{
var tagid = $("#tagid").val();
var email = $("#email").val();
var amount = $("#amount").val();
var param = 'tagid='+ tagid + '&email=' + email + '&amount=' + amount;
param = param + '&type=assign_amount';
locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
success:function(msg)
{
alert(msg);
}
});
});
});
dbentry.php
<?php
$vals = $_POST;
include 'dbconfig.php';
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo json_encode(array('status' =>$values));
}
function assign_amount()
{
global $con;
global $vals;
$sql = "INSERT INTO `dynamic_url`(`tagid`,`email`,`amount`) VALUES('".$vals['tagid']."','".$vals['email']."','".$vals['amount']."')";
$result = mysql_query($sql,$con);
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
}else{
$status="failed";
}
return $status;
}
?>
Try to echo it like
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
} else {
$status="failed";
}
return $status;
And in your if statement code like
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo $values;
}
For the ajax return purpose you better to echo or print rather than return it.
In order to see alert() message, you have to prevent default behaviour of clicked submit button:
$('#form-submit').click(function(e)
{
e.preventDefault();
//....
}
Otherwise, the FORM is submited and page is reloaded.
Display $status at last in php file instead of return statement
You will get it in alert
echo $status;
Can you try this,
var locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
dataType:'json',
success:function(msg)
{
alert(msg.status.sql);
}
});
Your code has a lot of flaws in it. For instance you are contatenating the string to create a data object. But if somebody would enter a & or = or any other special charactor in it, your form would fail.
Also you are binding on the click function on a button. While this works, it would be useless for people without javascript. This might not be an issue, but its easily prevented with some minor changes.
I would change the <button name="submit" to <input type="submit" and then bind jQuery to the form it self. Also add the action attribute to the form to include 'dbentry.php'
$(function(){
$('#contact-form').submit(function(){
var $form = $(this);
var data = $form.serialize();
var locurl = 'dbentry.php';
$.post(locurl,data, function(msg) {
alert(msg.status)
}, 'json');
return false; //prevent regular submit
});
});
Now to make it work PHP has to return JSON data.
<?php
header('Content-type: application/json');
//your code that includes
echo json_encode(array('status' =>$sql));
//also notice that your code only returns data on success. Nothing on false.
?>

Categories