How to handle validation errors in laravel5.1 using ajax/jquery - javascript

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>');
});

Related

How to submit a form request using ajax without page refresh and return a message in laravel?

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);
});

Jquery Not Sending the Form to HTTP

I'm having some problems with Jquery/Ajax.
This is my code for the form :
<form class="form-auth-small" method="POST" id="form" enctype="multipart/form-data">
<div class="form-group">
<label for="signin-email" class="control-label sr-only">Email</label>
<input type="email" class="form-control" name="email" value="samuel.gold#domain.com" placeholder="Email">
</div>
<div class="form-group">
<label for="signin-email" class="control-label sr-only">Name</label>
<input type="text" class="form-control" name="name" value="John">
</div>
<div class="form-group">
<label for="signin-email" class="control-label sr-only">Phone</label>
<input type="text" class="form-control" name="phone" placeholder="938434928">
</div>
<div class="form-group">
<label for="signin-email" class="control-label sr-only"></label>
<input type="password" class="form-control" name="password" placeholder="****">
</div>
<div class="form-group">
<input name="image" type="file" />
</div>
<button type="submit" id="submit" class="btn btn-primary btn-lg btn-block">Register</button>
</form>
And this is my code to AJAX/Jquery:
<script>
$(".submit").on("click", function(e) {
var form = $("#form");
// you can't pass Jquery form it has to be javascript form object var formData = new FormData(form[0]);
console.log(formData);
$.ajax({
type: "POST",
url: '/user/signup/',
data: formData,
contentType: false, //this is requireded please see answers above processData: false, //this is requireded please see answers above //cache: false, //not sure but works for me without this error: function (err) { console.log(err);
success: function(res) {
console.log(res);
},
});
});
</script>
When i do console.log to check that from form i don't receive any value, and when i check in network i dont see any HTTP callback.
Your code doesn't work because you were using the class selector token . (dot) instead of the id selector token # hashtag. Further details can be found on the documentation
Change this instruction
$(".submit").on("click", function(e) // …
to
$("#submit").on("click", function(e) // …
You dont have submit class. You have id="submit"
$("#submit").on("click", function(e) {
Use this and it should work.
Also change type="submit" to type="button" or in your js code you need to add
e.preventDefault();

php javascript form serialize get data undefined index

I want to call input value from javascript
My home page code :
<form method="post" id="form">
<div class="row">
<div class="col-md-6">
<label for="f_name">First Name</label>
<input type="text" class="form-control" name="f_name "id="f_name" value="">
</div>
<div class="col-md-6">
<label for="l_name">Last Name</label>
<input type="text" class="form-control" name="l_name" id="l_name" value="">
</div>
</div>
....
javascript code :
$("#singup_btn").click(function(event){
event.preventDefault();
$.ajax({
url : "register.php",
method : "POST",
data : $("form").serialize(),
success : function(data){
alert(data);
}
})
})
...calling page code :
<?php
include "db.php";
$fname = $_POST["f_name"];
$lname = $_POST["l_name"];
...
echo $fname;
...error while click button, only last name (input) value defined
<br />
<b>Notice</b>: Undefined index: f_name in <b>D:\xampp\htdocs\shop\register.php</b> on line <b>5</b><br />
<br />
<b>Notice</b>: Undefined index: email in <b>D:\xampp\htdocs\shop\register.php</b> on line <b>7</b><br />
<br />
<b>Notice</b>: Undefined index: password in <b>D:\xampp\htdocs\shop\register.php</b> on line <b>8</b><br />
please someone help me?
I stuck like more than 4 hours on this. Im learning javascript n php, n still newbie. Please help. thanks.
You are missing a # You also have an error in your first input field.
<input name="f_name ">
shouldbe
<input name="f_name">
$("#singup_btn").click(function(event){
event.preventDefault();
$.ajax({
url : "register.php",
method : "POST",
data : $("#form").serialize(),
success : function(data){
alert(data);
}
})
})
try this code
$(document).on('click', '#singup_btn', function() {
$.ajax({
url : "register.php",
type : "POST",
data : $("#form").serialize(),
success : function(data){
alert(data);
}
});
});
Please remove type="submit" from submit button and add type="button". It will work!
Serializing the form with a space in name="f_name "id="f_name" forces a + to be appended to the serialized value. This is why its not being picked up correctly server side.
Expected server side value
f_name=asd&l_name=asd
Actual server side value
f_name+=asd&l_name=asd
see test below
$("button").click(function()
{
//output values before serialization
console.log( "Result of f_name");
console.log ($("#f_name").val() );
console.log( "Result of l_name");
console.log ($("#l_name").val() );
//output values after serialization
var serialized = $("form").serialize();
console.log( "Result: Notice how f_name has an appended + in its key");
console.log( "'" + serialized + "'");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="form">
<div class="row">
<div class="col-md-6">
<label for="f_name">First Name</label>
<input type="text" class="form-control" name="f_name "id="f_name" value="">
</div>
<div class="col-md-6">
<label for="l_name">Last Name</label>
<input type="text" class="form-control" name="l_name" id="l_name" value="">
</div>
</div>
<button type="button"> test </button>
</form>
Credit to Chris

saving inputs from pagedown editor in the database

I am using pagedown editor to replace textarea in an app i'm building but when i get sample codes as input from the editor and save it in the database, querying it out gives the result without any formatting.
I was expecting the result to the same as the preview of pagedown editor.
this is the form
{{Form::open(array('url'=>'profile/askquestion'))}}
<div class="form-group">
<label for="inputEmail" class="control-label">Title</label>
<div class="">
<input type="text" class="form-control" id="inputEmail" name="title" value="{{ Input::old('title') != NULL ? Input::old('title') : '' }}" placeholder="What's your programming question? Be specific." autofocus>
<span class="badge alert-danger">{{ ($errors->has('title') ? $errors->first('title') : '') }}</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="control-label"></label>
<div class="wmd-panel1">
<div id="wmd-button-bar-second" class="pagedown-swag"></div>
<textarea class="wmd-input form-control" name="body" id="wmd-input-second" rows="10"></textarea>
<span class="badge alert-danger">{{ ($errors->has('body') ? $errors->first('body') : '') }}</span>
</div><br ><hr>
<div id="wmd-preview-second" class="wmd-preview"></div><hr>
</div>
<div class="form-group">
<div class="">
<button type="submit" class="btn btn-primary pull-right">Post Your Question</button>
</div>
</div>
{{Form::close()}}
code for saving in the database
public function postAskquestion(){
$registerData = Input::all();
$registerRules = array(
'title' =>'required',
'body' =>'required',
);
$registerValidator = Validator::make($registerData,$registerRules);
if($registerValidator->fails()) {
return Redirect::back()->withInput()->withErrors($registerValidator);
}
if( $registerValidator->passes()) {
$question = new Question();
$question->title = Input::get('title');
$question->description = Input::get('body');
$question->user_id = Auth::user()->id;
$question->save();
return Redirect::to('/')->with('alertMessage',"question posted successfully.");
}
}
code for querying the contain
Route::get('question/{id}/{slug}', function ($id, $slug) {
$data['question'] = Question::find($id);
return View::make('site.question')->with($data);
});
code for displaying the contain
<div id="wmd-preview" class="wmd-panel1 wmd-preview">{{$question->description}}</div>
Help please
I know this is old post but here is how I am doing it
I'm saving the html from wmd-preview and save it with ajax
jQuery
var value = $("#wmd-preview).html();
$.ajax({
type: "POST",
url: "path/to-your-php-file",
dataType: "html",
data: {value: value} //The first value is the variable that you're sending to PHP
})
PHP
CONNECT TO YOUR DATABASE
$value = $_POST['value];
$query = mysqli_query($db,"INSERT INTO posts VALUES('$value'));

Angularjs - form validation

im trying to validate my users inputs and it works greate that the user can press the submit btn and it errors the input fields that is missing so the user know what input he is missing.
My problem is that it only works when i remove action="/buy" method="post" but i need it to normal submit the form when there is no errors.
How can i do that?
Im using this form validation with angularjs validate http://www.brentmckendrick.com/code/xtform/
<form name="userForm" ng-submit="submitForm(userForm.$valid)" xt-form novalidate>
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.fornavn.$invalid && !userForm.fornavn.$pristine }">
<label class="control-label" for="textinput">Fornavn <span class="star-color">*</span></label>
<input autocomplete="off" type="text" value="<?php echo set_value('fornavn'); ?>" name="fornavn" ng-model="fornavn" class="form-control" xt-validate required>
</div>
<button id="membership-box__payBtn" type="submit" name="betaling" class="btn btn-success text-uppercase">Go to payment</button>
</form>
Well you can use the $http service to send any type of request to server. When you actually do form post data is posted with content-type:'application/x-www-form-urlencoded'.
For your request if you can set the correct content-type and encode the object to send correctly, it would work. See this fiddle i created earlier that sends data to server as standard form post.
http://jsfiddle.net/cmyworld/doLhmgL6/
The relevant $http request looks like
$scope.update = function (user) {
$http({
method: 'POST',
url: 'https://mytestserver.com/that/does/not/exists',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: function (data) {
var postData = [];
for (var prop in data)
postData.push(encodeURIComponent(prop) + "=" + encodeURIComponent(data[prop]));
return postData.join("&");
},
data: user
});
You can model your input fields, and delegate each field to your model as:
<form name="userForm" ng-submit="submitForm(userForm.$valid)" xt-form novalidate>
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.fornavn.$invalid && !userForm.fornavn.$pristine }">
<input autocomplete="off" type="text" name="fornavn" ng-model="fornavn.input1" class="form-control" xt-validate required>
</div>
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.fornavn2.$invalid && !userForm.fornavn2.$pristine }">
<input autocomplete="off" type="text" name="fornavn2" ng-model="fornavn.input2" class="form-control" xt-validate required>
</div>
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.fornavn3.$invalid && !userForm.fornavn3.$pristine }">
<input autocomplete="off" type="text" name="fornavn3" ng-model="fornavn.input3" class="form-control" xt-validate required>
</div>
<button id="membership-box__payBtn" type="submit" name="betaling" class="btn btn-success text-uppercase">Go to payment</button>
</form>
And in your controller, send data using $http as:
var baseUrl=<yourBaseUrl>;
var url = baseUrl+'/buy';
var data = $scope.fornavn;
if(!$scope.userForm.$invalid){
$http.post(url, data).
success(function(data) {
if (data.error_msg) {
alert(data.error_msg);
}else{
alert("Successful! ");
}
}).
error(function(data) {
alert('error');
});
}

Categories

Resources