Ajax call with Laravel Form - ajax

Hello can someone please help me because I wanted to use ajax in my laravel form, when everytime I hit 'CREATE POST' button, the table contains all my posts will hide and then the form will show, and when clicking the submit button in the form the table will then show with its new data inserted below the table and the form will hide. I have a code but it is not working.
Controller Code:
public function store(Request $request)
{
//validate the data
$this->validate($request, array(
'title' => 'required|max:255',
'slug' => 'required|alpha_dash|min:5|max:255|unique:posts,slug',
'category_id' => 'required|integer',
'body' => 'required',
'featured_image' => 'image|nullable|max:1999'
));
//store in the database
$post = new Post;
$post->title = $request->title;
$post->slug = $request->slug;
$post->category_id = $request->category_id;
$post->body = Purifier::clean($request->body);
//Save Our Image
if ($request->hasFile('featured_image')) {
$image = $request->file('featured_image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/'. $filename);
Image::make($image)->resize(800, 400)->save($location);
$post->image = $filename;
}
$post->save();
return response()->json($post);
// Session::flash('success', 'The blog post was succesfully saved!');
// //redirect to another page
// return redirect()->route('posts.show', $post->id);
}
Route:
Route::resource('/posts', 'PostController');
Route::post('/addpost', 'PostController#store');
Form Code:
{!! Form::open(['id' => 'form-post', 'method' => 'POST', 'route' => 'posts.store', 'data-parsley-validate' => '', 'files' => true]) !!}
{{ csrf_field() }}
<div class="form-group">
<label class="control-label" for="title">Title:</label>
<input type="text" name="title" class="form-control" data-error="Please enter title." required />
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label class="control-label" for="title">Slug:</label>
<input type="text" name="slug" class="form-control" data-error="Please enter title." required />
<div class="help-block with-errors"></div>
</div>
{{ Form::label('category_id', 'Category') }}
<select id="add-category" class="form-control" name="category_id">
#foreach($categories as $category)
<option value='{{ $category->id }}'>{{ $category->name }}</option>
#endforeach
</select>
{{ Form::label('featured_image', 'Upload Featured Image:', ['class' => 'form-spacing-top']) }}
{{ Form::file('featured_image',["id" => 'add-image', "class" => 'form-control-file']) }}
{{ Form::label('body', 'Post Body:') }}
{{ Form::textarea('body', null, array('id' => 'add-body', 'class' => 'form-control')) }}
{{ Form::button('Create Post', array('id' => 'submit-post', 'class' => 'btn btn-success btn-lg btn-block', 'style' => 'margin-top: 20px;'))}}
{!! Form::close() !!}
</div>
</div>
Ajax Code:
$(document).on('click', '.create-post', function() {
$('.create-form').css('display','block');
$('.posts-table').css('display','none');
});
$('#submit-post').click(function(e) {
e.preventDefault();
var action = $('#form-post').attr('route');
var title = $("#form-post").find("input[name='title']").val();
var slug = $("#form-post").find("input[name='slug']").val();
var category_id = $("#add-category").val();
var featured_image = $("#add-image").val();
var body = $("#add-body").val();
$.ajax({
type : 'POST',
url : "/addpost",
headers: {
'X-CSRF-TOKEN' : $('input[name="_token"]').val()
},
data : {
title: title,
slug: slug,
category_id: category_id,
featured_image: featured_image,
body: body
},
success: function(data){
$('.create-form').css('display','none');
$('.posts-table').css('display','block');
$('.table tbody').append("<tr id='" + data.id + "' class='item'><th>" + data.id + "</th><td>" + data.title + "</td><td>" + data.body + "</td><td>date</td><td><button class='show-modal btn btn-success' data-id='" + data.id + "' data-title='" + data.title + "' data-slug='" + data.slug + "' data-category='" + data.category_id + "' data-image='" + data.featured_image + "' data-body='" + data.body + "'><span class='glyphicon glyphicon-eye-open'></span> Show</button><button class='edit-modal btn btn-info' data-id='" + data.id + "' data-title='" + data.title + "' data-slug='" + data.slug + "' data-category='" + data.category_id + "' data-image='" + data.featured_image + "' data-body='" + data.body + "'><span class='glyphicon glyphicon-edit'></span> Edit</button><button class='delete-modal btn btn-danger' data-id='" + data.id + "' data-title='" + data.title + "' data-slug='" + data.slug + "' data-category='" + data.category_id + "' data-image='" + data.featured_image + "' data-body='" + data.body + "'><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>");
console.log(data);
}
});
});

It's not enough information about the error.
Try dd() in your controller & check it in [F12 -> Network].
And since you're using ajax to sending request, there no need to define options (action, route) in Form. remove it.

Related

Laravel Inertia Dynamic Form Validation

I have a button that when clicked, adds some inputs to a form:
<a #click="addNewText()" class="items-center px-4 py-2 bg-gray-800 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-700 active:bg-gray-900 focus:outline-none focus:border-gray-900 focus:shadow-outline-gray transition ease-in-out duration-150">
<i class="far fa-2x fa-plus-square"></i>
</a>
I am using Laravel 8 and Inertia and want to validate my form. When I try to validate, the form inputs don't show up in $request->input('texts'); if the form is empty. If the form inputs are filled, then they show up?
Here is my controller code:
public function index()
{
$texts = [];
$texts = collect(
[
['skill_level' => null, 'word_count' => null, 'title' => null, 'description' => null, 'category' => null]
]
);
//dd($texts->toJson());
//return the view
return Inertia::render('Client/OrderFormBuilder/GiantIndex', [
"allTexts" => $texts->toJson()
]);
}
public function setOrderDetails(Request $request)
{
$texts = $request->input('texts.*');
$rules = [];
$messages = [];
for ($i = 0; $i < count($texts); $i++)
{
$rules['texts[' . $i . '][skill_level]'] = 'required';
$rules['texts[' . $i . '][word_count]'] = 'required';
$rules['texts[' . $i . '][category]'] = 'required';
//$rules['texts.' . $i . '.title'] = 'required|string|min:5|max:10000';
//$rules['texts.' . $i . '.description'] = 'required|string|min:10|max:10000000';
}
for ($i = 0; $i < count($texts); $i++)
{
$messages['texts[' . $i . '][skill_level].required'] = 'Please Enter Your Desired Skill Level.';
$messages['texts[' . $i . '][word_count].required'] = 'Please Enter Your Desired Word Count.';
$messages['texts[' . $i . '][category].required'] = 'Please Enter Your Desired Category.';
/*
$messages['texts.' . $i . '.title.required'] = 'A Title Is Required For Your Text.';
$messages['texts.' . $i . '.title.string'] = 'Please Enter A Valid Title For Your Text.';
$messages['texts.' . $i . '.title.min'] = 'Please Enter A Minimum Of 5 Characters For Your Title.';
$messages['texts.' . $i . '.title.max'] = 'Please Enter A Maximum Of 10000 Characters For Your Title.';
$messages['texts.' . $i . '.description.required'] = 'A Description Is Required For Your Text.';
$messages['texts.' . $i . '.description.string'] = 'Please Enter A Valid Description For Your Text.';
$messages['texts.' . $i . '.description.min'] = 'Please Enter A Minimum Of 10 Characters For Your Description.';
$messages['texts.' . $i . '.description.max'] = 'Please Enter A Maximum Of 10000000 Characters For Your Description.';
*/
}
//dd($texts, $rules, $messages);
Validator::make($texts, $rules, $messages)->validateWithBag('updateOrderFormBuilder');
}
And here is my Vue form template code:
<div v-for="(singleText, index) in form.texts" v-bind:key="index" class="shadow sm:rounded-md sm:overflow-hidden mt-5">
<div class="bg-white py-6 px-4 space-y-6 sm:p-6">
<div class="col-span-6 sm:col-span-4">
<div>
<label class="block font-medium text-sm text-gray-700" for="skill_level">Skill Level</label>
<input :id="'skill_level_' + index" :name="'texts[' + index + '][skill_level]'" type="text" class="form-input rounded-md shadow-sm mt-1 block w-full" v-model="singleText.skill_level" :autocomplete="'texts[' + index + '][skill_level]'" />
<div v-if="form.error('texts[' + index + '][skill_level]')">
<p class="text-sm text-red-600">
{{ form.error('texts[' + index + '][skill_level]') }}
</p>
</div>
<label class="block font-medium text-sm text-gray-700" for="word_count">Word Count</label>
<input :id="'word_count_' + index" :name="'texts[' + index + '][word_count]'" type="text" class="form-input rounded-md shadow-sm mt-1 block w-full" v-model="singleText.word_count" :autocomplete="'texts[' + index + '][word_count]'" />
<div v-if="form.error('texts[' + index + '][word_count]')">
<p class="text-sm text-red-600">
{{ form.error('texts[' + index + '][word_count]') }}
</p>
</div>
<label class="block font-medium text-sm text-gray-700" for="category">Category</label>
<input :id="'category_' + index" :name="'texts[' + index + '][category]'" type="text" class="form-input rounded-md shadow-sm mt-1 block w-full" v-model="singleText.category" :autocomplete="'texts[' + index + '][category]'" />
<div v-if="form.error('texts[' + index + '][category]')">
<p class="text-sm text-red-600">
{{ form.error('texts[' + index + '][category]') }}
</p>
</div>
</div>
</div>
Finally, here is my Vue code:
props: ['allTexts'],
data: function() {
return {
showingNavigationDropdown: false,
text: {
skill_level: null,
word_count: null,
title: null,
description: null,
category: null,
},
form: this.$inertia.form({
'_method': 'POST',
texts: [],
}, {
bag: 'updateOrderFormBuilder',
resetOnSuccess: false,
}),
}
},
mounted: function () {
this.form.texts = JSON.parse(this.allTexts); //this.allTexts;
console.log(this.form.texts);
},
methods: {
switchToTeam(team) {
this.$inertia.put(route('current-team.update'), {
'team_id': team.id
}, {
preserveState: false
})
},
logout() {
axios.post(route('logout').url()).then(response => {
window.location = '/';
})
},
submit() {
this.$inertia.post(route('create-new-order.set-order-details-by-form', this.form), {
preserveScroll: true
})
},
addNewText() {
if(this.form.texts.length < 20)
{
this.form.texts.push(this.text);
console.log(this.form.texts, this.text);
}
},
removeText: function(index) {
if(this.form.texts.length > 1)
{
this.form.texts.splice(index, 1);
}
}
}
Why, when I click on the submit button does $request->input('texts.*'); not work? It always shows nothing when the form is empty, and only shows the inputs when they have been filled in the form?
I think you need to use and send your form.text data. Notice that your inertia.post() are using different parameter

Laravel 5: When store data to database The server responded with a status of 405 (Method Not Allowed)

I m new in Laravel and trying to add data to the database via ajax, but it throws this message: "The server responded with a status of 405 (Method Not Allowed)" I define two routes for this one is for form page
Route::get('/create/{id}', 'Participant\ParticipantProjectDefinitionController#create')->name('participant.project-definition.create');
and other route to save this data like this:
// To save Project definition Data
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
And the Ajax code I'm using is this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: {
'_token' : token,
'customer_name' : $('#field_name_0').val(),
'customer_name' : $('#field_data_0').val(),
// 'form_fields' : form_fields
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
Controller code
/**
* create project Definition Form
*
*/
public function create(request $request, $id){
$ProjectDefinitionFields = ProjectDefinitionFields::all();
$ProjectDefinitionFieldRow = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
// dd($ProjectDefinitionFieldRow);
return view('participants.project_definition.create', ['ProjectDefinitionFieldRow' => $ProjectDefinitionFieldRow]);
}
public function store(request $request, $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields){
$project = ProjectDefinitionFields::find('field_id');
$count = ProjectDefinitionFields::where('project_definition_id','=', $id)->count();
$pd_id = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
for($i=0;$i<$count;$i++){
$data[]= array (
'field_name'=>$request->get('field_name_'.$i),
'field_data'=>$request->get('field_data_'.$i),
'user_id' => Auth::user()->id,
// 'user_id' => $request->user()->id,
'project_definition_id' => $pd_id,
// 'field_id' => $projectDefinitionFields->id,
);
}
$project_data = ProjectDefinitionData::create($data);
if($project_data){
return response()->json($project_data);
}
}
Model
on ProjectDefinition
public function formFields(){
// return $this->hasMany('App\Model\ProjectDefinitionFields');
return $this->belongsTo('App\Model\ProjectDefinitionFields');
}
on projectDefinitionFields
public function projectDefinition(){
return $this->belongsTo('App\Model\ProjectDefinition');
}
This is my create.blade.php
<form id="create_project_definition_data_form" enctype="multipart/form-data" >
#csrf
{{ method_field('PUT') }}
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
#section('scripts')
<script src="{{ asset('js/participants/project-definition.js') }}"></script>
<script>
// on document ready
$(document).ready(function(){
var baseUrl = "{{ url('/') }}";
var indexPdUrl = "{{ route('participant.projectDefinition') }}";
var token = "{{ csrf_token() }}";
{{-- // var addUrl = "{{ route('participant.project-definition.create') }}"; --}}
storeDefinitionFormData(token, baseUrl);
// console.log(addUrl);
});
</script>
ERROR
Request URL:http://127.0.0.1:8000/participant/project-definition/create/2kxMQc4GvAD13LZC733CjWYLWy8ZzhLFsvmOj3oT
Request method:POST
Remote address:127.0.0.1:8000
Status code: 405 Method Not Allowed
Version:HTTP/1.0
Add method attribute in form
method="post"
Change your route from
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
to
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
Firstly, you should post here what's your problem and where's your problem we don't need to see all of your code to solve a basic problem.
Your form should be this:
<form id="create_project_definition_data_form" enctype="multipart/form-data" method='post'>
#csrf
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
You should use 'post' method when you're creating a something new, this is safer than using 'get' method. so change route method too.
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
also, in your 'ParticipantProjectDefinitionController->store()' function has
$id, User $user, ProjectDefinitionFields $ProjectDefinitionFields parameters but your router not. We can fix it like this:
Route::post('/store-project-definition-data/{id}/{user}/{ProjectDefinitionFields}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
That means you should pass all of them to your controller.
Soo we can edit your ajax call like this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: { // $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields
'_token' : token,
'id' : 'your_id_field',
'user' : '{{ Auth::user() }}',
'ProjectDefinitionFields' : 'your_definition_fields' // you need to pass type of 'ProjectDefinitionFields'
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
before try it, I'll give you a advice. Read whole documentation and review what others do on github or somewhere else
Route::match(['GET','POST'],'/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
You can try this Route it will resolve 405

How to refresh HTML after AJAX post

I have a site where guests can sign in via a modal form.
The solution I came up with is working but I feel like it's a dirty/insecure way to do it.
In the master layout, I load the partial view which contains the modal form.
when the user is authenticated I refresh the navbar to show the logged in username. That's the part where I'm kind of confused. Wouldn't it be possible to 'refresh' the navbar which is also a partial view.
login-modal.blade.php:
<div class="ui small modal" id="loginModal">
<div class="header">
Login
</div>
<div class="ui active dimmer" id="loader" style="display: none">
<div class="ui text loader">Loading</div>
</div>
<div class="content">
<div class="ui grid">
<div class="nine wide column centered">
{!! Form::open(array('route' => 'auth.login', 'method' => 'post','id'=>'formLogin','class' => 'ui large form')) !!}
<meta name="csrf_token" content="{{ csrf_token() }}"/>
<div class="field {!! $errors->has('password') ? 'error' : '' !!}">
<div class="ui left icon input">
<i class="user icon"></i>
{!! Form::text('username','',['name'=>'username','id'=>'username','class' => 'pd','placeholder'=>'Username']) !!}
</div>
{!! $errors->first('username', '<span class="ui text" id="" style="color: #bf4d4b">:message</span>') !!}
</div>
<div class="field {!! $errors->has('password') ? 'error' : '' !!}">
<div class="ui left icon input">
<i class="lock icon"></i>
{!! Form::password('password',['name'=>'password','id'=>'password','class' => '','placeholder'=>'Password']) !!}
</div>
{!! $errors->first('password', '<span class="ui text" id="" style="color: #bf4d4b">:message</span>') !!}
</div>
{!! Form::submit('Login',['id'=>'loginButton','class'=>'ui fluid large teal submit button']) !!}
<div class="ui error message"></div>
{!! Form::close() !!}
<div class="ui message">
No account? Sign Up
</div>
</div>
</div>
</div>
<div class="actions">
</div>
</div>
now the javascript in the same file:
<script>
$('#loginButton').click(function () {
$('#loginModal').modal(
{
blurring: true,
closable: true,
})
.modal('show');
});
$(document).ready(function () {
$('form#formLogin').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
timeout: 10000,
url: $('form#formLogin').attr('action'),
dataType: 'json',
data: $('form#formLogin').serialize(),
beforeSend: function (xhr) {
$('div#loader').show();
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
complete: function () {
$('div#loader').hide();
},
success: function (data) {
if (data.success == false) {
var errors = data.errors; $('#loginModal').find('div.field.error').removeClass("field error").addClass("field");
$('#loginModal').find('span').remove();
$.each(errors, function (field, errormsg) {
if (errormsg.length != 0) {
var currentField = $('#loginModal').find('#' + field);
var currentFieldSpan = $('#loginModal').find('#span' + field);
if (currentFieldSpan.length > 0) {
$('#loginModal').find('div.field.error').removeClass("field error").addClass("field");
$('#loginModal').find('span').remove();
}
currentField.closest("div.field").removeClass("field").addClass("field error");
$("<span class='ui text' id='span" + field + "' style='color: #bf4d4b'>" + errormsg + "</span>").insertAfter(currentField.closest("div.ui.left.icon.input"));
}
});
if ((typeof data.locked != 'undefined') && data.locked.status == true) {
//BIDOUILLE pour disable le button login//
function enableLoginButton() {
$('#loginModal').find('#loginButton').removeClass('disabled');
}
//disable login button
$('#loginModal').find('#loginButton').addClass('disabled');
//after lockout time enable the login button again
setTimeout(enableLoginButton, (data.locked.remainingtime * 1000));
}
}
else if (data.success == true) {//authentication was successful
var cnt = '<div class="ui simple dropdown item">' +
'<img class="logo" src="{{ asset('images/food.png') }}" style="margin-right: 1em">' +
data.user['username'] +
' <i class="dropdown icon"></i>' +
'<div class="menu">' +
'<a class="item" href="#">Link Item</a>' +
'<a class="item" href="#">Link Item</a>' +
'<div class="divider"></div>' +
'<div class="header">Header Item</div>' +
'<div class="item">' +
'<i class="dropdown icon"></i>' +
'Sub Menu' +
'<div class="menu">' +
'<a class="item" href="#">Link Item</a>' +
'<a class="item" href="#">Link Item</a>' +
'</div>' +
'</div>' +
'<a class="item" href="#">Link Item</a>' +
'</div>' +
'</div>'
//remove the signin button
$('#navbartop .right .item').remove();
//add the dropdown with username
$('#navbartop .right').append(cnt);
//dissmis modal
$('#loginModal').modal().modal('hide');
}
},
error: function (xhr) {
var validationerrors = xhr.responseJSON;
$('#loginModal').find('div.field.error').removeClass("field error").addClass("field");
$('#loginModal').find('span').remove();
$.each(validationerrors, function (field, errormsg) {
if (errormsg.length != 0) {
//select the field
var currentField = $('#loginModal').find('#' + field);
var currentFieldSpan = $('#loginModal').find('#span' + field);
if (currentFieldSpan.length > 0) {
$('#loginModal').find('div.field.error').removeClass("field error").addClass("field");
$('#loginModal').find('span').remove();
}
//apply 'field error' class to the closest div with 'field' class
currentField.closest("div.field").removeClass("field").addClass("field error");
//appends a span with red text and the validation error message
$("<span class='ui text' id='span" + field + "' style='color: #bf4d4b'>" + errormsg + "</span>").insertAfter(currentField.closest("div.ui.left.icon.input"));
}
});
}
});
return false;
});
});
</script>
AuthController.php:
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
if ($throttles) {
$this->clearLoginAttempts($request);
}
if (method_exists($this, 'authenticated')) {
return $this->authenticated($request, Auth::guard($this->getGuard())->user());
}
//if user intended to access Logout() while not logged in, avoid instant redirect and logout
if (str_contains(redirect()->intended()->getTargetUrl(),'auth/logout')) {
return redirect()->route('home.index')->with('success', Auth::user()->username.' logged in successfully. ');
}
if($request->ajax())
{
return Response::json(['success' => true, 'errors' => '','user'=> Auth::user()]);
}
return redirect()->intended($this->redirectPath())->with('success', Auth::user()->username.' logged in successfully. ');
}
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
if ($throttles && ! $lockedOut) {
$this->incrementLoginAttempts($request);
}
if($request->ajax())
{
return Response::json(['success' => false, 'errors' =>
[$this->loginUsername() => $this->getFailedLoginMessage()]
]);
}
return $this->sendFailedLoginResponse($request);
}
protected function sendLockoutResponse(Request $request)
{
$seconds = app(RateLimiter::class)->availableIn(
$this->getThrottleKey($request)
);
if($request->ajax()) {
return Response::json(['success' => false,
'errors' =>
[$this->loginUsername() => $this->getLockoutErrorMessage($seconds)],
'locked' =>
['status'=>true, 'remainingtime'=>$seconds]]);
}
return redirect()->back()
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getLockoutErrorMessage($seconds),
]);
}
I would wrap the navbar into a div like this:
<div id="ajax-nav">
<!-- Nav here -->
</div>
Then you can reload the navbar when your login response was successful:
$('#ajax-nav').load("some url that returns the html of the navbar");
Then you just need a route that leads to a Controller that can generate the navbar based on the user login state (logged in or guest).
With this procedure, you can completely replace the content of the navbar with a newly generated one after a specific event like your successful login or you could even set an interval to refresh the navbar - but that should not be needed in your case.
I guess you need to change this line:
'<img class="logo" src="{{ asset('images/food.png') }}" style="margin-right: 1em">'
For
'<img class="logo" src="{{ asset(\'images/food.png\') }}" style="margin-right: 1em">'
I hope it works ;)

Mulitple row insert into db in codeigniter

ajax change function execute listByBatch() and show the table with data by batch which is post by ajax. And then I trying to insert table rows by insertAttendance, code below:
Jquery post:
$("#batch-list").change(function(){
/*dropdown post */
$.ajax({
url:"<?php echo base_url(); ?>index.php/attendance/list_ByBatch",
data: {batchid: $(this).val()},
type: "POST",
dataType:'json',
success: function(data){
$("#traineeList").html(data);
$("#subTotal").html("Total: " + $('#traineeList tr').length.toString());
document.getElementById("classHour").defaultValue = "4";
}
});
});
Controller:
public function list_ByBatch() {
$batch = $this->input->post('batchid', TRUE);
$data['trainee']= $this->AttendanceModel->get_traineeList($batch);
if (!empty($data['trainee'])) {
echo form_open('attendance/insertAttendance');
echo"<table class='table table-hover type-list2'id='traineeList'>
<tr class='success'>
<th>Trainee ID</th>
<th>Trainee Name</th>
<th>Present</th>
</tr>";
foreach ($data['trainee'] as $row) {
echo "
<tr><td>" . str_pad($row->TraineeID, 7, "0", STR_PAD_LEFT) . "</td>
<td>" . $row->Name . "</td>
<td><input type='checkbox' name='.$row->TraineeID[]' value='" . $row->TraineeID . "' checked></td>
</tr>";
}
echo"</table>";
echo"
<div class='row'>
<div class='form-group col-sm-2'>
<h5 id='subTotal'></h5>
</div>
<div class='form-group col-sm-6'>
<input type='date' class='form-control' name='attnDate' id='attnDate' placeholder='Attendance Date' required>
</div>
<div class='form-group col-sm-2'>
<input type='number ' class='form-control' name='classHour' id='classHour' placeholder='Class Hour' required>
</div>
<div class='form-group col-sm-2'>
<input type='submit' class='btn btn-default btn-success' name='record' value='Record'>
</div>
</div>";
echo "</form>";
}
}
public function insertAttendance() {
$TID ['TID']= $this->input->post('trainee');
$attnDate = $this->input->post('attnDate');
$classHour = $this->input->post('classHour');
echo '<pre>';
print_r($TID);
if(is_array($TID)){
foreach ($TID as $TID=>$key) {
$query = "INSERT INTO `tbl_attn_temp` (TraineeID, Date, classHour) VALUES ('" . $key . "','" . $attnDate . "','" . $classHour . "')";
$this->db->query($query);
}
}else{
echo "Trainee ID is not array";
}
}
I just trying to insert all rows (TraineeID) shows in table with "attnDate" and 'classHour" by clicking submit button.

Select Cascade Using jQuery and PHP in Laravel 4

I'm trying to populate a select box based on a previous select box value in Laravel 4. Here's what I have so far:
My JS:
var url = document.location.hostname + '/cream/public/list-contacts';
var contacts;
$.ajax({
async: false,
type: 'GET',
url: url,
dataType: 'json',
success : function(data) { contacts = data; }
});
$('#account_id').change(function() {
alert(url);
label = "<label class='control-label'>Contacts</label>";
select = $("<select name='contact_id[]' id='contact_id'>");
console.log(contacts);
for(var i in contacts) {
alert(contacts[i]['account_id']);
if(contacts[i]['account_id'] == $(this).val()) {
select.append('<option value="' + contacts[i]['id'] + '">' + contacts[i]['name'] + '</option>');
}
}
$('.contacts').html(select).prepend(label);
});
My list-contacts route declaration:
Route::get('list-contacts', 'ContactListController#contacts');
My contacts() method in my ContactListController:
public function contacts()
{
return Contact::select('contacts.id', 'contacts.account_id', DB::raw('concat(contacts.first_name," ",contacts.last_name) AS name'))->get()->toArray();
}
The form in my view:
{{ Form::open(array('action' => 'DelegatesController#store', 'class' => 'view-only pull-left form-inline')) }}
{{ Form::label('account_id', 'Account', array('class' => 'control-label')) }}
{{ Form::select('account_id', $accounts) }}
<div class="contacts"></div>
{{ Form::label('delegate_status_id', 'Status', array('class' => 'control-label')) }}
{{ Form::select('delegate_status_id', $delegate_statuses) }}
{{ Form::label('price', 'Price', array('class' => 'control-label')) }}
{{ Form::text('price', '', array('class' => 'input-small')) }}
{{ Form::hidden('event_id', $event->id) }}
{{ Form::submit('Add Delegate', array('class' => 'btn btn-success')) }}
{{ Form::close() }}
EDIT: I've modified my code above. When I visit /list-contacts it gets the correct data I need, it's just not assigning that data to the contacts variable in my AJAX request in my JS? Any help would be appreciated.
Error: This is the error that is shown in my console log for the contacts variable:
file: "/Applications/MAMP/htdocs/cream/vendor/laravel/framework/src/Illuminate/Routing/Controllers/Controller.php"
line: 290
message: ""
type: "Symfony\Component\HttpKernel\Exception\NotFoundHttpException"
I now have this working. It was to do with the generated URL in the AJAX request. I removed the document.location.hostname and hard coded the url without localhost.
Here's the working code for those interested:
My JS:
var url = '/cream/public/list-contacts';
var contacts;
$.ajax({
async: false,
type: 'GET',
url: url,
dataType: 'json',
success : function(data) { contacts = data; }
});
$('#account_id').change(function() {
select = $("<select name='contact_id' id='contact_id'>");
for(var i in contacts) {
if(contacts[i]['account_id'] == $(this).val()) {
select.append('<option value="' + contacts[i]['id'] + '">' + contacts[i]['name'] + '</option>');
}
}
$('.delegates .contacts').show();
$('.delegates .contacts .controls').html(select);
});
My list-contacts route declaration:
Route::get('list-contacts', 'ContactListController#contacts');
My contacts() method in my ContactListController:
public function contacts()
{
return Contact::select('contacts.id', 'contacts.account_id', DB::raw('concat(contacts.first_name," ",contacts.last_name) AS name'))->get();
}
The form in my view:
{{ Form::open(array('action' => 'DelegatesController#store', 'class' => 'delegates pull-left form-horizontal add-delegate')) }}
<div class="control-group">
{{ Form::label('account_id', 'Account', array('class' => 'control-label')) }}
<div class="controls">
{{ Form::select('account_id', $accounts) }}
</div>
</div>
<div class="control-group contacts">
{{ Form::label('contact_id', 'Contacts', array('class' => 'control-label')) }}
<div class="controls">
</div>
</div>
<div class="control-group">
{{ Form::label('delegate_status_id', 'Status', array('class' => 'control-label')) }}
<div class="controls">
{{ Form::select('delegate_status_id', $delegate_statuses) }}
</div>
</div>
<div class="control-group">
{{ Form::label('price', 'Price', array('class' => 'control-label')) }}
<div class="controls">
{{ Form::text('price', '', array('class' => 'input-small')) }}
</div>
</div>
{{ Form::hidden('event_id', $event->id) }}
{{ Form::close() }}

Resources