Ajax PUT method not hitting the server - javascript

I have a login form and I am trying to login using a PUT method as to store the logged-in username. But for some reason it's not hitting the server and not logging in. Could you please help?
I want this to go to the login page and failing to do so. Please help
Below is the code for the same:
HTML:
<form name="login" class="login-form request-form form-horizontal" method="post" id="login-user">
<p class="pl-sign">Please Sign In</p>
<div class="form-group" id="login-fields">
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"><span class="text--white glyphicon glyphicon-user"></span></i>
</span>
<input type="text" name="user" id="user" placeholder="Username" class="form-control" required/>
</div>
</div>
</div>
<div class="form-group" id="login-fields">
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"><span class="text--white glyphicon glyphicon-lock"></span></i>
</span>
<input type="password" name="pass" id="pass" placeholder="Password" class="form-control" required/>
</div>
</div>
</div>
<input class="view sign-in-app" type="submit" value="Sign In" id="submit-login" />
<div class="forgot-up">
forgot username/password ?
</div>
</form>
jQuery:
$("#login-user").validate({
submitHandler: userLogin
});
function userLogin() {
var username = $('#user').val();
var password = $('#pass').val();
var data = $("#login-user").serialize();
var userUrl = 'http://website.com/DatabaseName/Tablename/' + username + '/login?' + password + '';
console.log(data);
$.ajax({
url: userUrl,
type: 'PUT',
data: data,
success: function(data) {
if (data == 0) {
window.location.href = "http://website.com/page2.html";
} else if (data == -1) {
("#error").html('<span class="error">Incorrect username or password</span>');
} else {
$("#error").fadeIn(1000, function() {
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> ' + data + ' !</div>');
});
}
}
});
}

If you don't want a form submit to laod a new page (or relaod the current one if action isn't defined in the form), use preventDefault() method on the passed in event to the event handler
function userLogin(e) {
e.preventDefault();
... rest of your code
I'm assuming
submitHandler: userLogin
in the validate object will pass on the event object

Related

AJAX I must double click to submit second textarea! (Laravel)

$(document).ready(function (){
$('#myForm').submit(function (e) {
e.preventDefault(); //Do not submit the form
var dataflow=$(this).serialize(); //Get the inputs value
$.post('{{route('homepage.update')}}', dataflow, function (data){ //post.create is the route name
//The request is done, do something with the server response
});
});
});
I use this to save form without refresh
Here is my route
Route::post('/homepage/update', 'AdminController#Update')->name('homepage.update');
And my html
{{ csrf_field() }}
<div class="form-group">
<label for="title"><b class="fa fa-pencil"></b> Title</label>
<input id="title" class="form-control" value="{{ $article->title }}" name="title">
<br />
<label for="content"><b class="fa fa-home"></b> Desc</label>
<div class="box-body pad">
<textarea id="content" name="content" rows="10" cols="80">
{{ $article->content }}
</textarea>
</div>
</div>
<center>
<div class="form-group">
<button type="submit" class="btn btn-success btn-sm"><b class="fa fa-save"></b> Submit</button>
</form>
My function who update ajax data
public function HomePage(Request $r) {
$article = Article::find(1);
$article->title = $r->input('title');
$article->content = $r->input('content');
$article->homepage = 1;
$article->save();
}
The problem is i must click twice button to save two forms when i click one it submit only title! Please help how to fix that

val and fadeOut not working on click

i'm creating a ajax post request that works fine. however to make it more appealing i'm trying to implement so that when the user click on #sign_in it will change the text while request is going on. if it result in error a message will appear. this message will automatically remove after a couple of seconds. however if u click .close it will force close. The issue is however that following does not work:
$(".alert a").click(function(e) {
$('.alert').fadeOut();
});
Nothing happens when i click on .close. in addition to this below does not work either.
$('#sign_in').val('Logger ind...');
Full Code
<form id="sign_in">
<div class="form-group">
<input type="text" name="username" id="username" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<input type="password" name="password" id="password" class="form-control" placeholder="Kodeord">
</div>
<a href="#">
<small>Forgot password?</small>
</a>
<div class="form-group text-center add_top_20">
<input class="btn_1 medium" id="sign_in" type="submit" value="Log ind">
<input type="hidden" name="next" value="{{ next }}" />
</div>
</form>
<div class="alert alert-error alert-danger" style="display: none;">
<a class="close" href="#">×</a>
Invalid email or password. Try clicking 'Forgot Password' if you're having trouble signing in.
</div>
jquery
$("#sign_in").submit(function (event) {
// Change sign in button text
$('#sign_in').val('Logger ind...');
// post request
event.preventDefault();
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url: "/account/login/auth/",
type: "POST",
dataType : 'json',
contentType: 'application/json',
data: {
'username': username,
'password': password
}, success: function (data) {
if (data.success) {
alert('success');
} else {
showAlert()
}
// Change sign in text back
$('#sign_in').val('Log ind');
}, error: function(error){
// Change sign in text back
$('#sign_in').val('Log ind');
}
});
});
function showAlert(){
if(!$('.alert').is(':visible'))
{
$('.alert').fadeIn()
$('.alert').delay(4000).fadeOut()
}
}
$(".alert a").click(function(e) {
$('.alert').fadeOut();
});
and all of this is wrapped in $(document).ready(function () {
Mmm, your event is launching but you need to use clearQueue in order to launch your fadeOut animation again interrupting the previous one.
$(".alert a").click(function(e) {
$('.alert').clearQueue();
$('.alert').fadeOut();
});
Change your form id or submit button id and change :visible to :hidden
function showAlert(){
if($('.alert').is(':hidden'))
{
$('.alert').fadeIn()
$('.alert').delay(4000).fadeOut()
}
}
Here I have change form 'id'
<form id="sign_in_form">
<div class="form-group">
<input type="text" name="username" id="username" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<input type="password" name="password" id="password" class="form-control" placeholder="Kodeord">
</div>
<a href="#">
<small>Forgot password?</small>
</a>
<div class="form-group text-center add_top_20">
<input class="btn_1 medium" id="sign_in" type="submit" value="Log ind">
<input type="hidden" name="next" value="{{ next }}" />
</div>
</form>
<div class="alert alert-error alert-danger" style="display: none;">
<a class="close" href="#">×</a>
Invalid email or password. Try clicking 'Forgot Password' if you're having trouble signing in.
</div>
jQuery
$("#sign_in_form").submit(function (event) {
// Change sign in button text
$('#sign_in').val('Logger ind...');
// post request
event.preventDefault();
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url: "/account/login/auth/",
type: "POST",
dataType : 'json',
contentType: 'application/json',
data: {
'username': username,
'password': password
}, success: function (data) {
if (data.success) {
alert('success');
} else {
showAlert()
}
// Change sign in text back
$('#sign_in').val('Log ind');
}, error: function(error){
// Change sign in text back
$('#sign_in').val('Log ind');
}
});
});
function showAlert(){
if($('.alert').is(':hidden'))
{
$('.alert').fadeIn()
$('.alert').delay(4000).fadeOut()
}
}
$(".alert a").click(function(e) {
$('.alert').clearQueue();
$('.alert').fadeOut();
});

Search with ajax on click and show results in same page laravel

I've setup a view which contains a search form:
<form>
<input type="hidden" id="product_id" value="{{$tour->id}}">
<div class="form-group col-md-4">
<label>Date:</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control pull-right" id="start" placeholder="Start Date">
</div>
</div>
<div class="form-group col-md-4">
<label>End:</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control pull-right" id="end" placeholder="End Date">
</div>
</div>
<div class="form-group col-md-4" id="dateprice-search">
<label></label>
<button type="submit" class="btn" id="btn-search" >
Search
</button>
</div>
The below is the ajax code to handle the request of the form:
$(document).ready(function() {
$('#dateprice-search').on('click', '#btn-search', function() {
$.ajax({
type: 'post',
url: '/date-price',
data: {
'_token': $('input[name=_token]').val(),
'product_id': $("#product_id").val(),
'start': $("#start").val(),
'end': $("#end").val()
},
success: function(data) {
$('.shadow-z-1').show();
$('.shadow-z-1').append("<tr class='liquid-row><td>" + data.start + "</td><td>"+ data.end + "</td><td>" + data.end + "</td><td><a class='btn-m btn btn-m-success'>Available</a></td></tr>");
}
});
});
});
Route:
Route::post('/date-price','GetPublicController#datePrice')
->name('searchDate');
And finally method in controller to give the results:
public function datePrice(Request $request){
$start = $request->start;
$end = $request->end;
$dates = DatePrice::where('tour_id','=',$request->product_id)
->whereBetween('start', array($request->start, $request->end))
->whereBetween('end', array($request->start, $request->end))
->get();
return response()->json($dates);
}
At first the url looks like this before submitting the form http://localhost:8000/trips/popular/trekking/test and url becomes http://localhost:8000/trips/popular/trekking/test? after clicking the search button. Console section of inspect element shows no error in script. What mistake I had made over here ?
It mean your form submiting to same page due to type="submit"
1) change to type="button"
<button type="button" class="btn" id="btn-search" >
2) Here click event should be for button not to div so change the selector and add e.preventDefault(); in jquery to prevent the default submit .
$('#btn-search').on('click', '#btn-search', function() { e.preventDefault(); });
note :
1st : your action attribute missing so form will be submit same page .
2nd : your method attribute missing so it will take default GET method
You have given button type as submit, either remove it as
<button type="button" class="btn" id="btn-search" >
Search
</button>
or use the jquery preventDeafult() function to prevent the default behavior of submit button i.e form submit in your button click event as
$(document).ready(function() {
$('#dateprice-search').on('click', '#btn-search', function(e) {
e.preventDefault();
//your ajax code
});
});

Node and Angular form conditions

I have A front end Angular form, with Node reviving the data on the back end.
I have conditions on the from in the front end written in Angular, I would like have some extra conditions that would display with a new button to replace the submit button if the post was successful.
dose anyone know how I would do this ? I was thinking something like ng-hide/show show text and button and hide form and submit button on form completion.
Node Code
var firstFunction = function () {
var promise = new Promise(function (resolve) { // may be redundant
setTimeout(function () {
app.post('/api/data', function (req, res) {
console.log(req.body);
// Get varibles from the post form
var email_user = req.body.email;
var first_name = req.body.fname;
var last_name = req.body.lname;
// res.send(email_user);
res.send(first_name + ' ' + last_name + ' ' + email_user);
//resolve when get the response
resolve({
data_email: email_user,
data_first_name: first_name,
data_last_name: last_name
});
});
}, 2000);
});
return promise;
};
Angular code (view)
<div class="form-group">
<label for="first-name">First Name*</label>
<input type="text" class="form-control col-sm-12" name="Fname" placeholder="Enter first name"
ng-model="formData.Fname"
ng-required="true">
<span ng-if="!myForm.Fname.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
</div>
<div class="form-group">
<label for="first-name">Last Name*</label>
<input type="text" class="form-control col-sm-12" name="Lname" placeholder="Enter last name"
ng-model="formData.Lname"
ng-required="true">
<span ng-if="!myForm.Lname.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
</div>
<div class="form-group">
<label for="first-name">Email*</label>
<input type="email" class="form-control col-sm-12" name="email" placeholder="Enter valid E-mail"
ng-model="formData.email"
ng-required="true">
<span ng-if="!myForm.email.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
</div>
<div class="form-group row">
<div class="col-xs-6 col-xs-offset-3">
<button type="submit" class="btn btn-block btn-info"
ng-disabled="!myForm.$valid">
Submit <span class="glyphicon glyphicon-circle-arrow-right"></span>
</button>
</div>
Angular code (controller)
FirstModule.controller('formController', function ($scope, $http) {
$scope.formData = {};
$scope.processForm = function (Fname, Lname, email) {
var data = {
fname: $scope.formData.Fname,
lname: $scope.formData.Lname,
email: $scope.formData.email
};
//Call the services
//Change http://localhost:8080/api/data to /api/data when live
$http.post('http://localhost:8080/api/data', JSON.stringify(data)).then(function (response) {
if (response.data)
$scope.formData = "Post Data Submitted Successfully!";
}, function (response) {
$scope.formData = "Post Data Submitted Failed";
$scope.statusval = response.status;
$scope.statustext = response.statusText;
$scope.headers = response.headers();
});
};
});

Angular validations: Restrict server request if user enters invalid email or password

<form name="LPform" novalidate>
<div class="form-row clearfix">
<label class="lbl-fld" style="margin-left: 12%;width:20%;">Email ID</label>
<input class="mob-adj-inpbx " type="email" name="uemail" ng-model="useremail" placeholder=" me#example.com" ng-required="true"/>
<div class="valid-chk validation-loginpopup" ng-show="LPform.uemail.$dirty && allow_Invalid">
<i style="font-size: 1.15em;padding:0px;" ng-class="{'false':'icon-close', 'true': 'icon-correct'}[LPform.uemail.$valid]" class="icon-correct"></i>
</div>
<div class="error-prompt" ng-show="LPform.uemail.$dirty && allow_Invalid">
</div>
</div>
<div class="form-row clearfix">
<label class="lbl-fld" style="margin-left: 12%;width:20%;">PASSWORD</label>
<input class="mob-adj-inpbx" type="password" name="upassword" ng-model="userpassword" placeholder=" password" ng-required="true"/>
<div class="valid-chk validation-loginpopup" ng-show="LPform.upassword.$dirty && allow_Invalid">
<i style="font-size: 1.15em;padding:0px;" ng-class="{'false':'icon-close', 'true': 'icon-correct'}[LPform.upassword.$valid]" class="icon-correct"></i>
</div>
<div class="error-prompt" ng-show="LPform.upassword.$dirty && allow_Invalid">
</div>
</div>
<div id="server_message" class="form-row clearfix basic-error-msg-loginpopup" ng-show="server_message">
{{server_message}}
</div>
<div class="btn-container clearfix mobile-adj" style="margin-left:17.2%;">
<div class="btn-wrap btn-loginpopup">
<input style="max-height:40px;width:121%;" type="submit" name="commit" value="LOGIN" ng-click="login_request()"/>
</div>
</div>
</form>
This part is displayed to the user and the inputs are validated using angular validations. All validations are working fine.
$scope.login_request = function(){
if(LPform.useremail.$valid && LPform.userpassword.$valid) {
$scope.allow_Invalid = "true";
$http({
method: 'POST',
url: '/users/home_login',
data: {email: $scope.useremail, password: $scope.userpassword}
}).success(function (response) {
console.log(response);
window.location = response.location;
}).error(function (response) {
console.log(response);
$scope.server_message = response.server_message;
});
}
else if(!LPform.useremail.$valid) {
$scope.allow_Invalid = "true";
$scope.server_message = "Please enter valid email.";
}
else if(!LPform.userpassword.$valid) {
$scope.allow_Invalid = "true";
$scope.server_message = "Please enter valid password.";
}
else{
$scope.allow_Invalid = "true";
$scope.server_message = "Request Failed.";
}
};
This part is in javascript file where I want to use the validations to decide whether to send a request to the server or not. The conditions I have used in the if else clause is not working, which I randomly tried btw. I am aware that I can disable Login button, however, I don't want to implement this that way.
I believe your problem is that the form name is bound to $scope and isn't a global variable.
In controller change
LPform
To
$scope.LPform

Categories