I'm trying to make user registration process via ajax in laravel. But I'm unable to do that.
Routes
Route::get('/register', 'Auth\AuthController#getRegister')->name('register');
Route::post('/register', 'Auth\AuthController#postRegister')->name('postRegister');
HTML form
<form action="{{ route('postRegister') }}" method="POST" id="registerForm">
<h4>REGISTER NOW</h4>
<hr><br>
<input type="text" name="name" class="form-control" placeholder="Name">
<br>
<input type="number" name="student_id" class="form-control" placeholder="Student ID">
<br>
<input type="email" name="email" class="form-control" placeholder="Email address">
<br>
<input type="number" name="phone" class="form-control" placeholder="Phone no">
<br>
<input type="password" name="password" id="password" class="form-control" placeholder="Choose password">
<br>
<input type="password" name="password_confirmation" class="form-control" placeholder="Confirm password">
<br>
<div class="row">
<div class="col-md-12 text-right">
<button type="submit" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect" id="registerButton"><span id="regLoader" style="display: none"><i class="fa fa-spinner fa-pulse"></i><span class="sr-only">Loading...</span> </span>
Register</button>
</div>
</div>
{{ csrf_field() }}
</form>
JS
$('#registerForm').submit(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '/register',
data: $(this).serialize(),
dataType: 'json',
success: function(data){
},
error: function(data){
}
});
});
I think you need to change your code like:
jQuery(function($) {
$('#registerForm').submit(function(e){
e.preventDefault();
$.ajax({
url: $form.attr('action'),
data: $(this).serialize(),
dataType: 'json',
success: function(data){
},
error: function(data){
}
});
});
});
Your code looks perfect.
1) Maybe some form validation goes failed and which prevents data to be stored in the database.
Comment out your server side validations(if you have) and check again.
2) If this didn't work, comment out dataType: 'json' in AJAX and check again.
Also, print console.log() in your success method of ajax to troubleshoot.
If none of it work, show your controller code.
Thanks
1) Can you able to see the xmlhttp request passing to the server through network tab of chrome/mozilla.
If so there is no error in your ajax/front end,
2) Before going to route write a anonymous function in the action route to see whether the request comes till the route
Route::post('/register', function(Illuminate\Http\Request, $request) {
dd($request);
});
If You have Auth Routes enabled then there is a possibility
for the request to point RegistrationController inside Auth folder, do a
dd($request) inside the constructor of that controller. hence you can figure it out whether the request is coming there.
3) Try regenerating the APP key (It is just a try if nothing works)
4) Try writing a new post route and call that route in ajax to post the data to the server,if that works the old route which you wrote may overridden by some other route.
Try in the above order , you will somewhere catch the error.
Related
Hello I am a newbie to all these forms and php and javascript.
I just made some modifications to this code. But I can't make it run a php file.
I don't know why? Please help. It ran successfully before my modifications.
The javascript function for sending data to sendotp.php
function send_otp(){
var mobile=jQuery('#mobile').val();
var email=jQuery('#email').val();
jQuery.ajax({
url:'sendotp.php',
type:'post',
data:{'mobile='+mobile,'email='+email}
success:function(result){
if(result=='1'){
jQuery('.second_box').show();
jQuery('.first_box').hide();
}
if(result=='not_exist'){
jQuery('#email_error').html('Please enter valid mobile or E-mail');
}
}
});
}
The javascript function for checking otp is
function submit_otp(){
var otp=jQuery('#otp').val();
var eotp=jQuery('#eotp').val();
jQuery.ajax({
url:'checkotp.php',
type:'post',
data:{'otp='+otp,'eotp='+eotp},
success:function(result){
if(result=='yes'){
window.location='savedata.php'
}
if(result=='Please enter correct otp.'){
jQuery('#otp_error').html('Please enter valid otp');
}
}
});
}
The html code is
<div class="login-form">
<form method="post">
<h2 class="text-center">Alumni Authorization</h2>
<div class="form-group first_box">
<input type="text" id="mobile" class="form-control" placeholder="10 Digit Mobile No" required="required">
<span id="email_error" class="field_error"></span>
<input type="text" id="email" class="form-control" placeholder="Enter E-mail" required="required">
<span id="email_error" class="field_error"></span>
</div>
<div class="form-group first_box">
<button type="button" class="btn btn-primary btn-block" onclick="send_otp()">Send OTP</button>
</div>
<div class="form-group second_box">
<input type="text" id="otp" class="form-control" placeholder="Mobile OTP" required="required">
<span id="otp_error" class="field_error"></span>
<input type="text" id="eotp" class="form-control" placeholder="E-mail OTP" required="required">
<span id="otp_error" class="field_error"></span>
</div>
<div class="form-group second_box">
<button type="button" class="btn btn-primary btn-block" onclick="submit_otp()">Submit OTP</button>
</div>
</form>
Sorry folks, it was a simple error.
The corrected part is
jQuery.ajax({
url:'checkotp.php',
type:'post',
data:{'otp':otp,'eotp':eotp},
Try changing the format of data you send to the back end
as a json format. It binds values related to the given
property.
function submit_otp(){
var otp=jQuery('#otp').val();
var eotp=jQuery('#eotp').val();
jQuery.ajax({
url:'checkotp.php',
type:'post',
data:{otp: otp, eotp: eotp}, // Declare data in JSON format
success:function(result){
if(result=='yes'){
window.location='savedata.php'
}
if(result=='Please enter correct otp.'){
jQuery('#otp_error').html('Please enter valid otp');
}
}
});
}
Please use like below code
jQuery.ajax({
url:'sendotp.php',
type:'POST',
data:{mobile:mobile,email:email}
success:function(result){
console.log(result);
if(result=='1'){
jQuery('.second_box').show();
jQuery('.first_box').hide();
}
if(result=='not_exist'){
jQuery('#email_error').html('Please enter valid mobile or E-mail');
}
}
});
It may be related to the way you're sending your data in your ajax call.
You're sending a string rather than a set of parameters.
Try this syntax :
// code
type:'post',
data:{
'otp':otp,
'eotp':eotp
},
success:function(result){
//rest of code
EDIT : I forgot the quotes on the parameters. It says "function undefined" because it tries to evaluate otp as a function while it's just a variable.
I have a very simple form that has an input field for first name. I captured the form data and transmitted it via ajax to a PHP page using the standard jQuery posting method. However, I am not able at all get any responses from the PHP page that any data was captured on the server-side. I am not sure what I have done wrong or what is missing.
Here is my code.
Form:
<form action="process.php" method="POST">
<div class="form-group">
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
<div class="d-none" id="firstName_feedback">
<p>Please enter a first name.</p>
</div>
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
Here is my Jquery Ajax call:
<script>
$(document).ready(function() {
$('form').submit(function(event) {
var formData = $("form").serialize();
console.log(formData);
$.ajax({
type: 'POST',
url: 'form.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
</script>
And here is my PHP page:
if(isset($_POST['formData']))
$ajaxData = ($_POST['formData']);
echo $ajaxData;
{
}
In your Ajax function, you're passing the contents of formData to the server, though not as formData but as their original input name.
In this case, you have:
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
The input's name is firstName, so you need to call $_POST['firstName'] instead of $_POST['formData'].
if (isset($_POST['firstName'])) {
$ajaxData = $_POST['firstName'];
echo $ajaxData;
}
The same applies for any other field you would have in your form, so for example, having another input with the name lastName means you'd have to call $_POST['lastName'] to access it.
There were also some misplaced brackets and parentheses in the PHP code which I accommodated above.
I have an ASP.NET MVC project and currently I am using ViewData["ResultMessage"] to show the result of a form (which is done after the user submits & refreshes the page).
I want to do it right after he clicks submit (without refreshing the page). So I have to use Javascript for that, which I am new with. No experience what so ever.
How my form looks like is this:
<form id="contactForm" method="post" action="..">
<div class="field half first">
<label for="Name">Name</label>
<input type="text" name="Name" id="Name" placeholder="Your name" required />
</div>
<div class="field half">
<label for="Email">Email</label>
<input type="email" name="Email" id="Email" placeholder="Your email" required />
</div>
<div class="field">
<label for="Message">Message</label>
<textarea name="Message" id="Message" rows="5" placeholder="Your message" required minlength="20"></textarea>
</div>
<input type="submit" value="Send Message" />
<p>#ViewData["ContactActionResult"]</p>
</form>
You can see the result is displayed with Razor using ViewData. Now I want to do it without refreshing the page and learn JS on the way.
What I have tried so far:
$(function () {
$("button").click(function (e) {
e.preventDefault()
$.ajax({
type: "POST",
url: "/Receiver",
data: car,
datatype: "html",
success: function (data) {
alert("Congratulations, it worked!");
$('#contactForm').html(data);
},
error: function(data) {
alert("Failed.");
}
});
});
});
But I am not sure if I did something wrong or simply not implementing it right. I have the above function inside <script> here </script> in my HTML page. Nothing happens when I click the submit button on the form.
If it is an ajax call, It is best if you return a JSON response . You can use the Request.IsAjaxRequest() to determine whether the request is normal form request or ajax call.
You should also consider using to the PRG pattern. After successfully saving, you should do a redirect to a GET action where you can render a view, instead of returning to the same view with a viewbag message. If you want to pass some message to the new view/action, use TempData instead of ViewData.
[HttpPost]
public ActionResult Receiver(string name, string Email)
{
// Your existing code to save
if(Request.IsAjaxRequest())
{
return Json(new { status = "success", message = "Created successfully" });
}
// Normal form submit. So let's follow PRG pattern
TempData["ResultMessage"] = "Created successfully";
return RedirectToAction("Index");
}
You can also put a try/catch and return a json like this for error usecase
return Json(new { status = "error", message = "some serious error" });
In Index action/view, you can read TempData["ResultMessage"] and display to user.
Now, for the ajax usecase, in your current view, you can add a div to show the message
<form id="contactForm" method="post" asp-action="Receiver">
<div id="msg"></div>
<div class="field half first">
<label for="Name">Name</label>
<input type="text" name="Name" id="Name" placeholder="Your name" required />
</div>
<div class="field half">
<label for="Email">Email</label>
<input type="email" name="Email" id="Email" required />
</div>
<div class="field">
<label for="Message">Message</label>
<textarea name="Message" id="Message" rows="5"
placeholder="Your message" required minlength="20"></textarea>
</div>
<input type="submit" value="Send Message" />
</form>
and now in your ajax call's success callback, check the json response coming back from server and show the message property as needed. If you are putting the script inside the razor view file, make sure you are putting it inside a Scripts section so that it will be evaluated in the proper order (After jQuery is loaded, assuming you load jQuery before calling RenderSection("scripts") inside the layout)
#section Scripts
{
<script>
$(function (){
$("#contactForm").submit(function (e){
e.preventDefault()
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: car,
success: function (data){
if (data.status === "success")
{
$('#msg').html(message);
}
//to do : handle statuss=="error" as needed
},
error: function (data)
{
alert("Failed.");
}
});
});
});
</script>
}
For asp.net core, you can write a IsAjaxRequest method in your base controller and use that. jQuery will add X-Requested-With header with value XMLHttpRequest for your ajax calls.
protected bool IsAjaxRequest()
{
return Request.Headers["X-Requested-With"] == "XMLHttpRequest";
}
I am working as junior web master maybe that's why I have come with a simple question here. I have designed a single page application for client which has contact form at the end of page, validation is done using bootstrap but to send form data to mail id only method I know is using php with action directing different page. since my website is single page application i would like a popup on successful submission to mail id
Below is the HTML code for the contact form
<form class="form-inline" data-toggle="validator" role="form" method="post" id="enquiry" action="index.php">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3">Name</label>
<input type="text" class="form-control" name="name" id="exampleInputEmail3" placeholder="Name" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword3">Mobile Number</label>
<input type="text" class="form-control" id="exampleInputPassword3" name="mobile" placeholder="Mobile Number" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword3">Email Id</label>
<input type="email" class="form-control col-lg-12" id="exampleInputPassword3" name="email" placeholder="Email Id" required>
</div>
<br/> <br/>
<div class=" col-lg-12 form-group">
<textarea cols="80" placeholder="Enter query Here" class="form-control" name="query" id="address" data-error ="Please Enter Your Query" required></textarea><br/><br/>
</div>
<button style="background-color:#f15a24; color:#FFF;" name="submit" id="submit" type="submit">Submit</button>
</form>
Can use php to send form data and still get a pop up in same page?
Or do I need to use jquery to send data and pop-up?
It would be great if somebody helps me out with code, thanks in advance
Updated
below(index.php page) i have added the code what you have given,
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.easing.min.js"></script>
<script src="js/jquery.fittext.js"></script>
<script src="js/wow.min.js"></script>
<script src="js/creative.js"></script>
<script src="js/validator.js"></script>
<script>
$(document).ready(function(){
$("#enquiry").on("submit",function(e){
e.preventDefault();
var dataString = $('#enquiry').serialize();
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function(ret) {
if(ret === "Success"){ alert("Success"); }else{ alert("Failed"); }
//Failure message if ret is false
});
}
});
});
</script>
Add this js to your script
<script>
$(document).ready(function(){
$("#enquiry").on("submit",function(e){
e.preventDefault();
var dataString = $('#enquiry').serialize();
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function(ret) {
if(ret === "Success")
{
alert("Success");
} else {
alert("Failed");
}
}
});
}
);
});
submit.php contains the code to send and exit it with the success (true) or failure (false) message. That will be caught in ret variable.
Edited
This will be more detailed answer I was looking for, I thought it be would be helpful for somebody so I have answered my own question as an alternative solution, check out the links below.
Show submitted form response on the same page. (No Reload)
http://www.9lessons.info/2009/04/submit-form-jquery-and-ajax.html
I'm working on phonegap, basically its like making mobileapps crossplatform by using HTML, JS and CSS. On the device i currently have the JS and the HTML (form) in same document.
What I'm trying to do is to pass email and password to my server, and then process it there through a login. I've tested the login script on the server and it works with hardcoded data. So I'm guessing somewhere when sending the data from the device its failing.. I'm fairly new to JS too.
I tried to hardcode the data in the AJAX but it doesnt seem to work. Preferebly I would like to use something like var pdata = $('#form').serialize(); or something else if its better.
Any ideas?
EDIT: Forgot to say that the PHP on the server auto submits by using JS when $_POST is set (isset)
The form
<form id="form" onsubmit="dologin()">
<div class="form-group">
<label for="email">Epost</label>
<input type="email" class="form-control" name="email" value="" placeholder="Epost">
</div>
<div class="form-group">
<label for="password">Passord</label>
<input type="password" class="form-control" name="password" value="" placeholder="Passord">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember_me">
Husk meg
</label>
</div>
<button type="submit" class="btn btn-primary">Logg inn</button>
</form>
The javascript
<script>
function dologin() {
//var pdata = $('#form').serialize();
//alert(pdata);
$.ajax({
type: 'POST',
data: {email:"test#test.no",password:"test"},
url: 'LINK',
success: function(data) {
alert(data);
},
error: function() {
alert("error");
}
});
return false;
};
</script>
The PHP
<form id="form" method="post">
<!-- {{ Form::label('email', 'Email Address') }} -->
<div class="form-group">
<input type="text" name="email" value="<?php if(isset($_POST["email"])) echo $_POST['email'];?>">
</div>
<div class="form-group">
<!-- {{ Form::label('password', 'Password') }} -->
<input type="text" name="password" value="<?php if(isset($_POST["password"])) echo $_POST['password'];?>">
</div>
</form>
Are you able to hit your server via through phonegap?
If no then please check your config.xml for white list urls - change access control property to
access origin = "*"
Hopeful you will be able to hit your server with data.
You can use weinre to debug your app. That way you will be able to see if the request was placed from the app or not.
http://people.apache.org/~pmuellr/weinre/docs/latest/Home.html