I am making a simple registration system in Ionic Cordova. I am sending the data from the form to server through an AJAX call but I am not getting anything in response form the sever. When I made a different conventional form and dent the data to the same script I got the proper response. I am able to figure out the issue.
form:-
<div class="list" id="register">
<label class="item item-input item-floating-label">
<span class="input-label">Name</span>
<input type="text" placeholder="Name" id="name">
</label>
<br>
<label class="item item-input item-floating-label">
<span class="input-label">Email</span>
<input type="email" placeholder="Email" id="email">
</label>
<br>
<label class="item item-input item-floating-label">
<span class="input-label">Password</span>
<input type="password" placeholder="Password" id="pass">
</label><br>
<button class="button button-full button-assertive" id="signup">
Submit
</button>
AJAX call:-
$(document).ready(function(){
$("#signup").click(function(){
console.log("Button clicked");
var name=$("#name").val();
var email=$("#email").val();
var pass=$("#pass").val();
var dataString="name="+name+"&email="+email+"&pass="+pass+"&signup=";
if($.trim(name).length>0 && $.trim(email).length>0 && $.trim(pass).length>0)
{
$.ajax({
type: "POST",
url: "http://127.0.0.1/ionic/reg.php",
data: {dataString: dataString,signup:true},
success: function(data){
if(data =="success")
{
alert("Thank you for Registering with us! you can login now");
}
else if(data =="exist")
{
alert("Hey! You alreay has account! you can login with us");
}
else if(data =="failed")
{
alert("Something Went wrong");
}
}
});
}
return false;
});
});
PHP script:-
<?php
header('Access-Control-Allow-Origin: *');
include 'db_connect.php';
if(isset($_POST['signup']))
{
$name=trim($_POST['name']);
$email=trim($_POST['email']);
$password=trim($_POST['pass']);
$login=mysqli_num_rows(mysqli_query($con,"select * from `phonegap_login` where `email`='$email'"));
if($login!=0)
{
echo "exist";
}
else
{
$q=mysqli_query($con,"insert into `phonegap_login` (`name`,`email`,`password`) values ('$name','$email','$password')");
if($q)
{
echo "success";
}
else
{
echo "failed";
}
}
echo mysql_error();
}
?>
Related
I am trying to get my jQuery to work with CSS animations/class changes and working with an ajax post for this logon forum. I am having trouble reworking the JQuery animation script and incorporating the Ajax port for username and password. It does not seem to be posting the login information.
<form class="login" action="" method="post" autocomplete="false">
<div class="group">
<input id="user" type="username" name="user" class="input" placeholder="Username" required autofocus>
</div>
<div class="group">
<input id="password" type="password" name="password" class="input" data-type="password" placeholder="Password" required>
</div>
<div class="group">
<button>
<i class="spinner"></i>
<span class="state">Log in</span>
</button>
</div>
<div class="hr"></div>
</form>
Here is the jQuery
var working = false;
$('.login').on('submit', function(e) {
e.preventDefault();
if (working) return;
working = true;
var $this = $(this),
$state = $this.find('button > .state');
$this.addClass('loading');
$state.html('Authenticating');
$.ajax({
type: "POST",
data: $(this).serialize(),
cache: false,
url: "login.php",
success: function(data) {
if (data.status == 'success') {
this.addClass('ok');
$state.html('Welcome back!');
setTimeout(function() {
window.location = "/index.php"
}, 4000);
} else if (data.status == 'error') {
setTimeout(function() {
$state.html('Log in');
$this.removeClass('ok loading');
}, 3000);
}
},
});
});
After using Diego's suggestion and piping the out to the console log I was able to determine that the php function was not returning anything. Adding an echo in with corresponding results resolved my issue along with using 'data' in the if statement instead of 'data.status'.
In my app I want to make a login page. I want do do this login using ajax jquery. If login success it navigate to next page or show a error message in a div.
this is my code
<form role="form">
<div class="form-group radio-inline">
<label><b>I Am</b></label>
<input type="radio" name="category" value="s"> Student
<input type="radio" name="category" value="t"> Teacher
<input type="radio" name="category" value="p"> Parent
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email address">
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" name="password" placeholder="Enter password">
</div>
<button type="submit" class="btn btn-primary btn-block">Sign in</button>
</form>
<div id="error">
</div>
jquery
$(document).on('click','.btn',function() {
var email = $("#email").val();
var password = $("#password").val();
var category = $("input[name=category]:checked").val();
$.ajax({
url: "../logincheck.php",
type: "POST",
data: {category:category,email:email,password:password},
success:function(data) {
if (data==='studentlogin') {
window.location.href = '../student/index.php';
}
if(data==='teacherlogin'){
window.location.href = '../teacher/index.php';
}
if(data==='teachersubject') {
window.location.href = '../teacher/subjectadd.php';
}
else {
window.location.href = 'login.html';
$("#error").html("Invalis Email/Password");
}
}
});
});
logincheck.php
$category=$_POST['category'];
$email=$_POST['email'];
$pwd=$_POST['password'];
if ($category == 's') {
$result=mysqli_query($conn,"SELECT studentid,studentfname FROM studentinfo WHERE emailid='$email' and pwd='$pwd'");
$res=mysqli_fetch_array($result);
if($res[0]>0){
$_SESSION['snstudentid']=$res[0] ;
$_SESSION['snstudentfname']=$res[1] ;
echo "studentlogin";
//header("location:student/index.php");
exit();
}
else{
echo "error";
//header("location:pages/login.html");
}
} elseif ($category == 't') {
$result=mysqli_query($conn,"SELECT teacherid,teacherfname FROM teacherinfo WHERE emailid='$email' and pwd='$pwd'");
$res=mysqli_fetch_array($result);
if($res[0]>0){
$check_subject = mysqli_query($conn, "SELECT count(teachersubjectid) FROM teachersubject WHERE teacherid='$res[0]'");
$subject_result = mysqli_fetch_array($check_subject);
if ($subject_result[0]>0) {
$_SESSION['snteacherid']=$res[0];
$_SESSION['snteacherfname']=$res[1];
echo "teacherlogin";
//header("location:teacher/index.php");
exit();
} else {
$_SESSION['snteacherid']=$res[0];
$_SESSION['snteacherfname']=$res[1];
echo "teachersubject";
//header("location:teacher/subjectadd.php");
exit();
}
} else{
echo "error";
//header("location:pages/login.html");
}
}
that error message show for few second and then it goes.I do that error class style display:none;
How I do that?Please help me.
Have a look at what this code does:
else {
window.location.href = 'login.html';
$("#error").html("Invalis Email/Password");
}
yes, it redirects the page to login.html, then, while the page is loading it puts up the error message, then the page load completes and, in your initial login page, the error message is empty.
Remove the line:
window.location.href = 'login.html';
assuming you are already on login.html.
If <div id="error"> has a style of display:none;, then its contents will not be displayed. Inside of the ajax success callback, $("#error").html("Invalis Email/Password"); needs to be $("#error").html("Invalis Email/Password").show(); to set display:block;. See .show().
I am working with ajax and php. I want to display message on another page after user successfully added using Ajax. I have tried so much. It's working when first display "Success" message on popup and afrer redirect on another page. But i want to first redirect on another page and after display message.
User Add Page:
<form action="<?php echo $action_link; ?>" method="post" id="form_user_profile" class="form-horizontal" novalidate="novalidate">
<input type="hidden" id="id" name="id" value="<?php echo $id; ?>">
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">First Name
<span class="required" aria-required="true"> * </span>
</label>
<div class="col-md-4">
<div class="input-icon right">
<i class="fa"></i>
<input type="text" class="form-control" name="fname" value="<?php echo $user_db[0]['fname']; ?>">
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<input type="submit" class="btn green" name="submit" value="<?php echo $addupdate_msg; ?>">
</div>
</div>
</div>
</form>
Ajax in Validate
$("#form_user_profile").validate({
rules: {
fname: {
required: true
}
},
messages: {
fname: "Please enter first name"
},
submitHandler: function(form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(response) {
if(response == 1){
bootbox.alert("User has been added successfully.", function() {
window.location.href= "<?php echo $user_list; ?>";
});
}
}
});
}
});
Action
if (isset($_REQUEST['submit']) && $_REQUEST['submit'] == "Add") {
$fname = mysqli_real_escape_string($obj->CONN, $_REQUEST['fname']);
$user->setfname($fname);
$insert = $user->insert();
ob_get_clean();
if($insert){
echo '1';
$_SESSION['msg'] = "New user has been added successfully.";
}else{
echo '0';
}
exit;
}
The success popup appears before the user is redirected because of the following code:
if(response == 1){
bootbox.alert("User has been added successfully.", function() {
window.location.href= "<?php echo $user_list; ?>";
});
}
If you wish to show a message on the new page instead, just redirect the user
if(response == 1)window.location.href= "<?php echo $user_list; ?>";
On the new page where you send the customer after success, show the message with something like
$(function() {
bootbox.alert(<?= $_SESSION['msg'] ?>);
});
You can check if there is a $_SESSION['msg'] set on the page you are directing it to, if set then alert.
Jquery:
if(response == 1){window.location.href= "<?php echo $user_list ?>";}
Then, $user_list page:
if(isset($_SESSION['msg'])){
echo '$(document).ready(function(){
bootbox.alert('.$_SESSION['msg'].');
})';
}
Note, I'm using the single quotes so that PHP doesn't think $ is a variable.
I am trying to learn web applications, here I have my client side using HTML and server is PHP based.
I have signup from on my client side, which when filled and click submit button is sent to PHP page using jQuery AJAX.
So, after the form data is sent or POST to PHP page using AJAX, a couple of validations happen like checking username and email, if the validations succeed it should send back a JSON object to my HTML page "SUCCESS", if validation fails "Error".
So, the problem is when I submit the form it is redirecting me to the PHP page instead of displaying the JSON response back on my html.
I was trying to solve this since last week and I filtered stack overflow, youtube and many other sites for a solution, which didn't go well.
Here is the code
PHP:
<?php include ( "./inc/connect.inc.php" );
header("Content-type: application/javascript");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET");
session_start();
if (isset($_SESSION['user_login'])) {
$user = $_SESSION["user_login"];
}
else
{
$user = "";
}
?>
<?php
$registration = #$_POST['signup-submit'];
$fname = #$_POST['fname'];
$lname = #$_POST['lname'];
$uname = #$_POST['uname'];
$email = #$_POST['email'];
$email_repeat = #$_POST['email_repeat'];
$password = #$_POST['password'];
$ucheck_array = array('Username Takne');
$echeck_array = array('Email already used');
$siginup_sucess_array = array('Sucess');
//Sign-Up form validation
if ($registration) {
$usernamecheck = mysql_query("SELECT * FROM users WHERE username='$uname' ");
$usernamecount = mysql_num_rows($usernamecheck);
$emailcheck = mysql_query("SELECT * FROM users WHERE email='$email' ");
$emailcount = mysql_num_rows($emailcheck);
if ($usernamecount == 0 && $emailcount == 0) {
$squery = mysql_query("INSERT INTO users VALUES ('','$uname','$fname','$lname','$dob','$location','$email','$password','$date','0','','','','','','no')" );
echo json_encode($siginup_sucess_array);
}
else {
if ($usernamecount == 1) {
echo json_encode($ucheck_array);
}
else if ($emailcount == 1) {
echo json_encode($echeck_array);
}
}
}
HTML Form:
<form id="register-form" class="animated fadeInRight" action="http://localhost/Exercises/AJAX/df.php" method="post" role="form" style="display: none;">
<div class="form-group">
<input type="text" name="fname" id="fname" placeholder="First Name" value="" autofocus>
</div>
<div class="form-group">
<input type="text" name="lname" id="lname" tabindex="1" class="form-control" placeholder="Last Name" value="">
</div>
<div class="form-group">
<input type="text" name="uname" id="uname" tabindex="1" class="form-control" placeholder="User Name" value="">
</div>
<div class="form-group">
<input type="text" name="dob" id="dob" placeholder="D-O-B" value="">
</div>
<div class="form-group">
<input type="text" name="location" id="location" tabindex="1" class="form-control" placeholder="Location" value="">
</div>
<div class="form-group">
<input type="email" name="email" id="email" placeholder="Email" value="">
</div>
<div class="form-group">
<input type="email" name="email_repeat" id="email_repeat" placeholder="Confirm Email" value="">
</div>
<div class="form-group">
<input type="text" name="password" id="password" tabindex="1" class="form-control" placeholder="Password" value="">
</div>
<div class="form-group dob">
<input type="text" name="date" id="date" placeholder="Date" value="">
</div>
<p class="index_p">By creating the account you accept all the <span style="color: #4CAF50; font-weight: bold; text-decoration: underline;">Terms & Conditions.</span></p>
<div class="form-group">
<div class="row">
<div id="btn_signin" class="col-sm-6 col-sm-offset-3">
<input type="submit" name="signup-submit" id="signup-submit" value="SIGN UP">
</div>
</div>
</div>
</form>
<div id="signup-test"></div> //PHP response to be displayed here
JS:
$("#signup-submit").click( function() {
$.post( $("#register-form").attr("action"),
$("#register-form :input").serializeArray(),
function(signup_data){
$("#signup-test").html(signup_data);
});
clearInput();
});
$("#register-form").submit( function() {
return false;
});
function clearInput() {
$("#register-form :input").each( function() {
$(this).val('');
});
}
To be clear I tried e.preventDefault, return false and many other scripts,
and my PHP and HTML are not in the same folder or directory.
Thanks.
Try using a more flexible jQuery ajax. I use this version if ajax because I can change it to get and post very easily. I have tested this method and it works with your form:
<script>
function clearInput() {
$("#register-form :input").each( function() {
$(this).val('');
});
}
$(document).ready(function() {
$("#register-form").submit(function(e) {
//console.log($(this).attr("action"));
$.ajax({
url: $(this).attr("action"),
type: 'post',
data: $(this).serialize(),
success: function(response)
{
// console.log(response);
$("#signin-test").html(response);
clearInput();
},
error: function(response)
{
console.log(response);
}
});
e.preventDefault();
});
});
</script>
This may be because you are handling your form based on the behavior of a button. You should be listening for the onSubmit event of the form and preventing that from firing.
$("#register-form").submit( function( e ) {
e.preventDefault();
$.post( $("#register-form").attr("action"),
$("#register-form :input").serializeArray(),
function(signup_data){
$("#signup-test").html(signup_data);
});
clearInput();
});
I solved it with the following script, hope it would help someone.
The problem with all the scripts which I tried is, they don't have XMLHttpRequest permission to POST data and get the data back from PHP(server side in my case).
So, XMLHttpRequest is a must for Ajax to Get or Post data "CROSS_DOMAIN".
Script :
function signup(){
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value;
var email_repeat = document.getElementById("email_repeat").value;
var password = document.getElementById("password").value;
if (fname == "") {
document.getElementById("fname").style.background = "rgba(244,67,54,0.45)";
document.getElementById("fnamestatus").innerHTML = "<p style='width: 30px; color: rgba(255, 62, 48, 0.9); font-size: 14px; font-weight: bold; margin-top:5px; margin-left: -40px; margin-bottom: 0px;'>2-25</p>";
}
else if (email != email_repeat){
document.getElementById("email").style.background = "rgba(244,67,54,0.45)";
document.getElementById("email_repeat").style.background = "rgba(244,67,54,0.45)";
alert("Your email fields do not match");
}
else {
var signup_ajax = new XMLHttpRequest();
signup_ajax.open("POST", "URL which you want to post data", true);
signup_ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
signup_ajax.onreadystatechange = function () {
if (signup_ajax.readyState == 4 && signup_ajax.status == 200) {
if (signup_ajax.responseText = "Success"){
alert("Account created");
}
else if (signup_ajax.responseText = "Try again.") {
window.scrollTo(0,0);
alert("Try again.");
}
}
}
signup_ajax.send("fname=" +fname+ "&lname=" +lname+ "&uname=" +uname+ "&email=" +email+ "&email_repeat=" +email_repeat+ "&password=" +password );
}
}
PHP(I'm just posting the basic php, you can always add as may validations as you need) :
if(isset($_POST["uname"])) {
$fname = #$_POST['firstname'];
$lname = #$_POST['lastname'];
$uname = #$_POST['uname'];
$email = #$_POST['email'];
$email_repeat = #$_POST['email_repeat'];
$password = #$_POST['password'];
//Sign-Up form validation
if($_POST) {
$squery = mysql_query("INSERT INTO users VALUES ('','$uname','$fname','$lname','$email','$password')" );
echo 'Sucess';
}
else
echo 'Try again.';
}
Only change what I did to my HTML Form is :
<input type="button" name="signup-submit" id="signup-submit" class="form-control btn btn-signup" onclick="signup()" tabindex="4" value="SIGN UP">
I have a popup form which i am submitting through AJAX and PHP. The problem is the form is submitting successfully but script is neither uploading pic nor inserting pic name to mysql.
If i don't use a popup form with the same script than it's working properly.
Any help ??
Html form:
<form action="" method="post" class="signupform">
<label>Full Name</label>
<input type="text" Placeholder="Name" name="name" pattern="[A-Z a-z]{3,25}" title="Name should contain 3 to 25 characters" Required="required"/>
<br />
<label>Email Address</label>
<input type="email" Placeholder="Email-id" name="email" Required="required"/>
<br />
<label>Password</label>
<input type="password" Placeholder="Password" name="pass" pattern="[A-Za-z0-9#]{6,15}" title="Password should be alphanumeric. Only A-Z,a-z,0-9 and # allowed and it must be 6 to 15 digits long." Required="required"/>
<br />
<label>Sex</label>
<span>Male<input type="radio" name="sex" checked="checked" value="M"/> Female<input type="radio" name="sex" value="F"/></span>
<br />
<label>City</label>
<input type="text" Placeholder="City" name="city" Required="required"/>
<br />
<label>Profile pic</label>
<input type="file" Placeholder="Profile pic" name="dp"/>
<br />
<div class="checkbox">
<input id="send_updates" type="checkbox" Required="required"/>
<label for="send_updates">I accept the terms and conditions</label>
</div>
<div class="action_btns">
<div class="one_half"><i class="fa fa-angle-double-left"></i> Back</div>
<div class="xyx xyxy"><input type="submit" value="Register" name="submitp" class="signsub"/></div>
</div>
</form>
Ajax:
$(document).ready(function()
{
$('.signsub').click(function()
{
$.ajax({
type: "POST",
url: "ajaxsignup.php",
data: $('.signupform').serialize(),
cache: false,
success: function(data) {
if (data)
{
$('.user_register').hide();
$(".error").html(" Thank you for joining us you are successfully logged in !!").show().delay(30000).fadeOut('slow');
window.location.reload().delay(30000);
}
else
{
$(".signsub").val('Register')
$(".error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
return false;
});
});
ajaxsignup.php
<?php
session_start();
include('includes/db.php');
$name=$_POST['name'];
$pass=$_POST['pass'];
$email=$_POST['email'];
$sex=$_POST['sex'];
$city=$_POST['city'];
$dp=$_FILES['dp']['name'];
include('includes/uploadfiledp.php');
$queryb="INSERT INTO login VALUES('','$name','$pass','$email','$sex','$city','$chckfil')";
$resultb=mysql_query($queryb);
if($resultb)
{
$_SESSION['user']=$email;
echo ok;
}
?>
uploadfiledp.php
$allowedExts = array("jpeg", "jpg");
$extension = end(explode(".", $_FILES["dp"]["name"]));
if (in_array($extension, $allowedExts))
{
if ($_FILES["dp"]["error"] > 0)
{
echo "Return Code: " . $_FILES["dp"]["error"] . "<br>";
}
else
{
if (file_exists("images/" . $_FILES["dp"]["name"]))
{
$b=explode(".", $_FILES["dp"]["name"]);
$first=$b[0];
$ext=$b[1];
$i=1;
do
{
$fname1=$first;
$fname1=$fname1.$i;
$i++;
$chckfil=$fname1.".".$ext;
}
while(file_exists("images/" . $chckfil));
move_uploaded_file($_FILES["dp"]["tmp_name"],
"images/" . $chckfil);
}
else
{
move_uploaded_file($_FILES["dp"]["tmp_name"],
"images/" . $_FILES["dp"]["name"]);
$chckfil=$_FILES["dp"]["name"];
}
}
}
else
{
echo "Invalid file";
}
The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls.Data from file select elements is not serialized.Something like this might help u..
You can make use of Formdata() ,
$(document).ready(function()
{
$("#formID").submit(function(){
{
var formData = new FormData($(this)[0]);
$.ajax({
type: "POST",
url: "ajaxsignup.php",
data: formData,
contentType: false,
processData: false,
cache: false,
success: function(data) {
if (data)
{
$('.user_register').hide();
$(".error").html(" Thank you for joining us you are successfully logged in !!").show().delay(30000).fadeOut('slow');
window.location.reload().delay(30000);
}
else
{
$(".signsub").val('Register')
$(".error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
return false;
});
});
FYI
FormData
ProcessData is set to false so that it prevents jQuery from automatically transforming the data into a query string