Form:-
<form name="form">
<div class="formfieldContainer">
<label> Email :</label>
<div class="login_wrapper loginContainer">
<span> </span>
<input type="email" id="email" required name="user_email" autofocus="autofocus" placeholder="Enter Email Address"/>
</div>
</div>
<div class="formfieldContainer">
<label> Password :</label>
<input type="password" name="user_password" placeholder="Enter Password"/>
</div>
<input type="button" name= "submit" value="submit" id="submit_login"/>
</form>
AJAX:-
$("#submit_login").click(function(){
var username=$('input[name=user_email]').val();
var password=$('input[name=user_password]').val();
$.ajax({
type: "POST",
url: "newExam.php",
data:{name: username,
pwd: password},
cache: false,
success: function(dataa) {
if(dataa)
{
console.log(dataa);
if(dataa==0)
{ $('form').effect( "shake" ); $('p.error').show(); $("#submit_login").val('Login')
alert('nodata');
}
else if(dataa==1){
window.location.href="user.php";
}
}
}
});// ajax
});
PHP:-
<?php
include('db.php');
$email_php = $_POST['name'];
$pwd_php=$_POST['pwd'];
$sql = "select name from user where email='$email_php' and password='$pwd_php'";
$result = mysqli_query($conn,$sql);
$num_rows= mysqli_num_rows($result);
if($num_rows>0){
$_SESSION['login_user']= $email_php;
echo '1';
}
else{
echo '0';
}
?>
I need the page to redirect to user.php when logged in successfully. But i am getting the following error:
Notice: Undefined index: name in C:\xampp\htdocs\demo\newExam.php on line 3
Notice: Undefined index: pwd in C:\xampp\htdocs\demo\newExam.php on line 4
How to overcome it?
Yo should be redirecting it from php page (using headers)instead of using window.location.href
You can use this method if you don't want to use php.
$.extend( {
redirectPost: function(location, args)
{
var form = '';
$.each( args, function( key, value ) {
form += '<input type="hidden" name="'+key+'" value="'+value+'">';
});
$('<form action="'+location+'" method="POST">'+form+'</form>').submit();
} });
Usage
$.redirectPost("user.php", {'key1': 'data1', 'key2': 'data2'});
Credit - https://gist.github.com/aabril/e6b96379ab0eb151a179
Related
I have a form that is posting data to a php api file. I got the api working and it creates an account but want to use AJAX to send the data so I can make the UX better. Here is what the PHP sending script is expecting:
<form id="modal-signup" action="/crowdhub_api_v2/api_user_create.php" method="post">
<div class="modal-half">
<input type="text" placeholder="First Name" name="user_firstname"></input>
</div>
<div class="modal-half">
<input type="text" placeholder="Last Name" name="user_lastname"></input>
</div>
<div class="modal-half">
<input type="Radio" placeholder="Gender" value="male" name="user_gender">Male</input>
</div>
<div class="modal-half">
<input type="Radio" placeholder="Gender" value="female" name="user_gender">Female</input>
</div>
<div class="modal-half">
<input type="date" placeholder="DOB" name="user_dateofbirth"></input>
</div>
<div class="modal-half">
<input type="text" placeholder="Zip Code" name="user_zip"></input>
</div>
<input class="end" type="email" placeholder="Email" name="user_email"></input>
<input type="password" placeholder="Password" name="user_password"></input>
<input type="submit"></input>
</form>
PHP
$user_firstname = $_REQUEST['user_firstname'];
$user_lastname = $_REQUEST['user_lastname'];
$user_email = $_REQUEST['user_email'];
$user_password = $_REQUEST['user_password'];
$user_zip = $_REQUEST['user_zip'];
$user_dateofbirth = $_REQUEST['user_dateofbirth'];
$user_gender = $_REQUEST['user_gender'];
$user_phone = $_REQUEST['user_phone'];
$user_newsletter = $_REQUEST['user_newsletter'];
How would I send this via ajax? I found this script that says it worked, but it did not create a user. I imagine its sending the data not the right way.
Ajax
$(function () {
$('#modal-signup').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/api_v2/api_user_create.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
First, let's get ajax in order:
$(function () {
$('#modal-signup').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
//same url as the form
url: '/crowdhub_api_v2/api_user_create.php',
data: $('form').serialize(),
//we need a variable here to see what happened with PHP
success: function (msg) {
//output to the page
$('#output').html(msg);
//or to the console
//console.log('return from ajax: ', msg);
}
});
});
});
Somewhere on the form page, add a div with id output:
<div id="output></div>
Finally, in api_user_create.php, there is an error:
$user_gender = $_REQUEST['user_gender'];
//these last two do not exist on the form
$user_phone = $_REQUEST['user_phone'];
$user_newsletter = $_REQUEST['user_newsletter'];
I'd recommend some error-checking on the PHP side, like this
if(!empty($_REQUEST)){
//For developing, you may want to just print the incoming data to see what came through
//This data returns into the msg variable of the ajax function
print_r($_POST);
//once that's good, process data
if(isset($_REQUEST['user_gender'])){
$user_gender = $_REQUEST['user_gender'];
}
//etc... as before
} else {
echo 'no data received';
}
I am creating an employee hierarchy and while setting up the superior for new employee I would like to check if the employee already exists in database ... but :) I would like to do it with AJAX to know it realtime without sending the form ..
I have absolutely no idea how to do it, since I am a newbie to Laravel ..
***UPDATED BASED ON ADVICES:***
I have a form in add_emp.blade.php:
<form action="../create_employee" method="POST">
<button class="button" type="submit" style="float:right"><span>Save</span></button>
<div style="clear:both"></div>
<fieldset>
<legend>Personal data</legend>
<label for="first_name">First name:</label><input type="text" class="add_emp required" name="first_name" value="" /><br />
<label for="last_name">Last name:</label><input type="text" class="add_emp required" name="last_name" value="" /><br />
<label for="superior">Superior:</label><input type="text" class="add_emp" name="superior" value="" id="superior_list" /><br />
</fieldset>
</form>
Here is a script in add_employee.blade.php
<script type="text/javascript">
$('#superior_list').blur(function(){
var first_name = $('#superior_list');
$.ajax({
method: "POST",
url: '/check_superior',
data: { superior: superior }
})
.done(function( msg ) {
if(msg == 'exist') {
//employee exists, do something...
alert( "good." );
} else {
//employee does not exist, do something...
alert( "bad." );
}
});
})
</script>
route for handling the superior:
Route::post('check_superior', 'EmployeeController#check_superior');
This is the Controller function check_superior:
public function check_superior(Request\AjaxUserExistsRequest $request){
if(Employee::where('superior','=',$request->input('superior'))->exists()){
return "exist";
}else{
return "not exist";
}
}
But still not working ... can you advice where could be the issue?
*** FINAL SOLUTION ***
Form:
<form action="../create_employee" method="POST">
<button class="button" type="submit" style="float:right"><span>Save</span></button>
<div style="clear:both"></div>
<fieldset>
<legend>Personal data</legend>
<label for="first_name">First name:</label><input type="text" class="add_emp required" name="first_name" value="" /><br />
<label for="last_name">Last name:</label><input type="text" class="add_emp required" name="last_name" value="" /><br />
<label for="superior">Superior:</label><input type="text" class="add_emp" name="superior" value="" id="superior_list" /><span id="check-superior-status"></span><br />
</fieldset>
</form>
Add to app.blade.php
meta name="csrf-token" content="{{ csrf_token() }}"
Controller
public function check_superior(Request $request){
if(Employee::where('first_name','=',$request->input('superior_fname'))
->where('last_name','=',$request->input('superior_lname'))
->exists()){
return "exist";
}else{
return "not exist";
}
}
final emp.blade.php AJAX script
// place data after SEPERIOR selection
$( "#superior_list" ).blur(function() {
var sup_list = $(this).val();
var sup_arr = sup_list.split(' ');
var superior_fname = sup_arr[0];
var superior_lname = sup_arr[1];
var superior = superior_fname+" "+superior_lname;
// control print out
//$('#check-superior-status').text(superior);
// get real data
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: "POST",
url: '/check_superior',
data: { superior_fname: superior_fname, superior_lname: superior_lname },
/* // debug only
error: function(xhr, status, error){
$('#check-superior-status').text(xhr.responseText);
},
*/
success: function(data){
$('#check-superior-status').text(data);
}
})
});
This works like a charm :) thank you guys .. hope this will help someone ..
First make the request.
php artisan make:request AjaxUserExistsRequest
Then open the request file (App\Http\Requests) and find the following:
public function validate(){
return [
//rules
];
}
This is where you would stick your validation rules so you can check against the form elements being submit.
Then you should use dependency injection to force your request into the first argument of the user_exists() function:
public function user_exists(Requests\AjaxUserExistsRequest $request){
return User::where('first_name', $request->first_name)->first();
}
This will return nullif no user exists, otherwise we don't care about the response.
Finally, of course we need our route.
Route::post('employee_exists', 'EmployeeController#user_exists');
Lastly, we'll go ahead and capture the form submit and check if the user exists with our jQuery.
$('#employee_form').submit(function(e){
e.preventDefault();
var first_name = $('#first_name').val(),
$this = this; //aliased so we can use in ajax success function
$.ajax({
type: 'POST',
url: '/employee_exists',
data: {first_name: first_name},
success: function(data){
if(data == null){
//then submit the form for real
$this.submit; //doesn't fire our jQuery's submit() function
} else {
//show some type of message to the user
alert('That user already exists!');
}
}
});
});
The below will give alert message the user already exists! if the first_name exists in your db or it will give alret nothing.(if you want to check with superior change the code vice versa)
first make sure you have jquery.min.js in your public folder.
Now in blade.php add id for first_name, last_name, and superior as below:
<form action="../create_employee" method="POST">
<button class="button" type="submit" style="float:right"><span>Save</span></button>
<div style="clear:both"></div>
<fieldset>
<legend>Personal data</legend>
<label for="first_name">First name:</label><input type="text" id="first_name" class="add_emp required" name="first_name" value="" /><br />
<label for="last_name">Last name:</label><input type="text" id="last_name" class="add_emp required" name="last_name" value="" /><br />
<label for="superior">Superior:</label><input type="text" class="add_emp" name="superior" value="" id="superior_list" /><br />
</fieldset>
</form>
<script>
$(document).ready(function(){
$("#superior_list").blur(function(){
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var superior = $('#superior_list').val();
$.ajax({
type: 'POST',
url: '/check_superior',
data: {first_name: first_name, last_name: last_name, superior: superior},
success: function(data){
if(data == 0){
alert('nothing');
} else {
alert('the user already exists!');
}
}
});
});
});
</script>
and in your route.php
Route::post('/check_superior', array('as' => '', 'uses' => 'EmployeeController#check_superior'));
in EmployeeController.php
public function check_superior(){
// can get last_name, superior like first_name below
$first_name = Input::get('first_name');
$data = YourModel::where('first_name',$first_name)->get();
return count($data);
}
It should work. if it doesn't please show us your error
Give your form an id:
<form action="../create_employee" method="POST" id="employee_form">
<button class="button" type="submit" style="float:right"><span>Save</span></button>
<div style="clear:both"></div>
<fieldset>
<legend>Personal data</legend>
<label for="first_name">First name:</label><input type="text" class="add_emp required" name="first_name" id="first_name" value="" /><br />
<label for="last_name">Last name:</label><input type="text" class="add_emp required" name="last_name" value="" /><br />
<label for="superior">Superior:</label><input type="text" class="add_emp" name="superior" value="" id="superior_list" /><br />
</fieldset>
</form>
your js will look like this
$('#employee_form').submit(function(e){
e.preventDefault();
var first_name = $('#first_name');
$.ajax({
method: "POST",
url: "checkUserExistence.php",
data: { first_name: first_name }
})
.done(function( msg ) {
if(msg == 'exist') {
//employee exists, do something...
} else {
//employee does not exist, do something...
}
});
})
also add csrf_field in your form to generate token, and use this token while sending request.
in your form:
{{ csrf_field() }}
in your ajax request:
$.ajax({
headers: {'X-CSRF-Token': $('input[name="_token"]').val()},
//other data....
})
you can also do it with meta teg. in your head teg
<meta name="csrf-token" content="{{ csrf_token() }}">
in your request
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content');
//other data...
}
});
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
How to access these variables ?
I'm trying to retrieve username and password in php files, But, it says Undefined index username if I use $_POST['Username'}
<script>
var a = new XMLHttpRequest();
a.onreadystatechange = function(){
if (a.readyState==4 && a.status==200) {
ajaxFinished = true;
alert(a.responseText);
}
else {
}
}
a.open("post","php/psswd.php",true);
a.send('"Username="+document.getElementByNames("Username")+"&Password="+getElementByNames("Password")'); // posting username and password
</script>
How to retrieve these fields in php file ?
I found out the answer myself, the problem was that,
a.setRequestHeader("Content-type","application/x-www-form-urlencoded");
needs to be added. And document.getElementsByName('xyz') returns nodeList, but not perticular node, We need to traverse that nodeList.
instead of using the XMLHttpRequest method, take a look at this:
<script type="text/javascript">
$('#loginForm').submit(function(e) {
var username = $("#login-username").val(); //id of the form text input
password = $("#login-password").val(); //id of the form text input
e.preventDefault();
$.ajax({
type: "POST",
url: url,
data: { form: 'login', username: '' + username + '', password: '' + password + ''}
}).success(function( msg ) {
//msg is the text returned from the PHP function that will validate the login
$('.login_success_text').html(msg);
});
});
</script>
<body>
<form role="form" name="loginForm" id="loginForm" method="POST">
<label>Username</label>
<input id="login-username" class="form-control text placeholder" placeholder="Username" name="username" type="text">
<label>Password</label>
<input id="login-password" class="form-control password placeholder" placeholder="Password" name="password" autocomplete="off" type="password">
<input type="submit" value="Login" />
<div class="login_success">
<span class="login_success_text"></span>
</div>
</body>
The syntax is getElementsByName and not the way you presently have getElementByNames
The word Elements is pluralized, not Names.
<script>
var a = new XMLHttpRequest();
a.onreadystatechange = function(){
if (a.readyState==4 && a.status==200)
{
ajaxFinished = true;
alert(a.responseText);
}
else
{
}
}
a.open("post","php/psswd.php",true);
a.send('"Username="+document.getElementsByName("Username")+"&Password="+getElementsByName("Password")'); // posting username and password
</script>
For more information on this, visit:
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByName
Edit
The following works using jQuery and tested with FF 28.0 and IE 7.
Sidenote: You may want to change this window.location = "success.php"
<!DOCTYPE html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
function chk_ajax_login_with_php(){
var username=document.getElementById("username").value;
var password=document.getElementById("password").value;
var params = "username="+username+"&password="+password;
var url = "php/psswd.php";
$.ajax({
type: 'POST',
url: url,
dataType: 'html',
data: params,
beforeSend: function() {
document.getElementById("status").innerHTML= 'checking...' ;
},
complete: function() {
},
success: function(html) {
document.getElementById("status").innerHTML= html;
if(html=="success"){
window.location = "success.php"
}
}
});
}
</script>
</head>
<body>
<div id='logindiv'>
<label>Username:</label>
<input name="username" id="username" type="text">
<label>Password:</label>
<input name="password" id="password" type="password">
<input value="Submit" name="submit" class="submit" type="submit" onclick='chk_ajax_login_with_php();'>
<div id='status'></div>
</div>
This chunk of AJAX
$('input#adminLogin').on('submit', function() {
var username = $('#username').val();
var password = $('#password').val();
if (username == '' || password == '')
$('#errForm').fadeIn(200).text('You must enter a username and password');
else {
$.ajax ({
type: 'post',
url: '/classes/login/Authenticator.php',
data: $('#login_form').serialize(),
cache: false,
success: function(data) {
if(data == 'You entered an invalid username or password');
$('.actionDiv').fadeIn(200).html(data);
else
$('.fade_bg').fadeOut(200);
}
});
}
});
Is making this jQuery
$('a#aLogin').on('click', function (e) {
e.preventDefault();
$('.fade_bg').fadeIn(200);
$('a#aLogin').hide();
});
not work, whether or not I have e.preventDefault() in the AJAX method. How come?
HTML
<div class="fade_bg">
<div class="actionDiv">
<span id="errForm"></span>
<form id="login_form" action="./classes/login/Authenticator.php" method="post">
<p>username: <input type="text" name="username" id="username" /></p>
<p>password: <input type="password" name="password" id="password" /></p>
<p><input type="submit" name="adminLogin" value="Log in" id="adminLogin" /></p>
</form>
<p><a id="cancelLogin" href="">Cancel</a></p>
</div>
<div id="topRight">
<a id="aLogin" href="">Admin login</a>
<form id="exit" action="./classes/login/ExitDoor.php" method="post">
<p>
<?php
if ($_SESSION['logged-in'] == 1)
print '<span id="greeting">Welcome, ' . $_SESSION['firstName'] . ' | </span>';
?>
<input id="aLogout" type="submit" name="adminLogout" value="Log out" />
</p>
</form>
</div>
You have a syntax error in your first snippet. That's why the second one isn't executed anymore.
Remove the semicolon at the end of this line
if(data == 'You entered an invalid username or password'); <--
All major browser have built-in developer tools. You can find such errors very quick by having a look at the developer console.
In your example chromes console would show you this - http://i43.tinypic.com/xqg48.jpg