Stop previous ajax when new request is made using ajax - ajax

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

Related

Why does laravel $request->file return null?

I have a code that I am using in another app to upload files using Ajax which is working well.
Reusing this code in a new app with Jquery modal dialog is not working as expected. Below is my form:
{!! Form::open(['method' => 'POST', 'route' => ['auto-evaluation-documents.store'], 'files' => 'true', 'role' => 'form', 'id' => 'document_form']) !!}
<div class="modal-content" modal-transclude="" title="New Attachment">
<div class="form-group">
<input class="ng-scope" type="file" name="file" id="file">
</div>
</div>
{!! Form::close() !!}
Below is my modal dialog
var dialog;
dialog = $(".modal-content").dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons: {
"Save": uploadFile,
Cancel: function() {
$('#file').val('');
$('.c-fileupload__body').hide();
dialog.dialog( "close" );
}
},
close: function() {
//form[ 0 ].reset();
//allFields.removeClass( "ui-state-error" );
$('#file').val('');
$('.c-fileupload__body').hide();
}
});
$("#new_attachment_button").button().on( "click", function() {
dialog.dialog( "open" );
});
Below is the upload file function
function uploadFile() {
var document_form = $('#document_form');
var options = {
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
uploadProgress: OnProgress, //upload progress callback
data: { 'document_type': 'file', 'evaluation_session_id':'2'},
url: document_form.attr('action'),
type: 'post',
dataType: 'json'
};
// attach handler to form's submit event
document_form.ajaxSubmit(options);
// return false to prevent normal browser submit and page navigation
return false;
}
// pre-submit callback
function showRequest(formData, jqForm, options) {
var file_msg = $('#file_msg');
file_msg.empty().hide();
var value = $('#file').fieldValue();
if (!value[0]) {
message = "<li>Please select a file to upload</li>";
file_msg.append(message).show();
return false;
} else {
formData.push({ 'name': 'file', 'value': value[0]});
return true;
}
}
In Laravel controller, I do:
public function store(Request $request)
{
$file = $request->file('file');
$return['success'] = true;
$return['file_name'] = $file;
return response()->json($return, 200, ['Content-Type' => 'text/html']);
}
However, when I check my console, the result I get for $request->file('file') is null
If I do $request->get('file'), I get C:\fakepath\banner-image.jpg
Why is $request->file('file') not working even though my form has enctype="multipart/form-data" ?
I have applied other solutions here with no success. Please help
You should try to dump $request->all(); to see if error is on front-end. If you have file named "file" error is in front-end/Angular.

Form AJAX submit symfony doesn't work

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.

Laravel AJAX Image Upload Validation

I'm having trouble with validation on this AJAX POST for a file upload. Here's what I have so far. The 'required' validation keeps coming back telling me to select an image. When I console.log() the js variable with the image, it shows the filepath correctly.
View:
<form role="form" method="post" action="{{ route('profile.edit') }}" enctype="multipart/form-data">
<div class="form-group new-pic{{ $errors->has('profile-image') ? ' has-error' : '' }}">
<input type="file" id="newProfilePic" name="profile-image"/>
</div>
</form>
JS:
$('.btn-edit-profile-pic').click(function(e){
e.preventDefault();
var newPic = $('#newProfilePic').val();
$.ajax({
type: "POST",
url: "/profile-edit",
data: newPic,
error: function(data) {
var errors = $.parseJSON(data.responseText);
console.log(errors);
},
success: function() {
}
});
});
Controller:
if ($request->ajax())
{
$this->validate($request, [
'newPic' => 'required|image|max:4999'
],[
'required' => 'You must select an image',
'image' => 'The file must be an image',
'max' => 'The image file size must be less than 5mb'
]);
$extension = Input::file('profile-image')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension;
$image = Image::make(Input::file('profile-image'))
->orientate()
->resize(300, null, function ($constraint) {
$constraint->aspectRatio();
})
->save('images/profiles/'.$fileName);
Auth::user()->update([
'image_path' => $fileName,
]);
}
this is an intended behavior, you cant send upload file over XMLHTTPRequest, that is why you will always received the image file is required validation.
you can use an ajaxfileuploader plugins (They create a new form with in an iframe and submit it)
[http://www.sitepoint.com/10-jquery-ajax-file-uploader-plugins/]

Displaying validation errors in Laravel 5 with React.js and Ajax

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

laravel 5 and Ajax get data from database:

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>

Resources