HTML Form:
<form enctype="multipart/form-data" method="post" name="fileinfo" id="myForm">
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus id="userid" name="userid" placeholder="email" required size="32" maxlength="64" /><br />
<label>File to stash:</label>
<input type="file" name="fileToUpload[]" id="fileToUpload[]" required />
<input type="file" name="fileToUpload[]" id="fileToUpload[]" required />
<input type="submit" id="save" value="Stash the file!" />
</form>
I have used formdata to the best of my knowledge but I am not sure if I have done it right.
Javascript Code:
<script type="text/javascript">
$('#save').click(function(event){
event.preventDefault();
var fd = new FormData(document.querySelector("form"));
var ins = document.getElementById('fileToUpload[]').files.length;
console.log(ins);
if (ins != 0) {
fd.append("fileToUpload[][]", document.getElementById('fileToUpload[]').files[0]);
fd.append("Email", $('#userid').val());
for (var pair of fd.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(data){
console.log(data);
}
});
}
else{
console.log("Nothing attached ");
}
})
</script>
In my upload.php file i am just trying to print the names. but i Am always getting count value as 3 whatever be the number of files uploaded on the front end, even if I don't upload any files at all, it gives the value 2.
<?php
$count = count($_FILES['fileToUpload']['name']);
echo $count;
for ($i = 0; $i < $count; $i++) {
echo 'Name: '.$_FILES['fileToUpload']['name'][$i].'\r\n';
}
?>
I am doing this for the first time. I have no idea where I am going wrong. Thanks in advance.
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();
}
?>
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...
}
});
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
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