i want to add a function using laravel and vuejs and axios but it gives me error Error: "Request aborted".if I delete form validation system and checkForm function it all works well,really i don't know what error sign what,what kind of error.
fonction.blade.php
<section id="main-content">
<section class="wrapper">
<div class="container" id="app">
<div id="login-page">
<div class="form-login">
<div class="login-wrap">
<form #submit="checkForm">
<div v-if="errors.length">
<div class="alert alert-danger" role="alert">
<ul>
<li v-for="error in errors">#{{ error }}</li>
</ul>
</div>
</div>
<input type="text" class="form-control" id="fonction" name="fonction" v-model="fonction.fonction" placeholder="fonction">
<br>
<button class="btn btn-theme" #click="addFonction">AJOUTER FONCTION</button>
</form>
</div>
</div>
</div>
</div>
</section>
</section>
<script src="{{asset('js/vue.js')}}"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
vuejs
<script>
window.Laravel = {!! json_encode([
'csrfToken' => csrf_token(),
'url' => url('/')
]) !!};
</script>
<script>
var app = new Vue({
el: '#app',
data: {
errors: [],
fonctions:[],
fonction:{
fonction :''
}
},
methods:{
checkForm: function (e) {
if (this.fonction.fonction) {
return true;
}
this.errors = [];
if (!this.fonction.fonction) {
this.errors.push('fonction required.');
}
e.preventDefault();
},
addFonction:function(){
axios.post(window.Laravel.url+'/addfonction/', this.fonction)
.then(response => {
//console.log(response.data);
this.fonctions.unshift(this.fonction);
this.fonction={
fonction:''
}
})
.catch(error=>{
console.log(error);
})
},
},
});
</script>
SalarieController.php
public function addFonction(request $request){
$fonction = new Fonction;
$fonction->fonction = $request->fonction;
$fonction->save();
Response()->json(['etat' => true]);
}
Same question, maybe it connect with <form> tag.
I am solve for myself by replace <form> this tag with <div> tag. Also I replace all submit events with click ones on button.
Related
So I have my car project and I want my cars to be Likeabel. So I installed overtrue likeable with composer require overtrue/laravel-follow, and do everything that is required. I followed tutorial from here.
So this is my code. My CarsController#ajaxRequest:
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function ajaxRequest(Request $request){
$car = Car::find($request->id);
$response = auth()->user()->toggleLike($car);
return response()->json(['success'=>$response]);
}
This is my route in web.php : Route::post('ajaxRequest', 'CarsController#ajaxRequest')->name('ajaxRequest');.
This is my cars index.blade.php:
#foreach($cars as $car)
#if($car->placeni_status != 0)
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" data-id="{{ $car->id }}">
<div class="auto-listing">
<div class="cs-media auto-media-slider">
#foreach (explode('|', $car->fotografije) as $fotografija)<?php $img = explode('|', $car->fotografije); ?>
<figure>
<img src="/slike_oglasa/{{$fotografija}}" alt="#"/>
<figcaption>
<span class="auto-featured">PREMIUM</span>
<i class="icon-play3"></i>
<div class="cs-photo">8 Photos</div>
</figcaption>
</figure>
#endforeach
</div>
<div class="auto-text">
<span class="cs-categories">Timlers Motors</span>
<div class="post-title">
<h4>{{$car->naslov}}</h4>
<h6>{{$car->naslov}}</h6>
<div class="auto-price"><span class="cs-color">{{$car->cijena}} €</span> <em>{{$car->vrsta_cijene}}</em></div>
<img src="assets/extra-images/post-list-img1.jpg" alt=""/>
</div>
<ul class="auto-info-detail">
<li>Godiste<span>{{$car->godiste}}</span></li>
<li>Kilometraza<span>{{$car->kilometraza}}</span></li>
<li>Mjenjac<span>{{$car->mjenjac}}</span></li>
<li>Gorivo<span>{{$car->gorivo}}</span></li>
</ul>
<div class="btn-list">
<div id="list-view" class="collapse">
<ul>
<li><b>Marka:</b> {{$car->marka}}</li>
<li><b>Model:</b> {{$car->model}}</li>
<li><b>Kubikaza:</b> {{$car->kubikaza}}cc</li>
<li><b>Kilovata:</b> {{$car->kilovata}}kW</li>
<li><b>Konjska snaga:</b> {{$car->konjska_snaga}}ks</li>
<li><b>Registrovan do:</b> {{$car->registracija}}</li>
</ul>
</div>
</div>
<div class="cs-checkbox">
<input type="checkbox" name="list" value="check-listn" id="check-list">
<label for="check-list">Uporedi</label>
</div>
<i id="like{{$car->id}}" class="glyphicon glyphicon-thumbs-up {{ auth()->user()->hasLiked($car) ? 'like-post' : '' }}"></i> <div id="like{{$car->id}}-bs3">{{ $car->likers()->get()->count() }}</div>
<label for="check-list1" style="text-transform: uppercase; color:gray;font-size: 11px;padding-left: 10px;"> {{$car->user->city}}</label>
Pogledajte vise<i class=" icon-arrow-long-right"></i>
</div>
</div>
</div>
#else
And this is script for like system:
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('i.glyphicon-thumbs-up, i.glyphicon-thumbs-down').click(function(){
var id = $(this).parents(".panel").data('id');
var c = $('#'+this.id+'-bs3').html();
var cObjId = this.id;
var cObj = $(this);
$.ajax({
type:'POST',
url:'/ajaxRequest',
data:{id:id},
success:function(data){
if(jQuery.isEmptyObject(data.success.attached)){
$('#'+cObjId+'-bs3').html(parseInt(c)-1);
$(cObj).removeClass("like-post");
}else{
$('#'+cObjId+'-bs3').html(parseInt(c)+1);
$(cObj).addClass("like-post");
}
}
});
});
$(document).delegate('*[data-toggle="lightbox"]', 'click', function(event) {
event.preventDefault();
$(this).ekkoLightbox();
});
});
</script>
But when I press like and inspect it in console it shows me error:
jquery.js:4 POST http://localhost:8000/ajaxRequest 419 (unknown status)
and in preview it shows me this:
{message: "CSRF token mismatch.", exception: "Symfony\Component\HttpKernel\Exception\HttpException",…}
message: "CSRF token mismatch."
exception: "Symfony\Component\HttpKernel\Exception\HttpException"
file: "C:\engineering\xampp\htdocs\autoplac\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php"
line: 208
trace: [{,…},…]
You can add the route to App\Http\Middleware\VerifyCsrfToken ,$except array to disable csrf check for specific route.
Or you can submit your csrf token in your ajax request
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
check the doc
I am creating commenting system. Now, I want to post a new comment, but when I send a comment, I got an error in http://127.0.0.1:8000/comments/51.
The GET method is not supported for this route. Supported methods:
POST.
I want to post a comment in this URL http://127.0.0.1:8000/results/51.
In my chrome dev tool console, I have this error
Failed to load resource: the server responded with a status of 500
(Internal Server Error)
web.php
Route::middleware(['auth'])->group(function(){
//post a comment
Route::POST('comments/{post}', 'CommentController#store')->name('comment.store');
});
//comment area
Route::get('results/{post}/comments', 'CommentController#index');
Route::get('comments/{comment}/replies', 'CommentController#show');
comments.vue
<template>
<div class="commentarea" >
<div class="comment-posts" >
<div v-if="!auth" class="user-comment-area" >
<div class="user-post">
<!---<img src="{{asset('people/person7.jpg')}}" class="image-preview__image">--->
<input v-model="newComment" type="text" name="comment">
</div>
<div class="comments-buttons">
<button class="cancel-button">Cancel</button>
<button #click="addComment" class="comment-button" type="submit">Comment</button>
</div>
</div>
<h4>Comments ()</h4>
<div class="reply-comment" v-for="comment in comments.data" :key="comment.id">
<div class="user-comment">
<div class="user">
<!---<img src="{{ $comment->user->img }}" class="image-preview__image">--->
<avatar :username="comment.user.name"></avatar>
</div>
<div class="user-name">
<span class="comment-name">{{ comment.user.name }}</span>
<p>{{ comment.body }}</p>
</div>
</div>
<div class="reply">
<button class="reply-button">
<i class="fas fa-reply"></i>
</button>
</div>
<replies :comment="comment"></replies>
</div>
</div>
<div>
<button v-if="comments.next_page_url" #click="fetchComments" class="load">Load More</button>
</div>
</div>
</template>
<script>
import Avatar from 'vue-avatar'
import Replies from './replies.vue'
export default {
props: ['post'],
components: {
Avatar,
Replies
},
mounted() {
this.fetchComments()
},
data: () => ({
comments: {
data: []
},
newComment: '',
auth: ''
}),
methods: {
fetchComments() {
const url = this.comments.next_page_url ? this.comments.next_page_url : `/results/${this.post.id}/comments`
axios.get(url).then(({ data }) => {
this.comments = {
...data,
data: [
...this.comments.data,
...data.data
]
}
})
.catch(function (error) {
console.log(error.response);
})
},
addComment() {
if(! this.newComment) return
axios.post(`/comments/${this.post.id}`, {
body: this.newComment
}).then(( {data} ) => {
this.comments = {
...this.comments,
data: [
data,
...this.comments.data
]
}
})
}
}
}
</script>
commentsController.php
public function store(Request $request, Post $post)
{
return auth()->user()->comments()->create([
'body' => $request->body,
'post_id' => $post->id,
'comment_id' => $request->comment_id
])->fresh();
}
comment.php
protected $appends = ['repliesCount'];
public function post()
{
return $this->belongsTo(Post::class);
}
public function getRepliesCountAttribute()
{
return $this->replies->count();
}
I am glad if someone helps me out.
your URL is : http://127.0.0.1:8000/results/51.
your routes should be :
Route::group(['middleware' => 'auth'],function () {
Route::post('comments/{post_id}', 'CommentController#store')->name('comment.store');
});
your controller will be :
public function store(Request $request,$post_id)
{
return auth()->user()->comments()->create([
'body' => $request->body,
'post_id' => $post_id,
'comment_id' => $request->comment_id
])->fresh();
}
Thank you, I put catch method, and the issue was I did not include protected $fillable ['body','post_id', 'comment_id'] in comment model.
im new to laravel and i dont know how to do this.
i want to insert this #{{comment.user.avatar}}
inside this <img src={{ asset("images/profile/{comment.user.avatar}") }} />
what im getting is this
<img src="http://localhost:89/images/profile/{comment.user.avatar}">
what i want is
<img src="http://localhost:89/images/profile/avatarpicture.jpg">
this is my complete code
<div class="card" v-for="comment in comments">
<div class="card-content">
<div class="media">
<div class="media-left">
<img src={{ asset("images/profile/") }}#{{comment.user.avatar}} style='height:50px; width:50px' />
</div>
<div class="media-content">
<p class="subtitle is-6">#{{comment.user.firstname}} said...</p>
<p>
#{{comment.body}}
</p>
<span style="color: #aaa;" class="is-size-7">on #{{comment.created_at}}</span>
</div>
</div>
</div>
</div>
and this is my javascript
#section('scripts')
<script>
const app = new Vue({
el: '#app',
data: {
comments: {},
commentBox: '',
post: {!! $post->toJson() !!},
user: {!! Auth::check() ? Auth::user()->toJson() : 'null' !!}
},
mounted(){
this.getComments();
// this.listen();
},
methods:{
getComments(){
axios.get(`/api/posts/${this.post.id}/comments`)
.then((response) => {
this.comments = response.data
})
.catch(function(error){
console.log(error);
})
},
}
});
</script>
thank you in advance
arnel
Vue interpolation cannot be used inside HTML attributes. You must bind an expression and wrap it in quotes. Note :src is short hand for v-bind:src.
<img :src="'{{ asset("images/profile/") }}' + comment.user.avatar">
By doing this, you're binding the concatenated string:
'http://localhost:89/images/profile/' + comment.user.avatar
I am designing CI application and is stuck in ajax query. Basically the function which i have written is taking id as null when save button is pressed even though when i click on edit button it shows its picking up the correct id. Looks like I have some error in function. BELOW IS THE FUNCTION WHICH i HAVE WRITTEN :
public function ajax_update()
{
$this->_validate();
$data = array(
//'firstName' => $this->input->post('firstName'),
//'lastName' => $this->input->post('lastName'),
//'gender' => $this->input->post('gender'),
//'address' => $this->input->post('address'),
//'dob' => $this->input->post('dob'),
//'tid' => $this->input->post('tid'),
'name' => $this->input->post('tname'),
);
$this->transport->update(array('tid' => $this->input->post('tid')), $data);
var_dump( $this->input->post());
echo json_encode(array("status" => TRUE));
}
the update function is
public function update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
View is
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><html lang="en">
<head>
<?php include_once("header.php"); ?>
</head>
<body class="fixed-nav sticky-footer bg-dark">
<!-- Navigation-->
<?php include_once("sidebar.php"); ?>
<div>
<div class="content-wrapper">
<div class="container-fluid">
<!-- Breadcrumbs-->
<ol class="breadcrumb">
<li class="breadcrumb-item">
Home
</li>
<li class="breadcrumb-item active">Manage Transport</li>
</ol>
<!--Button to add Client
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal2"><i class="fa fa-plus" style="color:white"></i> Add Transport</button>-->
<button class="btn btn-success" onclick="add_transport()"><i class="glyphicon glyphicon-plus"></i> Add Transport</button>
<br>
<br>
<!-- Example DataTables Card-->
<div class="card mb-3">
<div class="card-header">
<i class="fa fa-table"></i> View Transport Details</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th style="width:90%;">Transport Detail</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Transport Detail</th>
<th>Action</th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- /.container-fluid-->
<!-- /.content-wrapper-->
</div>
<!-- Modal to add Transport-->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Transport Details</h4>
<button type="button" class="close" data-dismiss="modal">x</button>
</div>
<div class="modal-body">
<!--<form role="form" name="form1" action="<?php echo base_url('search/add_trans'); ?>" method="post" autocomplete="on">-->
<form action="#" id="form" class="form-horizontal">
<div class="row">
<div class="col-md-2">
<label>Transport Details</label>
</div>
<div class="col-md-10" id="new_data">
<textarea name="tname" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<!--<input type="submit" name="submit" class="btn btn-primary" value="Submit">-->
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Modal Finishes-->
</div>
<?php include_once 'footer.php'; ?>
<script type="text/javascript">
var save_method; //for save method string
var table;
//set input/textarea/select event when change value, remove class error and remove text help block
$("input").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("textarea").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("select").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
function add_transport()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#myModal').modal('show'); // show bootstrap modal
$('.modal-title').text('Add Transport'); // Set Title to Bootstrap modal title
}
function edit_transport(id)
{
//var table = $('#dataTable').DataTable();
// console.log( table.row( id ).data() );
// $("#tid").val(data.tname);
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('transport/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
// $('[name="id"]').val(data.id);
//$('[name="tid"]').val(data.tid);
$('[name="tname"]').val(data.tname);
// $('[name="firstName"]').val(data.firstName);
//$("#tid").val(data.tname);
//alert(data.tname);
// $('[name="lastName"]').val(data.lastName);
// $('[name="gender"]').val(data.gender);
// $('[name="address"]').val(data.address);
// $('[name="dob"]').datepicker('update',data.dob);
// $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('#myModal').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Transport'); // Set title to Bootstrap modal title
// new_data
//$("#new_data").html('<textarea name="name" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea> <input type="text" name="row_id" value="'+id+'" readonly hidden >');
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
//function reload_table()
//{
// table.ajax.reload(null,false); //reload datatable ajax
//}
function reload_table() {
table.api().ajax.reload(null, false); //reload datatable ajax
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('transport/ajax_add')?>";
} else {
url = "<?php echo site_url('transport/ajax_update')?>";
}
// console.log($('#form').serialize());
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#myModal').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
//$("#new_data").html('<textarea name="name" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea> ');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
//$("#new_data").html('<textarea name="name" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea>');
}
});
}
function delete_transport(id)
{
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url : "<?php echo site_url('transport/ajax_delete')?>/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
//if success reload ajax table
$('#myModal').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
}
function reload_table()
{
//console.log(table);
table.api().ajax.reload( null, false );
}
$(document).ready(function() {
//datatables
table = $('#dataTable').dataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('transport/ajax_list')?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
});
</script>
</body>
</html>
Any pointers please ?
On my controller
public function postJoin(Request $request){
$user=Auth::user();
$plan=$request['plan'];
$user->subscription($plan)->create($request['token'],['email'=>$users->email]);
return Redirect::action('subscripton')->with('notice','Ahora estás registrado');
}
so the error is "Call to a member function create() on null"
and when I do a
dd($user->subscription($plan));
its says also NULL.
the problem is the subscription function.
Any help Please?
here is where I send to stripe with Jquery
$(document).ready(function(){
Stripe.setPublishableKey('MYKEY');
$('#subscription-form button').on('click', function(){
var form = $('#subscription-form');
var submit = form.find('button');
var submitInitialText = submit.text();
submit.attr('disabled','disabled').text('Espere un momento...');
Stripe.card.createToken(form, function(status, response){
var token;
if (response.error) {
//esta parte no responde si hay error
form.find('.stripe-errors').text(response.error.message);
submit.removeAttr('disabled');
submit.text(submitInitialText);
}else{
token=response.id;
form.append($('<input type="hidden" name="token">').val(token));
form.submit();
}
});
});
});
my view
#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">Suscribirse</div>
<div class="panel-body">
{{Form::open(array('url'=>'subscription/join','id'=>'subscription-form'))}}
#include('subscription.partials.card')
<button class="btn btn-primary">Suscribirse</button>
<!-- {{Form::submit('Suscribirse',['class'=>'btn btn-primary'])}} -->
{{Form::token()}}
{{Form::close()}}
</div>
</div>
</div>
</div>
#endsection
this is my Form view
<div class="stripe-errors panel"></div>
<div class="form-group">
{{Form::label('escoge un plan')}}
{{Form::select('plan', ['Premium' => 'Grande ($5,000 MXN)', 'Vip' => 'Vip (5,500 MXN)'],null,['placeholder'=>'escoga un plan','class'=>'form-control'])}}
</div>
<div class="form-group">
{{Form::label('tarjeta de credito')}}
{{Form::text('number',null, ['placeholder'=>'0000-0000-0000-0000','class'=>'form-control','data-stripe'=>'number'])}}
</div>
<div class="form-group">
{{Form::label('Año de expiracion')}}
{{Form::text('año',null, ['placeholder'=>'00','class'=>'form-control','data-stripe'=>'exp-year'])}}
</div>
<div class="form-group">
{{Form::label('mes de expiracion')}}
{{Form::text('mes',null, ['placeholder'=>'00','class'=>'form-control','data-stripe'=>'exp-month'])}}
</div>
<div class="form-group">
{{Form::label('CVC')}}
{{Form::text('cvc',null, ['placeholder'=>'000','class'=>'form-control','data-stripe'=>'cvc'])}}
</div>
Always check if user logged in or not:
if (auth()->check()) {
// Do something.
}
Another thing is you should use relation like this:
$user->subscription()->create(....);
I solve the problem with this line->
$user->newSubscription('main', $plan)->create($creditCardToken, ['email' =>$email,]);
but now it says "This customer has no attached payment source".
myDasbord refresh the customers, but theres no payments.