How to login users using ajax and php? - javascript

I've added an ajax jquery function to do a much nicer login, but it still doesn't work. What am I doing wrong? Thanks.
form_log.php withing heads:
<script type="text/javascript">
$(document).ready(function() {
$('#myform').submit(function() {
$.ajax({
type: "POST",
url: 'login.php',
data: {
username: $("#username").val(), //id
password: $("#password").val()
},
success: function(data)
{
if (data === 'Correct') {
window.location.replace('index.php');
}
else {
alert(data);
}
}
});
});
});
</script>
And the in form_log.php's html bodies:
<form id="myform">
<label for="username">Username</label>
<input type="text" id="username" value="waqmaz#gmail.com" />
<label for="password">Password</label>
<input type="text" id="password" value="Lol123" />
<input type="submit" id="login" value="Login"/>
</form>
Now login.php:
<?php
session_start();
require("funkcje_bazy.php");
//require('fff.php');
$lacz = lacz_bd();
$nazwa_uz_l = $_POST['username'];//nazwa_uz_l
$haslo_l = $_POST['password']; //haslo_l
$wynik = $lacz->query("SELECT * FROM uzytkownicy WHERE email='".$nazwa_uz_l."' AND haslo = '".$haslo_l."' AND aktywacja IS NULL ");
if($wynik->num_rows>0) {
$_SESSION['prawid_uzyt'] = $nazwa_uz_l;
echo ('Correct');
}
else
{
echo 'Incorrect username/password';
}
?>
At the top of all these 2 files I have session_start(); icluding index.php.
The login doesn't work. When I click input submit, nothing happens. I am new to an jquery ajax. I check the correct answers, thanks.

Try to prevent the default action of the submit button by using event.preventDefault(), meaning block the post back which is about to happen,
$('#myform').submit(function(e) {
e.preventDefault();
.
.
//rest of your code.

An alternative is to use:
$('#login').click(function() {

Related

how to clear form after submit the form and pass the data to php file without reloading page

how to clear form after submit the form and pass the data to php file without reloading page...the form data is pass the php file and it stored the data base.but i was unable to clear the form data after submit the form.if i reset the form using javascrip but data not pass the data base.if i pass the data to php the form is not clear.is there a way for me achive both target?thank you..
here my snipt code...
<iframe name="votar" style="display:none;"></iframe>
<form action="confirm.php" id="sfm" method="POST" target="votar">
<input type="text" placeholder="Name" name="name" value="" required/>
<input type="submit" value="Submit My Project " />
</form>
Using AJAX you can do this.
$('#submitBtn').click(function () {
$.ajax({
url: 'confirm.php',
data: $('#sfm').serialize(),
type: "post",
success: function (data) {
$('input[type="text"]').val('');
}
});
return false;
});
you can try this
in index.php
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'ajax.php',
data: $('form').serialize(),
success: function (data) {
$('#name').val('');
alert('data');
//your return value in data
}
});
});
});
</script>
</head>
<body>
<form action="ajax.php" id="sfm" method="POST" target="votar">
<input type="text" placeholder="Name" name="name" id="name" value="" required/>
<input type="submit" value="Submit My Project " />
</form>
</body>
</html>
and in ajax.php
<?php
$name = $_GET['name'];
//do what you want to do using name
echo "what you need to return";
Have you thought about to use Ajax to handle the form submit?
Form submit with AJAX passing form data to PHP without page refresh
try making $_POST array empty after submitting and saving the form
$_POST='';
After getting success response you can clear form input
$('#sfm').submit(function () {
var form = $(this);
$.ajax({
url: 'phpfile.php',
data: form.serialize(),
type: "POST",
success: function (data) {
$('input[type="text"]').val('');
}
});
return false;
});
You can do like this, first get form inputs value and then reset
You can also able to reset after success response
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var that = $(this);
var params = that.serialize();
that.get(0).reset();
console.log(params);
$.ajax({
type: 'GET',
url: 'submit.php',
data: params,
success: function (data) {
console.log(data);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="confirm.php" id="sfm" method="POST" target="votar">
<input type="text" placeholder="Name" name="name" value="" required/>
<input type="submit" value="Submit My Project " />
</form>
SERVER SIDE
<?php
$name = $_GET['name'];
echo 'success';
exit();
?>

AJAX success function works, but file isn't running

I'm new to StackOverflow, web development, and I'm low on time for this assignment, so I apologize if I'm a bit slower at understanding web development vocabulary and any answers or tips. I'm having trouble with calling another php file through ajax.
index.php:
<!--------------------------- HTML STARTUP ----------------------------------->
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="finalproject.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="finalproject.js"></script>
<title>Final Project</title>
</head>
<body>
<!--------------------------- LOGIN ------------------------------------------>
<?php
require_once 'dbconnection.php';
//----------------------- CREATE USERS TABLE -----------------------------------
$userspass = "CREATE TABLE usersPass (
userID VARCHAR(60),
password VARCHAR(60)
);";
$connected->query($userspass);
$selectAllInfo = "SELECT * FROM usersPass;";
$connected->query($selectAllInfo);
//-------------------------- LOG IN OR REGISTER --------------------------------
?>
<form id="trial"><button onclick="OpenRegister()">Sign Up!</button>
<script>
$(document).on("click" , "#Register", function(e)
{
var datastring = $("#trial").serialize();
$.ajax({
type: 'POST',
url: 'userlogin.php',
data: datastring,
success: function(data){
alert('Sign Up function is a success!');
}
});
e.preventDefault();
});
</script></form>
<br/><br/>
<button onclick="InputInfo()">Login</button>
<?php
$connected->close();
?>
</body>
</html>
And here's the JavaScript when the function is called.
finalproject.js:
/*jslint browser: true*/
/*global $, jQuery, alert*/
function OpenRegister() {
'use strict';
$('form').append("<div id=SignInContainer>
<span style='font-size: 20px'>UserID</span>
<input type='text' name='UserID' value='Type userID here...'>
<span style='font-size: 20px'>Password</span>
<input type='text' name='UserID' value='Type password here...'>
<button id='Register'>Submit</button>
</div>");
}
$(document).ready(function () {
'use strict';
$(document).on('focus', 'input', function () {
$('input').focus(function () {
$(this).val('');
});
});
});
And this is the php file I'm trying to load. userlogin.php:
<?php echo "If this displays, you win." ?>
dbconnection.php
<?php
$connected = new mysqli('localhost', 'Username', 'Password', 'Username');
mysqli_select_db($connected, 'cferna50');
// Check connection
if ($connected->connect_error) {
die("Connection failed: " . $connected->connect_error);
}
I'm just trying to get the "userlogin.php"file to run through AJAX. I'm running this thing on Chrome. I've heard that there is a bit of a problem with using AJAX on local files, but I tried that --access-file-from-files thing and it didn't help. I tried running it on FireFox and Internet Explorer and it still doesn't help. I'm sure I have everything in the same directory. I'm using an online school server thing to do all this. I've been hurting my head over this for endless hours, any help would GREATLY be appreciated.
Simply because you are not passing (data) through the method, either you Serialize the data or pass them individually, and i suppose you will use the first method to save time
<script>
$(document).on("submit","#loginForm", function(e)
{
var datastring = $("#loginForm").serialize();
$.ajax({
type: 'POST',
url: 'userlogin.php',
data: datastring,
success: function(data){
alert(data);
//or
//alert('Sign Up function is a success!');
},
error: function(){
alert("error handling");
}
});
e.preventDefault();
});
</script>
HTML
<form id="loginForm" method="POST">
<input type="text" name="userid" id="userid" placeholder="user ID" />
<input type="text" name="password" id="password" placeholder="Password" />
<button type="submit" >Submit</button>
</form>
PHP
<?php
if(isset($_POST['userid'])){
$username = $_POST['userid'];
$pass = $_POST['password'];
//do your magic now
}
?>
Correct concatenation of html string at .append() remove if($("#Register").click())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function SignUp() {
if ($("[name=username]").val().length
&& $("[name=password]").val().length) {
$.ajax({
type: 'POST',
url: 'userlogin.php',
data: {
username: $("[name=username]").val(),
password: $("[name=password]").val()
},
success: function(data) {
alert('Sign Up function is a success!');
},
error: function() {
alert("stacsnippets success")
}
});
}
}
</script>
<script>
function OpenRegister() {
'use strict';
$('body').append("<div id=SignInContainer>"
+ "<span style='font-size: 20px'>UserID</span>"
+ "<input type='text' name='username' placeholder='Type userID here...'>"
+ "<span style='font-size: 20px'>Password</span>"
+ "<input type='password' name='password' placeholder='Type password here...'>"
+ "<button onclick='SignUp()' id='Register'>Submit</button>"
+ "</div>");
}
</script>
<button onclick="OpenRegister()">Sign Up!</button>
php
if (isset($_POST["username"]) && isset($_POST["password"])) {
// do username, password validation stuff here
}
jsfiddle https://jsfiddle.net/qnrnn5b5/

How to pass on a form through Ajax, and PHP

I'm new to this, I just want it to work with simple code then i'll add onto it. But it's not working in the sense that i don't get an echo. I just want to submit a form and have it not refresh the page.
here is my form
<form >
<input type="text" id="name" >
<input type="submit" value="s" onclick="return chl()" >
</form>
here is my js
<script>
function chl(){
var name= document.getElementByID('name').value;
var dataString='name' + name;
$.ajax({
type:"post",
url:"hi.php",
data:dataString,
cache:false,
success: function(html){
alert ("success");
}
});
return false;
}
</script>
and here is my php
<?php
$name=$_POST ['name'];
echo "response".$name;
?>
The datastring should be formed like a querystring; you've missed the = between the key and the value:
var dataString = 'name=' + name;
That being said, you can improve your code. Firstly you should attach the event to the submit of the form, and use event.preventDefault() to stop the normal form submission. Also, you can use serialize() to generate an object containing the forms' values to pass across in the AJAX request. The response from your PHP code will be retuned in the parameter sent to the success handler, so you need to do something with it there. Lastly, you should attach your events in JS, not HTML attributes, for a better separation of concerns. Try this:
<form method="hi.php">
<input type="text" id="name" />
<input type="submit" value="s" />
</form>
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "post",
url: this.action,
data: $(this).serialize(),
cache: false,
success: function(html){
alert(html); // = 'response: name = [VALUE]'
}
});
});
$name = $_POST['name'];
echo "response: name = ".$name;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<!--form method="hi.php"--> <!-- Remove this from your code and method is post or get you can't use hi.php as method -->
<input type="text" id="name" />
<input type="submit" id="click" value="s" /> <!-- Give id to your button -->
<!--/form-->
<script type="text/javascript" src="js/jquery.js"></script> <!-- You need to use jquery -->
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#click').on('click', function(event) {
event.preventDefault();
/* Act on the event */
var name=$('#name').val();
$.ajax({
url: 'hi.php',
type: 'POST',
data: {name: name}
})
.done(function(data) {
alert(data); // You can alert that data
console.log(data); //or you view this data on console Ctrl+shift+I
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
});
</script>
</body>
</html>
<!-- Your php page hi.php -->
<?php
echo $_POST['nmae'];
// or just say hi
echo 'hi';
?>
Form
<form name="test" id="test">
<input type="text" id="name" >
<input type="submit" value="s" >
</form>
Script
<script>
$("#test").submit(function(e){
e.preventDefault();
var name= document.getElementByID('name').value;
$.ajax({
type:"post",
url:"hi.php",
data:{"name":name},
cache:false,
success: function(html){
alert (html);
}
});
return false;
}
</script>
You can also try with -
var dataString = $('form').serialize();
By this you can get rid of generating the datastring if you have a number of input fields.
change ajax function like and send data as shown below and your php and js function must be in different pages
function chl(){
var name= document.getElementByID('name').value;
$.ajax({
type:"post",
url:"hi.php",
data:{name:name},
success: function(html){
alert ("success");
}
});
return false;
}
<form method="POST" action="server.php">
<input type="text" name="name" id="myName" >
<input type="submit" value="s" onclick="chl(); return false;" >
</form>
<script>
function chl()
{
var nameElement = document.getElementById("myName");
//Creates formData object and sends it to PHP script
var formData = new FormData();
//name equals to input element name attribute value
formData.append(nameElement.name, nameElement.value);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
alert(xmlHttp.responseText);
}
}
xmlHttp.open("POST", "server.php");
xmlHttp.send(formData);
}
</script>
<?php
$name = $_POST['name'];
echo $name;
?>

Form is not submitting in jQuery ajax success

I am making a simple form of single text input.I want to cross check from db that is it exist or not.So my html is
<form action="zoneAdd" method="post" id="zoneAdd" name="zoneAdd">
<div class="box-body">
<div class="form-group">
<label>Zone Name<span id="required">*</span></label>
<input type="text" class="form-control" name="zone_name" id="zone_name" placeholder="Enter Zone Name" />
<span id="zone_name_error"></span>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<input type="submit" class="btn btn-primary btn-flat btn-sm" name="submit" value="Submit"/>
</div>
</form>
and my javasript is
$('document').ready(function(){
$("[name=submit]").click(function(e){
e.preventDefault();
if ($('#zone_name').val().length <= 0) {
$('#zone_name').addClass("errMsg");
$('#zone_name_error').addClass("errMsgDngr");
$('#zone_name_error').html('Please enter Zone name!');
//isStepValid = false;
}
else if(!$('#zone_name').val().match(/^[a-zA-Z\s-, ]+$/)){
$('#zone_name').addClass("errMsg");
$('#zone_name_error').addClass("errMsgDngr");
$('#zone_name_error').html('Please use only alphabats!');
//isStepValid = false;
}else{
var data = {'zone':$('#zone_name').val()}
$.ajax({
type:"post",
data:data,
url:"<?php echo site_url('zone/checkZoneName');?>",
success:function(err){
if(err == 0)
{
console.log('hello');
$('#zone_name_error').html('');
$('#zone_name_error').removeClass("errMsg");
$('#zone_name_error').removeClass("errMsgDngr");
//document.forms["zoneAdd"].submit();
$('form#zoneAdd').submit();
//console.log($('form#zoneAdd').submit());
}
else
{
$('#zone_name').addClass("errMsg");
$('#zone_name_error').addClass("errMsgDngr");
$('#zone_name_error').html('Zone Name already existed!');
}
}
});
}
});
});
every thing is going right. My problem is my form is not submit in ajax success
I think problem in form action.
Specify exact path in the form action such that
<form action="<?php echo site_url('filenameWhereyouSubmit')?>" method="post" id="zoneAdd" name="zoneAdd">
You don't have a handler function on form submit and your ajax call
happens after $("[name=submit]").click().
You're submitting the form after ajax success:
success:function(err){
if(err == 0)
{
...
$('form#zoneAdd').submit();
...
}
}
but the submit is not ajax call, so try to handle the form
onsubmit.
something like this:
$('document').ready(function(){
$('form#zoneAdd').submit(function(e){
e.preventDefault();
// You checks code ...
var data = {
'zone': $('#zone_name').val()
};
$.ajax({
type:"post",
data:data,
url:"<?php echo site_url('zone/checkZoneName');?>",
success: function (err){
if(err == 0)
{
console.log('hello');
$('#zone_name_error').html('');
$('#zone_name_error').removeClass("errMsg");
$('#zone_name_error').removeClass("errMsgDngr");
}
else
{
$('#zone_name').addClass("errMsg");
$('#zone_name_error').addClass("errMsgDngr");
$('#zone_name_error').html('Zone Name already existed!');
}
}
});
});
});
Start form like this :
<form id="FORM-ID" method="post" action="">
For ajax submit
$(document).ready(function(){
$('#FORM-ID').submit(function(e) {
var myarray= array of all form values
var data = JSON.stringify(myarray);
e.preventDefault();
$.ajax({
type: "POST",
data: {value:data},
url: "URL TO SUBMIT",
success: function() {
//Sucess function
}
});
});

HTML Form sends data to PHP Form without leaving the current page

I'm having issues with sending data from my HTML Form to my PHP page (via JS/AJAX) while staying on my current page. Here is what I currently have in place:
HTML Section:
<!-- Begin the Form -->
<form id="signup-form" method="POST">
<!-- Input of E-Mail -->
<div class="seven columns">
<input type="email" name="email" id="email" placeholder="Your E-Mail">
</div>
<!-- Send Button -->
<div class="five columns">
<button name="submit" type="button" class="button">Subscribe</button>
</div>
<!-- End of the Form -->
</form>
PHP:
<?php
require_once 'MCAPI.class.php';
$apikey = 'XXXXXX';
$list_id ='XXXXXX';
$api = new MCAPI($apikey);
$email = $_POST['email'];
echo "Email: ".$email;
$merge_vars = array(' ');
// By default this sends a confirmation email - you will not see new members
// until the link contained in it is clicked!
$retval = $api->listSubscribe( $list_id, $email, $merge_vars );
if ($api->errorCode){
echo "Unable to load listSubscribe()!\n";
echo "\tCode=".$api->errorCode."\n";
echo "\tMsg=".$api->errorMessage."\n";
} else {
echo "E-Mail submitted to the pxCollective Newsletter!";
}
?>
JS:
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var email = $("#email").val();
if(email=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "subscribeEmail.php",
data: email,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
If I don't try to keep it on the current page with JS/AJAX it'll direct to the PHP page just fine and subscribe the user to the mailing list. Any ideas as to what my issue may be?
Thanks!
This line data: email, should be data: {email: email},
try this
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var email = $("#email").val();
if(email=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "subscribeEmail.php",
data: {email: email}, // don't data: email,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
You're using $('.submit').click(), but there is no element with class submit! Your submit button is class button instead.
You should use $('#signup-form').submit() instead and change your <button> to an <input type="submit">.
Try
$.ajax({
type: "POST",
url: "subscribeEmail.php",
data: {email:email},
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
It should be "email="+email

Categories

Resources