I have simple form:
{{ Form::open(array('id' => 'frm')) }}
<div class="form-group">
{!! Form::label('id','id:'); !!}
{!! Form::text('id',null,['class' => 'form-control']); !!}
</div>
<div class="form-group">
{!! Form::submit('Update',['class' => 'btn btn-primary form-control']); !!}
{!! Form::close() !!}
I want to post the values from the form input fields to the controller then in the controller mthod run a query on the database for the id value from the form. Finally, using ajax, show the results of the DB query and if there are no results show a message alerting the user.
I have tried this:
<script>
$("document").ready(function(){
$("#frm").submit(function(e){
e.preventDefault();
var customer = $("input[name=postal]").val();
$.ajax({
type: "POST",
url : "http://laravel.test/ajax",
data : dataString,
dataType : "json",
success : function(data){
}
}, "json");
});
});//end of document ready function
</script>
I have tried a couple of ways to get the post data in the controller but have had no success.
---Problem 1:
There is problem when I try to use this in route:
Route::post('ajax', function() { // callback instead of controller method
$user = App\User::find(\Input::get('id');
return $user; // Eloquent will automatically cast the data to json
});
I get sintax error,on second line for (;)
Also, I try to get data in controller and than print them:
if(Request::ajax()) {
$data = Input::all();
print_r($data);die;
}
ROUTES.PHP
Route::post('/',
['as' => 'first_form', 'uses' => 'TestController#find']);
Route::get('/', 'TestController#index');
Route::post('ajax', function() { // callback instead of controller method
$user = App\User::find(\Input::get('id');
return $user; // Eloquent will automatically cast the data to json
});
Function:
public function ajax()
{
//
// Getting all post data
if(Request::ajax()) {
$data = Input::all();
print_r($data);die;
}
}
I found a couple more ways to send data from view to controller,but even woant show posted data. I check with fire-bug,there is posted value in post request
It appears you're passing your ajax method a variable that doesn't exist. Try passing it the form data directly and see if that yields any results, you can do this with the serialize method:
$("#frm").submit(function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url : "http://laravel.test/ajax",
data : form.serialize(),
dataType : "json",
success : function(data){
if(data.length > 0) {
console.log(data);
} else {
console.log('Nothing in the DB');
}
}
}, "json");
});
The ajax call has console.log in it now so it will output anything returned to it in the console.
routes.php (an example)
Route::post('ajax', function() { // callback instead of controller method
$user = App\User::find(\Input::get('id'));
return $user; // Eloquent will automatically cast the data to json
});
Please bear in mind I am just putting the code as an example as you didn't put your controller code in the question.
EDIT
I'm going to make a really simple example that works for you. I have made a fresh install of laravel and coded this and it's working fine for me. Please follow along carefully.
app/Http/routes.php
<?php
// route for our form
Route::get('/', function() {
return view('form');
});
// route for our ajax post request
Route::post('ajax', function() {
// grab the id
$id = \Input::get('id');
// return it back to the user in json response
return response()->json([
'id' => 'The id is: ' . $id
]);
});
resources/views/form.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Ajax Example</title>
</head>
<body>
{!! Form::open(['url' => 'ajax', 'id' => 'myform']) !!}
<div class="form-group">
{!! Form::label('id','id:') !!}
{!! Form::text('id', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Update',['class' => 'btn btn-primary form-control']); !!}
</div>
{!! Form::close() !!}
<div id="response"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$("document").ready(function(){
// variable with references to form and a div where we'll display the response
$form = $('#myform');
$response = $('#response');
$form.submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url : $form.attr('action'), // get the form action
data : $form.serialize(), // get the form data serialized
dataType : "json",
success : function(data){
$response.html(data['id']); // on success spit out the data into response div
}
}).fail(function(data){
// on an error show us a warning and write errors to console
var errors = data.responseJSON;
alert('an error occured, check the console (f12)');
console.log(errors);
});
});
});
</script>
</body>
</html>
Related
I am using Toast tui calendar https://nhn.github.io/tui.calendar/latest/ and I have an issue with ajax calling. It works correct except one thing, when I try to get data with the same option more than one times returns the new response but also still return the data of the previous response. please help me how can i resolve that thank u.
I think that there is something that I've missed.
controller
public function getBookingSlot(Request $request){
$userBookings = Booking::where('room_id',$request->room_id)->where('booking_status',1)->get();
foreach($userBookings as $booking){
$events [] = [
'id' => $booking->id,
'calendarId' => $booking->id,
'title' => 'Booked',
'category' => 'time',
'dueDateClass' => '',
'start' => $booking->start_datetime,
'end' => $booking->end_datetime,
];
}
return \Response::json([
'events' => $events ?? null
]);
}
html view
<div class="card mb-5 ">
<div id="calendar" style="height: 800px;"></div>
</div>
jquery
$(".butonSubmit").click(function(){
if($(".carousel-item").hasClass('active') ){
let room_id = $(".carousel-item.active").find('.room_id').val();
$.ajax({
url: "{{route('get-booking-slot')}}",
type:"POST",
data:{
"_token": "{{ csrf_token() }}",
room_id:room_id,
},
success:function(response){
calendar.createSchedules(
result = response.events
);
console.log(result);
},
error: function(response) {
console.log(error);
},
});
}
});
It is because you do not update the calendar after new request. Previous values are still there on the calender
I have a user schedule record that I can update easily without one form field called disabled_dates. disabled_dates is setup to store an array of dates a user can add one at a time. What I did was add a form field with its own button using a javascript function disable() in the onclick attribute to update the record.
<div class='input-group text-center'>
{!! Form::text('disabled_dates', null , ['class' => 'form-control text-center datetimepicker15', 'id' => 'disable_date', 'placeholder' => '']) !!}
<span class="input-group-btn">
<button type="button" onclick="disable();" class="btn btn-fab btn-round btn-success">
<i class="material-icons">add</i>
</button>
</span>
Then created the disable(); like so
function disable() {
var CSRF_TOKEN = '{{ csrf_token() }}';
var disabled_date = document.getElementById('disable_date').value;
$.ajax({
type:'PUT',
url:'/schedule',
data:{_token: CSRF_TOKEN, blocked_date: disabled_date},
success:function(response) {
console.log(response);
}
});
}
The controller function used is
public function add_blocked_day(Request $request)
{
$schedule = User::find(auth()->user()->id)->schedule;
$current_blocked_dates = $schedule->disabled_dates;
$schedule->disabled_dates = $current_blocked_dates. ','.$request->blocked_date;
$schedule->save();
exit;
}
All Im getting now is too many redirects. The solution Im thinking is to seperate disabled_dates and enclose in its own form tags, because its calling the original form route somehow
I got it to work by changing the function to this
$(document).on("click", ".add-day" , function() {
var CSRF_TOKEN = '{{ csrf_token() }}';
var disabled_date = document.getElementById('disable_date').value;
$.ajax({
type:'POST',
url:'schedule/blocked-day',
data:{_token: CSRF_TOKEN, blocked_date: disabled_date},
success:function(response) {
console.log(response);
}
});
});
I don't understand why my AJAX submit doesn't work.
I have two forms in my the controller:
$intervento = new Intervento();
$form = $this->createForm(InterventoType::class, $intervento);
$form->handleRequest($request);
$user = new User();
$form_user = $this->createForm(UserType::class, $user);
$form_user->handleRequest($request);
if ($form_user->isSubmitted() && $form_user->isvalid()) {
$response = new Response();
return $this->json(array('risultato' => ' ok'));
}
if ($form->isSubmitted() && $form->isvalid()) { }
return $this->render('interventi/collaudo.html.twig', array(
'form' => $form->createView(),
'form_utente' => $form_user->createView(),
));
In my twig file I start the form and it works:
{{form_start(form_utente,{'attr':{'id':'form-utente'}})}}
.....
<div class="row">
<div class="input-field col s4">
<input type="submit" class="waves-effect waves-light btn-large" value="Submit">
</div>
</div>
</div>
</div>
{{form_end(form_utente)}}
</div>
In my JavaScript file:
$('#form-utente').submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
alert(data['risultato']);
// setTimeout(function() { window.location.href = "#" }, 500);
// setTimeout(function() { $("#form-stufa").click() }, 500);
},
error: function(){
}
});
});
I also have another AJAX call in this JavaScript, but I don't this gives the problem.
The submit button sometimes returns Error 500, sometimes an undefined alert.
I think it doesn't go to submit in the controller but I don't know why.
Can anyone help me?
Use the FOSJsRoutingBundle for js urls. You need expose your routing.
I have a myitems($filter) method in a ItemsController that loads the myitems.blade view.
The view has list of items as label and text box to get number of items ($items is passed from myitems method to myitems view and there is a model form binding on items model as well)
I have a select box that has options 1. All, 2. Expired and 3.New
When I change the selection I want to have get new $items from the controller and recreate the form with new items list.
I am using using jquery to alert that the selection is changed. but I am not able to figure out how will I be able to call myitems($filter) from ajax and redirect to create the items.blade page.
Route
//Note the ? in parameter, it says parameter is optional
Route::get('/myitems/{filter?}',
['as' => 'myitems.list', 'uses' => 'ItemController#myitems']
);
Controller
...
public function myitems(Request $request, $filter = null)
{
if (empty($filter)) $filter=1;
$items = Item::where('item_type', $filter)->get();
// if ajax call just return the partial that displays the list
if ($request->ajax()) {
return view('_itemlist', compact('items'));
}
// passed as options to input select
$filters= [
'All' => '0',
'New' => '1',
'Expired' => '2'
];
return view('itempagewith_defaultitemlist', compact('items','filters'));
}
...
View
view itempagewith_defaultitemlist.blade.php
<div class="container">
{!! Form::model($myitems, ['route' => 'myitems.list', 'class'=>'form-horizontal', 'files' => true]) !!}
<div id="filterselectbox">
<div class="form-group">
{!!Form::label('filterselectbox','*Filter:',['class'=>'control-label']) !!}
{!!Form::select('filterselectbox', $filters, null, ['class'=>'form-control ']) !!}
</div>
</div>
{!! Form::close() !!}
<div id="item-container">
#include('_itemlist')
</div>
<script>
$('#filterselectbox').change(function() {
var id = $('#filterselectbox').val();
var ajaxurl = '{{route('myitems', ':id')}}';
ajaxurl = ajaxurl.replace(':id', id);
$.ajax({
url: ajaxurl,
type: "GET",
success: function(data){
$data = $(data); // the HTML content that controller has produced
$('#item-container').hide().html($data).fadeIn();
}
});
});
</script>
</div>
partial view _itemlist.blade.php
<ul>
#foreach ($items as $item)
<li>{{ $item->name }}</li>
#endforeach
</ul>
I am running a Laravel 5 application that has its main view rendered using React.js. On the page, I have a simple input form, that I am handling with Ajax (sending the input back without page refresh). I validate the input data in my UserController. What I would like to do is display error messages (if the input does not pass validation) in my view.
I would also like the validation errors to appear based on state (submitted or not submitted) within the React.js code.
How would I do this using React.js and without page refresh?
Here is some code:
React.js code:
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
var SignupForm = React.createClass({
getInitialState: function() {
return {email: '', submitted: false, error: false};
},
_updateInputValue(e) {
this.setState({email: e.target.value});
},
render: function() {
var text = this.state.submitted ? 'Thank you! Expect a follow up at '+email+' soon!' : 'Enter your email to request early access:';
var style = this.state.submitted ? {"backgroundColor": "rgba(26, 188, 156, 0.4)"} : {};
return (
<div>
{this.state.submitted ? null :
<div className="overall-input">
<ReactCSSTransitionGroup transitionName="example" transitionAppear={true}>
<input type="email" className="input_field" onChange={this._updateInputValue} ref="email" value={this.state.email} />
<div className="button-row">
<a href="#" className="button" onClick={this.saveAndContinue}>Request Invite</a>
</div>
</ReactCSSTransitionGroup>
</div>
}
</div>
)
},
saveAndContinue: function(e) {
e.preventDefault()
if(this.state.submitted==false) {
email = this.refs.email.getDOMNode().value
this.setState({email: email})
this.setState({submitted: !this.state.submitted});
request = $.ajax({
url: "/user",
type: "post",
data: 'email=' + email + '&_token={{ csrf_token() }}',
data: {'email': email, '_token': $('meta[name=_token]').attr('content')},
beforeSend: function(data){console.log(data);},
success:function(data){},
});
setTimeout(function(){
this.setState({submitted:false});
}.bind(this),5000);
}
}
});
React.render(<SignupForm/>, document.getElementById('content'));
UserController:
public function store(Request $request) {
$this->validate($request, [
'email' => 'Required|Email|Min:2|Max:80'
]);
$email = $request->input('email');;
$user = new User;
$user->email = $email;
$user->save();
return $email;
}
Thank you for your help!
According to Laravel docs, they send a response with 422 code on failed validation:
If the incoming request was an AJAX request, no redirect will be
generated. Instead, an HTTP response with a 422 status code will be
returned to the browser containing a JSON representation of the
validation errors
So, you just need to handle response and, if validation failed, add a validation message to the state, something like in the following code snippet:
request = $.ajax({
url: "/user",
type: "post",
data: 'email=' + email + '&_token={{ csrf_token() }}',
data: {'email': email, '_token': $('meta[name=_token]').attr('content')},
beforeSend: function(data){console.log(data);},
error: function(jqXhr, json, errorThrown) {
if(jqXhr.status === 422) {
//status means that this is a validation error, now we need to get messages from JSON
var errors = jqXhr.responseJSON;
var theMessageFromRequest = errors['email'].join('. ');
this.setState({
validationErrorMessage: theMessageFromRequest,
submitted: false
});
}
}.bind(this)
});
After that, in the 'render' method, just check if this.state.validationErrorMessage is set and render the message somewhere:
render: function() {
var text = this.state.submitted ? 'Thank you! Expect a follow up at '+email+' soon!' : 'Enter your email to request early access:';
var style = this.state.submitted ? {"backgroundColor": "rgba(26, 188, 156, 0.4)"} : {};
return (
<div>
{this.state.submitted ? null :
<div className="overall-input">
<ReactCSSTransitionGroup transitionName="example" transitionAppear={true}>
<input type="email" className="input_field" onChange={this._updateInputValue} ref="email" value={this.state.email} />
<div className="validation-message">{this.state.validationErrorMessage}</div>
<div className="button-row">
<a href="#" className="button" onClick={this.saveAndContinue}>Request Invite</a>
</div>
</ReactCSSTransitionGroup>
</div>
}
</div>
)
}