I want to display a sweetalert message if registration is successful or fail (I wrote the sweetalert code in a jquery file) and included it inside the registration view page (it is included in the master.blade.php which all pages extend) but instead of displaying the sweetalert error or success message, it keeps displaying parsed json format message.
These are the files created.
custom_file.js
$(document).ready(function () {
var form = $('#registration');
form.submit(function (e) {
e.preventDefault();
$.ajax({
url: form.attr('action'),
type: "POST",
data: form.serialize(),
dataType: "json"
})
.done(function (response) {
if (response.success) {
swal({
title: "Hi " + response.name,
text: response.success,
timer: 5000,
showConfirmButton: false,
type: "success"
});
window.location.replace(response.url);
} else {
swal("Oops!", response.errors, 'error');
}
})
.fail(function () {
swal("Fail!", "Cannot register now!", 'error');
});
});
the registraion.blade.php file
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">AJAX Register</div>
<div class="panel-body">
<form class="form-horizontal" id="registration" method="POST" action="{{ url('users/register') }}" data-parsley-validate="">
{!! csrf_field() !!}
<div class="form-group">
<label class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input type="text" class="form-control" name="name" id="name" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" id="email" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password" id="password" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password_confirmation" id="password_confirmation" data-parsley-equalto="#password" required="">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary ladda-button" data-style="expand-left" data-size="s" data-color="green">
<i class="fa fa-btn fa-user"></i> Register
</button>
<div class="btn btn-md btn-primary ladda-button" data-style="expand-left" data-size="s" data-color="blue"> <i class="fa fa-facebook"></i> Login with Facebook </div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
and this is the RegisterController.php script
public function postRegister(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email|unique:users,email',
'name' => 'required|min:2',
'password' => 'required|alphaNum|min:6|same:password_confirmation',
]);
if ($validator->fails()) {
$message = ['errors' => $validator->messages()->all()];
$response = Response::json($message, 202);
} else {
// Create a new user
$user = new User([
'name' => $request->name,
'email' => $request->email,
'password' => $request->password,
'facebook_id' => $request->email
]);
$user->save();
Auth::login($user);
$message = ['success' => 'Thank you for joining us!', 'url' => '/', 'name' => $request->name];
$response = Response::json($message, 200);
}
return $response;
}
}
Here's some test code:
index.php
<!DOCTYPE html>
<html>
<head>
<title>SweetAlert2 test</title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.5/sweetalert2.min.css">
</head>
<body>
<form id="myForm" method="post" action="ajax.php">
<input type="text" name="uname">
<input type="submit" value="Submit">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.5/sweetalert2.min.js"></script>
<script>
$(document).ready(function () {
var form = $('#myForm');
form.submit(function (e) {
e.preventDefault();
$.ajax({
url: form.attr('action'),
type: "POST",
data: form.serialize(),
dataType: "json"
})
.done(function (response) {
if (response.data) {
swal({
title: "Message",
text: response.data,
timer: 5000,
showConfirmButton: false,
type: "success"
})
.then(function() {}, function() {
// redirect after alert has been displayed
window.location.replace("https://google.com");
});
} else {
swal("Oops!", "Registration error!", 'error');
}
})
.fail(function () {
swal("Fail!", "Network/Server error!", 'error');
});
});
});
</script>
</body>
</html>
ajax.php
<?php
$user = isset($_POST['uname']) ? $_POST['uname'] : "Anonymous";
$myJson = ["data" => "Hi " . $user . "! Thank you for joining us!"];
echo(json_encode($myJson));
This works fine! Compare it with your code to see if there's an error somewhere.
Related
I'm trying to submit a form request and store data without page refresh or redirect. And send success message to
#if (session('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
,I get white page after clicking submit button with the following response
{
"msg": "Setting created successfully"
}
The html Form:
<form method="POST" action="/mail/store" id="contactForm">
#csrf
<div style="display: flex;" class="name-email">
<div class="form-group col-sm-6 fl_wrap">
<input type="text" name="name" value="{{ old('name') }}" id="name"
class="form-control fl_input" placeholder="Name"
required>
</div>
<div class="form-group col-sm-6 fl_wrap">
<input type="text" name="email" value="{{ old('email') }}" id="email"
placeholder="Email"
class="form-control fl_input" required>
</div>
</div>
<div class="form-group col-sm-12 fl_wrap mt-2">
<textarea type="text" name="message" rows="7" value="{{ old('message') }}" id="message"
class="form-control fl_input" placeholder="message"
required></textarea>
</div>
<div class="form-group text-center mt-5">
<button type="submit" value="save" id="submit" class="btn btn-warning submit"
style="color: white;background: rgb(59, 199, 246); border-color: rgb(59, 199, 246); width: 140px;">
send
</button>
</div>
</form>
Js Code:
I think there's something wrong or missing with ajax code but I don't know where
<script src="/js/jquery.min.js"></script>
<script !src="" type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#contactForm').on('submit',function (e) {
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
var message = $('#message').val();
$.ajax({
type: "POST",
url: host+'/mail/store',
data: { name:name ,email:email,message:message},
success: function( msg ) {
$("body").append("<div>"+msg+"</div>");
}
});
$.post('contactForm', { name:name, email:email, message:message }, function () {
console.log(data);
$('#postRequestData').html(data);
});
});
});
store function in controller
public function store(Request $request)
{
$mail = new Mail();
$mail->name = $request->name;
$mail->mail = $request->email;
$mail->message = $request->message;
$mail->save();
$result = array(
'msg' => 'Setting created successfully' );
return Response::json($result);
}
Routes
Route::get('/mail','MailsController#create');
Route::post('/mail/store','MailsController#store');
Try this one:
$.post("{{ url('mail/store') }}", {
name, email, message, '_token': "{{ csrf_token() }}"
}, function(data) {
$('#postRequestData').html(data.message);
});
Im creating a validation now using laravel5.1 with ajax of jquery. Everything works fine. But, what I want is to display the errors each <inputs> just like when using validation without ajax. Please see my code below, and the picture for the sample output. I've also tried it with #if of blade(laravel), but not working.
Note: Im using bootstrap framework too.
<div class="row">
<div class="col-md-6">
<div id="result">
<ul></ul>
</div>
<form action="" method="post" id="create">
<div class="form-group">
<label for="name" class="control-label">Name</label>
<input type="text" name="name" id="name" class="form-control">
</div>
<div class="form-group">
<label for="description" class="control-label">Description</label>
<textarea name="description" id="description" cols="30" rows="10" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="type" class="control-label">Type</label>
<input type="text" name="type" id="type" class="form-control">
</div>
<div class="form-group">
<label for="price" class="control-label">Price</label>
<input type="text" name="price" id="price" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-success">
</div>
{{ csrf_field() }}
</form>
</div>
</div>
<script>
$(document).ready(function(){
var url = '{{ route('ajax-push') }}';
var token = '{{ csrf_token() }}';
$('#create').on('submit', function(){
$.ajax({
type: 'POST',
url: url,
data: { _token: token },
dataType: 'json',
success: function(data){
console.log(data);
},
error: function(data){
var errors = data.responseJSON;
$('#result').removeClass('alert').removeClass('alert-danger');
$('#result > ul').empty();
$.each(errors, function(i, item){
$('#result').addClass('alert').addClass('alert-danger');
$('#result > ul').append('<li>' + item + '</li>');
});
}
});
return false;
});
});
</script>
Controller
public function postAjaxCreate(Request $request){
$validator = $this->validate($request, [
'name' => 'required|max:255',
'description' => 'required|min:2',
'type' => 'required|max:255',
'price' => 'required|numeric'
]);
if($validator->fails()){
return response()->json($validator->messages(), 200)->with($validator->messages());
}
}
You need to pass the from data to the ajax request
data: $('#create').serialize(),
and most likely the response doesn't have a responseJSON property, and you are sending the data twice from, remove the with function in you php function
Add the errors to the page using something similar to the following js:
$.each(data, function(i, item){
$('#'+i).addClass('alert alert-danger');
('#'+i).after('<p>' + item + '</p>');
});
Aim: Continue to display any form validation errors through json callback
Problem: When I submit on the form with invalid input it shows an error message in a div element. If all inputs are valid it will process the ajax request and show a success message in a div element. After which, the form resets but the modal remain open. When I try to again validate the input in doesn't show any error message. When I try to test the valid input still the same no message shown.
In short: Ajax success function not working on the second time.
Here's my code:
Bootstrap Modal (where my form inputs placed)
<div class="modal fade" id='frmModal'>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class='close' data-dismiss='modal'>×</button>
<h4 class='title'>Add new data</h4>
</div>
<div class="modal-body">
<?php echo form_open('Employee/save',array('id'=>'frm', 'class'=>'form-horizontal')); ?>
<div id="message"></div>
<div class="form-group">
<label for='fname' class='col-md-3 control-label'>First Name:</label>
<div class="col-md-9">
<input type="text" name="fname" id='fname' class='form-control' placeholder='First Name...'>
</div>
</div>
<div class='form-group'>
<label for='lname' class='col-md-3 control-label'>Last Name:</label>
<div class="col-md-9">
<input type="text" name="lname" id='lname' class='form-control' placeholder='Last Name...'>
</div>
</div>
<div class='form-group'>
<label for='age' class='col-md-3 control-label'>Age:</label>
<div class="col-md-9">
<input type="text" name="age" id='age' class='form-control' placeholder='Age...'>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary action" type='submit'><i class='glyphicon glyphicon-floppy-disk'></i> Save Data</button>
</div>
<?php echo form_close(); ?>
</div>
</div>
</div>
</div>
Jquery Code:
$(document).on('submit','#frm',function(e){
e.preventDefault();
var form = $('#frm');
$.ajax({
url: form.attr('action'),
type: 'POST',
dataType: 'json',
encode: true,
data: form.serialize(),
success: function(data) {
if (!data.success) {
if (data.errors) {
$('#message').html(data.errors).addClass('alert alert-danger');
}
} else {
reloadData();
$('#message').html("<span class='glyphicon glyphicon-ok'></span> " + data.message).removeClass('alert alert-danger').addClass('alert alert-success');
setTimeout(function() {
$("#message").fadeTo(500, 0).slideUp(500, function() {
$(this).remove();
});
}, 3000);
$('#frm')[0].reset();
}
}
});
});
CodeIgniter Controller:
$this->form_validation->set_rules('fname','First Name', 'required|trim');
$this->form_validation->set_rules('lname','Last Name', 'trim|required');
$this->form_validation->set_rules('age','Age', 'trim|numeric|required');
if($this->form_validation->run()===FALSE)
{
$info['success'] = false;
$info['errors'] = validation_errors();
}
else
{
$info['success'] = true;
$data = array(
"firstname" => $this->input->post('fname'),
"lastname" => $this->input->post('lname'),
"age" => $this->input->post('age'),
);
$this->Employee_model->save('ci_table', $data);
$info['message'] = 'Successfully saved data';
}
$this->output->set_content_type('application/json')->set_output(json_encode($info));
}
I think I understand... The form still works but the messages do not appear? If so then try the below...
You are removing the #message element instead of clearing it... try:
$("#message").fadeTo(500, 0).slideUp(500, function() {
$(this).empty();
This way you are emptying the #message element instead of removing it completely..
Inserting into mysql using php file called via AJAX. Before insert statement php code performs select query to find duplicate records and continue to insert statement.
Issue: When calling php file from ajax. it executed twice and getting response as duplicate record.
well i tried error_log from insert function its called twice.
Trigger point of form validation
$("#load-modal").on("click","#addcountryformsubmitbtn",function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$form.submit();
});
This is how form submitted after validation:
}).on('success.form.bv', function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$.post($url,$form.serialize()).done(function(dte){ $("#load-modal").html(dte); });
});
using bootstrapvalidator, Core PHP, mysqli, Chrome Browser.
Actual JS:
$(document).ready(function() {
$php_self_country="<?php echo $_SERVER['PHP_SELF']."?pg=countrycontent"; ?>";
$("#country-content").load($php_self_country,loadfunctions);
$("#country-content").on( "click", ".pagination a", function (e){
e.preventDefault();
$("#country-loading-div").show();
var page = $(this).attr("data-page");
$("#country-content").load($php_self_country,{"page":page}, function(){
$("#country-loading-div").hide();
loadfunctions();
});
});
$("#country-content").on("click","#closebtn",function(e){
e.preventDefault();
$("#country-content").load($php_self_country,loadfunctions);
});
});
function loadfunctions(){
$("[data-toggle='tooltip']").tooltip();
$("#country-content").on("click","#addcountrybtn, #addcountrylargebtn",function(e){
e.preventDefault();
$.ajax({
url: $php_self_country,
type: "POST",
data: { 'addcountry':'Y' },
dataType: "html",
cache: false
}).done(function(msg){
$("#load-modal").html(msg);
$("#load-modal").modal('show');
$('input[type="radio"]').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal' });
modalvalidation();
}).fail(function() {
$("#load-modal").html( "Request Failed. Please Try Again Later." );
});
});
$("#country-content").on("click",".tools a",function(e){
e.preventDefault();
var recordid = $(this).attr("record-id");
$.ajax({
url: $php_self_country,
type: "POST",
data: { 'modifycountry':recordid },
dataType: "html",
cache: false
}).done(function(msg){
$("#load-modal").html(msg);
$("#load-modal").modal('show');
$('input[type="radio"]').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal' });
modalvalidation();
}).fail(function() {
$("#load-modal").html( "Request Failed. Please Try Again Later." );
});
});
$("#load-modal").on("click","#addcountryformsubmitbtn",function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$form.submit();
});
$("#load-modal").on("hide.bs.modal", function () {
window.location.href=$php_self_country_pg;
});
}
function modalvalidation(){
$('#addcountryform').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
[-------Validation part comes here----------]
}
}).on('success.form.bv', function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$.post($url,$form.serialize()).done(function(dte){ $("#load-modal").html(dte); });
});
}
HTML
this html is called on button click addcountrybtn via AJAX and write in to div load-modal which is in base html file.
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><i class="fa fa-exchange"></i> <?php echo COUNTRYLABEL; ?></h4>
</div>
<div class="modal-body">
<form role="form" method="POST" action="self.php" name="addcountryform" id="addcountryform" class="form-horizontal">
<div class="form-group">
<div class="col-xs-3">
<label for="countryname" class="pull-right">Country Name</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="countryname" placeholder="Enter Country Name">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="crncyname" class="pull-right">Currency Name</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="crncyname" placeholder="Enter Currency Name">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="crncycode" class="pull-right">Currency Code</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="crncycode" placeholder="Enter Currency Code">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="forrate" class="pull-right">Foreign Currency Rate<?php echo isset($icon)?$icon:''; ?></label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="forrate" placeholder="Enter Foreign Currency Rate.">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="taxpercent" class="pull-right">Tax %</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="taxpercent" placeholder="Enter Tax Percentage">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer clearfix">
<button type="button" class="btn btn-danger pull-right" id="addcountryformsubmitbtn">Add</button>
</div>
</div>
Note:- in Database point of view code works as expected.
Couple of things that I have seen could possibly be the cause.
If you are using IE, I have seen that perform a GET immediately before doing a POST (to the same URL, with the same data being sent over), so it could be worth trying to check for that on your server (and ignore the GET)
Something else it maybe to add the following to the end of your button click events after the AJAX call (actually, normally I'd put the first line at the top with the prevent default, and the return statement obviously goes very last)...
e.stopImmediatePropagation();
return false;
I'm pretty new in web development and I know this might sound like a very simple question but I'm trying to add a login functionality in a bootstrap template.
The .js with the template validates the contents of the text and such. I'm trying to add a POST function in the submitHandler.
$(document).ready(function() {
$('#login-form').validate({
focusInvalid: false,
ignore: "",
rules: {
txtusername: {
minlength: 2,
required: true
},
txtpassword: {
required: true,
}
},
invalidHandler: function (event, validator) {
//display error alert on form submit
},
errorPlacement: function (label, element) { // render error placement for each input type
$('<span class="error"></span>').insertAfter(element).append(label)
var parent = $(element).parent('.input-with-icon');
parent.removeClass('success-control').addClass('error-control');
},
highlight: function (element) { // hightlight error inputs
},
unhighlight: function (element) { // revert the change done by hightlight
},
success: function (label, element) {
var parent = $(element).parent('.input-with-icon');
parent.removeClass('error-control').addClass('success-control');
},
submitHandler: function(form) {
var username=$("#txtusername").val();
var password=$("#txtpassword").val();
var dataString = 'username='+username+'&password='+password;
$.ajax({
type: "POST",
url: "login.php",
data: dataString,
cache: false,
success: function(data){
if(data) {
window.location.href = "index.php";
} else {
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
});
});
<?php
if (isset($_POST['submit'])) { // Form has been submitted.
$username = ($_POST['username']));
$password = ($_POST['password']));
.
.
.
.
.
}
else
{
echo "Doesnt Work";
}
?>
.
.
.
<form id="login-form" class="login-form" action="#" method="post">
<div class="row">
<div class="form-group col-md-10">
<div id="error"></div>
<label class="form-label">Username</label>
<div class="controls">
<div class="input-with-icon right">
<i class=""></i>
<input type="text" name="txtusername" id="txtusername" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-10">
<label class="form-label">Password</label>
<span class="help"></span>
<div class="controls">
<div class="input-with-icon right">
<i class=""></i>
<input type="password" name="txtpassword" id="txtpassword" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-10">
<button class="btn btn-primary btn-cons pull-right" type="submit">Login</button>
</div>
</div>
</form>
Thanks in advance!
Please check the documention of data sent to the server. You can use object to send your data. In the link above, there are some examples how to send data to server.
var dataString = {username: username, password: password}