Why sending data by Ajax jQuery fail - javascript

I'm trying to create a pop-up form login with Ajax jQuery, but It's always fail to send data. I've many ways on Internet that I can find but nothing change. Please take a look and help me. Thanks so much:
This is my form:
<form id="loginform" name="loginform" method="POST">
{{ csrf_field() }}
<div class='modal-body-left' >
<div class="form-group">
<input type="text" id="username" name="username" placeholder="Tên đăng nhập" value="" class="form-control login-field">
<i class="fa fa-user login-field-icon"></i>
</div>
<div class="form-group">
<input type="password" id="password" name="password" placeholder="Mật khẩu" value="" class="form-control login-field">
<i class="fa fa-lock login-field-icon"></i>
</div>
<div class="checkbox">
<label>
<input type="checkbox" style="margin-top: -8px"> Nhớ mật khẩu
</label>
Quên mật khẩu?
</div>
<button class="btn btn-success modal-login-btn" id="loginbutton" name="loginbutton" style="background-color: #47a49a; background: #fec10f;" type="submit">Đăng nhập</button>
</div>
</form>
This is my js:
$("#loginbutton").click(function(event) {
event.preventDefault();
var username = $("#username").val();
var password = $("#password").val();
var data ={"email":username, "password":password};
alert(data.email);
// alert(data.password);
$.ajax(
{
url: '{{url('/')}}/loginHandling',
type: 'POST',
data: {'email': "ruoitrau95#gmail.com", 'password':"tuyen12345"},
dataType: 'json',
success: function(data)
{
alert(data);
alert("done");
}
}
)
.fail(function(data) {
alert("fail");
});
});
And this is controller:
public function loginHandling() {
$email = Input::get('email');
$password = Input::get('password');
$check $this->pages->checkLogin($email, $password);
echo "alert(In loginHandling)";
if ($check) {
$name = $this->pages->getNameFromMail($email);
Session::put('logined', true);
Session::put('email', $email);
Session::put('name', $name);
die json_encode(array("success"=>"true"));
} else {
die json_encode(array("success"=>"false"));
}
}
I'm working on Laravel framework so my url is defined:
Route::post('/loginHandling',['as'=>'loginHandling','uses'=>'LoginController#loginHandling']);
Thanks again for your time

You need to pass the CSRF token in order for Laravel to process the request. There are a few ways to do this - try this one:
Form:
<meta name="_token" content="{{ csrf_token() }}" />
<form id="loginform" name="loginform" method="POST">
<div class='modal-body-left' >
<div class="form-group">
<input type="text" id="username" name="username" placeholder="Tên đăng nhập" value="" class="form-control login-field">
<i class="fa fa-user login-field-icon"></i>
</div>
<div class="form-group">
<input type="password" id="password" name="password" placeholder="Mật khẩu" value="" class="form-control login-field">
<i class="fa fa-lock login-field-icon"></i>
</div>
<div class="checkbox">
<label>
<input type="checkbox" style="margin-top: -8px"> Nhớ mật khẩu
</label>
Quên mật khẩu?
</div>
<button class="btn btn-success modal-login-btn" id="loginbutton" name="loginbutton" style="background-color: #47a49a; background: #fec10f;" type="submit">Đăng nhập</button>
</div>
</form>
Javascript:
$("#loginbutton").click(function(event) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
event.preventDefault();
var username = $("#username").val();
var password = $("#password").val();
$.ajax(
{
url: '{{url('/')}}/loginHandling',
type: 'POST',
data: {'email': username, 'password': password},
dataType: 'json',
success: function(data)
{
alert(data);
alert("done");
}
}
)
.fail(function(data) {
alert("fail");
});
});
You should now be able to access the submitted data in your controller with $request->all().

Related

Laravel Ajax form post shows 500 internal server error. I tried solving with a lot of solution but still not working

I want to post data with ajax request but it said internal server. I tried adding meta data and X-CSRF-TOKEN but still not working. Please take a look at my code
Ajax Code:
$("#firstForm").on("submit", (e)=>{
e.preventDefault()
let dataString = $(this).serialize();
let email = document.getElementById("emailInput").value
let password = document.getElementById("passwordInput").value
var token = $('meta[name="csrf-token"]').attr('content');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': token
}
});
$.ajax({
type: 'POST',
url: '/register/create',
data: dataString,
dataType: 'json',
}).done(function(response){
console.log("Done");
});
return false;
})
HTML Form:
<form class="mt-5 text-start" id="firstForm" method="post">
<label class="text-white main-font">Email</label>
<input type="email" name="email" id="emailInput" class="form-control mb-2" placeholder="Enter your email here">
<label class="text-white main-font">Password</label>
<input type="password" name="password" id="passwordInput" class="form-control password mb-2" placeholder="Enter your password here">
<i class="d-none fa-solid fa-eye fs-5 eye" onclick="eyeOpen()"></i>
<i class="fa-solid fa-eye-slash fs-5 eye" onclick="eyeClose()"></i>
<div class="form-check text-start mb-5">
<input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">
<label class="form-check-label text-white" for="flexCheckDefault">
I've agree to the terms and conditions!
</label>
</div>
<button id="firstBtn" class="mb-3 mt-5 btn btn-lg btn-danger text-white main-font w-100">Next</button>
</form>
Laravel Route:
Route::post('register/create', [AccountController::class, 'create']);
Laravel Controller:
public function create(Request $request) {
$user = new User;
$user->email = $request->email;
$user->password = Hash::make($request->password);
$user->save();
return view('accounts.login');
}
The Error:
[2022-11-22 13:18:23] local.ERROR: SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value (SQL: insert into `users` (`email`, `password`, `updated_at`, `created_at`) values (?, $2y$10$uwsmx9lDw4z9a0tGwUjBWeNM8zfNEkoa7oREGdCBgxTkF3Owlo5Uy, 2022-11-22 13:18:23, 2022-11-22 13:18:23)) {"exception":"[object] (Illuminate\\Database\\QueryException(code: HY000): SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value (SQL: insert into `users` (`email`, `password`, `updated_at`, `created_at`) values (?, $2y$10$uwsmx9lDw4z9a0tGwUjBWeNM8zfNEkoa7oREGdCBgxTkF3Owlo5Uy, 2022-11-22 13:18:23, 2022-11-22 13:18:23)) at C:\\xampp\\htdocs\\dating\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php:712)
when creating a new user the Name field is required and the error is also saying that the name doesn't have a value.
try adding a filled in your form for name and send it via ajax. like this
<form class="mt-5 text-start" id="firstForm" method="post">
#csrf
<label class="text-white main-font">Name</label>
<input type="text" name="name" id="name" class="form-control mb-2" placeholder="Enter your Name here">
<label class="text-white main-font">Email</label>
<input type="email" name="email" id="emailInput" class="form-control mb-2" placeholder="Enter your email here">
<label class="text-white main-font">Password</label>
<input type="password" name="password" id="passwordInput" class="form-control password mb-2" placeholder="Enter your password here">
<i class="d-none fa-solid fa-eye fs-5 eye" onclick="eyeOpen()"></i>
<i class="fa-solid fa-eye-slash fs-5 eye" onclick="eyeClose()"></i>
<div class="form-check text-start mb-5">
<input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">
<label class="form-check-label text-white" for="flexCheckDefault">
I've agree to the terms and conditions!
</label>
</div>
<button id="firstBtn" class="mb-3 mt-5 btn btn-lg btn-danger text-white main-font w-100">Next</button>
</form>
and also change your controller like this
public function create(Request $request) {
$user = new User;
$user->name= $request->name;
$user->email = $request->email;
$user->password = Hash::make($request->password);
$user->save();
return view('accounts.login');
}
change your ajax like this
let dataString = $(this).serialize();
$.ajax({
type: "post",
url: '/register/create',
data: dataString, // serializes the form's elements.
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data['message']);
},
});
I checked the laravel.log file's error messages. Found that Jquery serialization return empty string. So, I custom coded the serialize function to get the closet dataString as Jquery.
let dataString = "email=" + document.getElementById("emailInput").value + "&password=" + document.getElementById("passwordInput").value

The Ajax in JQuery is not executing

I want to make two post requests to the back end, Flask. I successfully got the login request yesterday, because I can see the information printed in the browser console. But After adding the second click event, both are failed.
And the "login" post and "search" post request failed differently, because for the first I can see "clicked" in the console, but for the second nothing.
I also used request.get_data() and request.get_json(), but got nothing. I have used an easier way to get post request from Flask, like request.form. However, I am still very confused what's wrong with the code.
Thank you for offering help!
Below is the .js file
$(document).ready(function () {
// login, for sending the email and password
$(function () {
$("form#formLogin").on('click','button#buttonLogin', function () {
console.log('clicked');
$.ajax({
url: "http://127.0.0.1:5000",
type: "POST",
data: $('form#formLogin').serialize(),
contentType: 'json; charset=UTF-8',
cache: false,
success: function (response) {
console.log(response.d);
console.log("login info sent");
},
fail: function (response) {
console.log(response.d);
console.log("failed");
}
})
});
})
// search, for executing sql
$(function () {
$('form#formSearch').on('click', 'button#buttonSearch', function () {
console.log('begin sending select');
$.ajax({
url: "http://127.0.0.1:5000",
type: "POST",
data: $('form#formSelect').serialize(),
contentType: 'json; charset=UTF-8',
cache: false,
success: function (response) {
console.log(response.d);
console.log("search info sent");
},
fail: function (response) {
console.log(response.d);
console.log("failed");
}
})
});
})
})
Below is .html, the login part
<form id="formLogin" class="formLogin" method="post">
<h1 class="h3 mb-3 font-weight-normal">Please Login</h1>
<input type="hidden" name="post" class="form-control" value="login"/>
<label for="inputEmail" class="sr-only">Email:</label>
<input type="email" id="inputEmail" name="userEmail" class="form-control" placeholder="Email address" required autofocus/>
<label for="inputPassword" class="sr-only">Password:</label>
<input type="password" id="inputPassword" name="userPwd" class="form-control" placeholder="Password" required/>
<label for="buttonLogin" class="sr-only">Login:</label>
<button id="buttonLogin" class="btn btn-lg btn-primary btn-block" value="login">login</button>
</form>
Below is .html, the search part
<form id="formSearch" method="post">
<input type="hidden" name="post" class="form-control" value="select"/>
<div class="input-group mb-3 mt-4">
<label for="selectRecord" class="sr-only">SelectRecord:</label>
<input type="text" id="selectRecord" name="selectRecord" class="form-control" placeholder="" aria-label="" aria-describedby="basic-addon1" required autofocus/>
<div class="input-group-prepend">
<label for="buttonSearch" class="sr-only">Search:</label>
<button id="buttonSearch" name="buttonSearch" class="btn btn-outline-secondary search" value="search">Search</button>
</div>
</div>
<label for="checkBoxRegion" class="sr-only">Region:</label>
<input id="checkBoxRegion" name="checkBoxRegion" type="checkbox"> <span class="checkboxFontSize">Region</span>
<label for="checkBoxProductName" class="sr-only">ProductName:</label>
<input id="checkBoxProductName" name="checkBoxProductName" type="checkbox"> <span class="checkboxFontSize">Product Name</span>
<label for="checkBoxStoreName" class="sr-only">StoreName:</label>
<input id="checkBoxStoreName" name="checkBoxStoreName" type="checkbox">
<span class="checkboxFontSize">Store Name</span>
</form>

How to validate login form on button click jquery/javascript?

How to validate login form on button click.When i click on button then its calling javascript function button click,i need to first validate form,required then click button work.required not working.I want to validate before button click.
<form id="loginform" class="form-vertical" method="post">
<div class="control-group normal_text"> <h3><img src="~/Content/img/logo.png" alt="Logo" /></h3></div>
<div class="control-group">
<div class="controls">
<div class="main_input_box">
<span class="add-on bg_lg"><i class="icon-user"> </i></span>
<input type="text" id="txtusername" class="form-control required" placeholder="Username" name="username" required />
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<div class="main_input_box">
<span class="add-on bg_ly"><i class="icon-lock"></i></span>
<input type="password" id="txtpassword" class="form-control" name="password" placeholder="Password" required />
<br />
<label style="color:red;font-size:15px;display:none;" id="errormsg">Incorrect Username or Password</label>
</div>
</div>
</div>
<div class="form-actions">
<span class="pull-left">Lost password?</span>
<span class="pull-right"><input type="submit" value="Login" id="btnlogin" class="flip-link btn btn-success" /></span>
</div>
</form>
<script type = "text/javascript"
src = "https://code.jquery.com/jquery-1.12.4.js" >
</script>
<script type = "text/javascript" >
$(document).ready(function() {
$("#btnlogin").click(function () {
var user = new Object();
user.Username = $('#txtusername').val();
user.Password = $('#txtpassword').val();
if (user != null) {
$.ajax({
type: "POST",
url: "/Admin/Login",
data: JSON.stringify(user),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (recordcount) {
if (recordcount != null) {
alert(recordcount);
if (recordcount <= 0) {
document.getElementById("errormsg").style.display = 'block';
}
else {
document.getElementById("errormsg").style.display = 'none';
}
}
else {
alert("Something went wrong");
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
}
});
});
</script>
<html>
<head>
<title>a</title>
</head>
<body>
<form id="loginform" class="form-vertical" method="post">
<div class="control-group normal_text">
<h3>
<!-- <img src="~/Content/img/logo.png" alt="Logo" /> -->
</h3>
</div>
<div class="control-group">
<div class="controls">
<div class="main_input_box">
<span class="add-on bg_lg">
<i class="icon-user"> </i>
</span>
<input type="text" id="txtusername" class="form-control required" placeholder="Username" name="username" required />
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<div class="main_input_box">
<span class="add-on bg_ly">
<i class="icon-lock"></i>
</span>
<input type="password" id="txtpassword" class="form-control" name="password" placeholder="Password" required />
<br />
<label style="color:red;font-size:15px;display:none;" id="errormsg">Incorrect Username or Password</label>
</div>
</div>
</div>
<div class="form-actions">
<span class="pull-left">
Lost password?
</span>
<span class="pull-right">
<input type="submit" value="Login" id="btnlogin" class="flip-link btn btn-success" />
</span>
</div>
</form>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#loginform").submit(function (e) {
var user = new Object();
user.Username = $('#txtusername').val();
user.Password = $('#txtpassword').val();
if (user != null) {
$.ajax({
type: "POST",
url: "/Admin/Login",
data: JSON.stringify(user),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (recordcount) {
if (recordcount != null) {
alert(recordcount);
if (recordcount <= 0) {
document.getElementById("errormsg").style.display = 'block';
}
else {
document.getElementById("errormsg").style.display = 'none';
}
}
else {
alert("Something went wrong");
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
}
debugger
return false;
//e.preventDefault();
});
});
</script>
</body>
</html>
You have to add onFocusOut() method in textbox, so when you entered the text in the textbox and goes to next textbox, focusout() method will call, and in the focusout() method, you have to write your validation logic.
For example, you can enable your login button, if text entered in the textbox is validated. Otherwise your button remain disabled.

without page reload how to insert the data using below javascript

Using e.preventDefault(); values not insert in to database,if comment e.preventDefault(); data inserted in to database, without page reload how to insert the data using below javascript code please suggest me
Insert form
<form class="form-horizontal msg_fixed_bottom send_message_form" method="POST" role="form" action="<?php echo base_url(); ?>index.php/Profile_cntrl/supplier_communication">
<div class="panel-footer" id="myForm" >
<div class="input-group submit_group">
<input id="messagee" name="messagee" type="text" class="form-control input-sm chat_input" placeholder="Write your message here..." />
<span class="input-group-btn">
<button class="btn btn-primary btn-sm" id="submit" name="submit">Send</button>
</span>
</div>
</div>
</form>
script
<script>
$(document).ready(function () {
scrollDown();
$("#submit").click(function (e) {
e.preventDefault();
var message = $("#messagee").val();
$('#chat_log').append('<div class="row msg_container base_sent active"><div class="col-md-10 col-xs-10"><div class="messages msg_receive"><p>' + message + '</p></div></div></div>');
$('#messagee').val('');
scrollDown();
});
});
function scrollDown() {
$('.msg_container_base').animate({scrollTop: $('.msg_container_base').prop("scrollHeight")}, 0);
}
</script>
HTML
<form id="data_form" class="form-horizontal msg_fixed_bottom send_message_form">
<div class="panel-footer" id="myForm" >
<div class="input-group submit_group">
<input id="messagee" name="messagee" type="text" class="form-control input-sm chat_input" placeholder="Write your message here..." />
<span class="input-group-btn">
<button class="btn btn-primary btn-sm" id="submit" name="submit" type="submit">Send</button>
</span>
</div>
</div>
JavaScript
$(document).ready(function(){
$('#data_form').on('submit', function(e){
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/Profile_cntrl/supplier_communication',
data: form_data,
success:function(data)
{
alert('Success');
},
error:function()
{
alert('failed');
}
});
e.preventDefault();
});
});
insert form
<form class="form-horizontal msg_fixed_bottom send_message_form" id="data_form" method="POST" role="form" action="#">
<div class="panel-footer" id="myForm" >
<div class="input-group submit_group">
<input id="messagee" name="messagee" type="text" class="form-control input-sm chat_input" placeholder="Write your message here..." />
<span class="input-group-btn">
<button class="btn btn-primary btn-sm" id="submit" name="submit">Send</button>
</span>
</div>
</div>
</form>
javascript
<script>
$(document).ready(function(){
$('#data_form').on('submit', function(e){
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/Profile_cntrl/supplier_communication',
data: form_data,
success:function(data)
{
var message = $("#messagee").val();
$('#chat_log').append('<div class="row msg_container base_sent active"><div class="col-md-10 col-xs-10"><div class="messages msg_receive"><p>' + message + '</p></div></div></div>');
scrollDown();
function scrollDown() {
$('.msg_container_base').animate({scrollTop: $('.msg_container_base').prop("scrollHeight")}, 0);
}
},
error:function()
{
alert('failed');
}
});
e.preventDefault();
});
});
</script>
You can use ajax for submitting the data without page reload.
<script type="text/javascript">
// Ajax post
$(document).ready(function() {
$(".submit").click(function(event) {
event.preventDefault();
var messagee= $("input#messagee").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "your_controller/your_function",
dataType: 'json',
data: {
messagee: messagee
},
success: function(res) {
if (res) {
// Show Entered Value
//sussess message here
}
}
});
});
});
Your Controller:
// This function call from AJAX
public function your_function() {
$data = array(
'messagee' => $this->input->post('messagee')
);
//Either you can print value or you can send value to database
echo json_encode($data);
}
your form:
<form class="form-horizontal msg_fixed_bottom send_message_form" method="POST" role="form" id="msg-form">
<div class="panel-footer" id="myForm" >
<div class="input-group submit_group">
<input id="messagee" name="messagee" type="text" class="form-control input-sm chat_input" placeholder="Write your message here..." />
<span class="input-group-btn">
<input type="submit" class="btn btn-primary btn-sm" id="submit" name="submit" value="Submit">
</span>
</div>
</div>
</form>
your ajax
<script>
$(document).ready(function(){
$("#msg-form").submit(function(e){
e.preventDefault();
var msg = $("#messagee").val();
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/Profile_cntrl/supplier_communication',
data: {msg:msg},
success:function(data)
{
alert('SUCCESS!!');
},
error:function()
{
alert('fail');
}
});
});
});
</script>
I think this will work fine. Now add your additional append functionality in the success area by yourself. thanks.

submit php form to google docs

This is my html form submitting using jquery
<form target="_self" onsubmit="" action="javascript: postContactToGoogle()" method="post" onsubmit="">
<span id="form-error"><?php if(isset($_SESSION['alert'])){ echo $_SESSION['alert']; unset($_SESSION['alert']);} ?></span>
<div class="form-group">
<p class="no-margin bottom5">YOUR NAME (required)</p>
<input type="text" class="form-control" name="name" id="name" required>
</div>
<div class="form-group">
<p class="no-margin bottom5">YOUR EMAIL (required)</p>
<input type="email" class="form-control" name="email" id="email" required>
</div>
<div class="form-group">
<p class="no-margin bottom5">MESSAGE</p>
<textarea class="form-control" rows="5" id="message" name="message"></textarea>
</div>
<button class="btn btn-default" type="submit">Send</button>
<div style="width: 100%; display: block; float: right; padding-top: 15px;">
<div class="requestSubmited" style="display:none; text-align: center;">Your request has been sent!</div>
</div>
</form>
This is my jquery
function postContactToGoogle(){
var name = $('#name').val();
var email = $('#email').val();
var message = $('#message').val();
$.ajax({
url: "https://docs.google.com/a/mapplinks.com/forms/d/1r3SISt7ocWE32s7LJxBOOteMeMV-JTy166pH87hxwF4/formResponse",
data: {"entry.2028011364" : name, "entry.1745855979" : email, "entry.919224434": message},
type: "POST",
dataType: "xml",
statusCode: {
0: function (){
alert("saved0");
//Success message
},
200: function (){
alert("saved");
//Success Message
}
}
});
}
This is my form and jquery which i have been using.Im getting response 0 but google form is not getting updated.Please help me in this
Just follow that guide:
https://wiki.base22.com/pages/viewpage.action?pageId=72942000
This will helps.

Categories