How to pass the data to route using jquery in Laravel - php

I have a route like this
Route::get('user/{id}/article', 'ArticleController#show')->name('Show');
And need to pass the parameter id using jquery
$('.user').click(function() {
var id = $(this).attr('data-id');
window.location.href ='{{ route('Show',['id'=> id]) }}';
});
But id can`t be recognized , How should I do?

Try to generate your html link like this
{{ $user->name }}

You can pass value like the below code:
<script type="text/javascript">
$('#modal-save').on('click',function(){
$.ajax({
type : 'post',
url : urlEdit,
data : {body : $('#post-body').val(), postId: postId , _token:token }
}).done(function(msg){
//console.log(msg.new_body);
$(PostBodyElement).text(msg['new_body']);
$('#edit-modal').modal('hide');
});
});
This should be in your controller
public function postEditPost(Request $request)
{
$this->validate($request,[
'body' => 'required'
]);
$post = Post::find($request['postId']);
if(Auth::user() != $post->user)
{
return redirect()->back();
}
$post->body = $request['body'];
$post->update();
return response()->json(['new_body' => $post->body],200);
}
And in your route :
Route::post('/edit',[
'uses' => 'PostController#postEditPost',
'as' => 'edit'
]);

$('.user').click(function() {
var id = $(this).attr('data-id');
var url = '{{ route("Show", ":id") }}';
url = url.replace(':id', id);
window.location.href = url;
});

Related

Yii2 add tag to blog post

I am totally confused about how should i save tag_id and post_id in the table when I still don't have the post_id. I made dropdownlist with options from database table
<?= Html::activeDropDownList($model, 'post_id', $ddItems, ['class' => 'form-control dd-list', 'prompt' => '']) ?>
That list contains tags(PHP, Java etc.).
User can have up to 3 tags on post. I tried to pass tags through GET and take in the controller with \Yii:$app->request->get(['id']) but without result.
my jQuery:
var ddList = $('.dd-list');
var tagList = $('.tag-container');
ddList.on('change', function () {
var tagHolder = document.createElement('div');
tagHolder.setAttribute('class', 'tag-holder');
var selected = $('.dd-list option:selected').text();
tagHolder.setAttribute('id', selected);
console.log(selected);
if(tagList.find('div').length > 2){
alert('You can have most 3 tags!');
return false;
}
if(tagList.find('#'+selected).length){
return false;
}else{
tagHolder.append(selected);
tagList.append(tagHolder);
$.ajax({
type : 'GET',
dataType : 'text',
url : '../post/create?tag=' + selected
});
}
});
actionCreate :
public function actionCreate()
{
$model = new Post();
$id = \Yii::$app->user->identity->id;
$ddItems = ArrayHelper::map(Tag::find()->all(),'tag_id', 'tag_name');
if ($model->load(Yii::$app->request->post())) {
date_default_timezone_set('Europe/Berlin');
$param = \Yii::$app->request->get();
$model->user_id = $id;
$model->date_create = date('m/d/Y');
if($model->save())
{
$tag = \Yii::$app->request->get(['tag']);
return $this->redirect(['view', 'id' => $model->post_id]);
}
throw new \yii\db\Exception("Some problem with DB connection ocurred!");
} else {
return $this->render('create', [
'model' => $model,
'ddItems' => $ddItems
]);
}
}
I am getting error : undefined tag. I am trying to get only one tag (because still don't know how to pass more).
What is the right way to reach my goal? I am in total mess from about 1 day! Ton of thanks in advance!
EDIT
I tried to send that tag with on click event like this :
$('.create-post').on('click', function () {
var tag = $('input[name=chosen-tag]').val();
console.log(tag);
$.ajax({
type : 'GET',
dataType : 'text',
url : '../post/create?tag=' + tag
});
});
I could not understand your programming scenario, But..
Change
$tag = \Yii::$app->request->get(['tag']);
To
$tag = \Yii::$app->request->get('tag');

Laravel 5.4 - MethodNotAllowedHttpException in RouteCollection.php line 233

In my laravel 5.4 app, i have a crud module. for the edit bit, the data is rendered in a bootstrap modal. the data is pulled successfully but on hitting the update button, the error shown is returned.
here's my blade form that's rendered in the modal:
<form id="formEdit" class="form-horizontal" role="form" method="put">
//form elements
</form>
here's the ajax that handles it:
//edit_id is defined globally
$('#updateClass').click(function(){
var name = $("#formEdit #name").val();
var status = ($('#formEdit #status').prop("checked") == true) ? 1 : 0;
var token = $('meta[name="csrf-token"]').attr('content');
var id = edit_id;
var url = "classes/update/"+id;
var formdata = {
'name' : name,
'status' : status,
'_token' : token
};
$.ajax({
method: "PUT",
url: url,
data: formdata,
dataType: "json"
})
.done(function(data) {
//
})
.fail(function(data) {
//
});
});
});
updateClass is the button that displays the edit form on the modal..
here's my routes in web.php:
Route::resource('classes', 'ClassesController');
Route::group(['prefix' => 'admin'], function () {
Route::get('classes', 'ClassesController#index');
Route::get('classes/edit/{id}', 'ClassesController#edit');
Route::put('classes/update/{id}', 'ClassesController#update');
});
and finally, my update function in the classes controller:
public function update(Request $request, $id)
{
$validator = $this->validator($request->all());
$errors = $validator->errors();
$errors = json_decode($errors);
if ($validator->passes())
{
Dl_class::find($id)->update($request->all());
return response()->json();
}
else
{
return response()->json($errors, 422);
}
}
what i'm i missing?
To send PUT request from form you need to send a hiddne input element named as method. Something like this:
<input type='hidden' name='_method' value='PUT'>
there is a helper method to do the same like:
{{ method_field('PUT') }}
Only then Laravel can recognize your PUT request.
Or alternatively, you can enclose this value to your ajax call also Something like:
var formdata = {
'name' : name,
'status' : status,
'_token' : token,
'_method' : 'PUT'
};

Post Error 500 adding a new row using Eloquent

I'm trying to follow a tutorial making a social network, the functionality of liking and disliking when no row is available in the database using Ajax (adding a new entry) is broken. Tutorial i'm following - this video is where he creates the controller: https://www.youtube.com/watch?v=drM19VKbCgU&list=PL55RiY5tL51oloSGk5XdO2MGjPqc0BxGV&index=20
Development Enviroment:
PhpStorm v9.0
Xampp v3.2.2
jQuery v1.12.0
Google Chrome
Error image:
Error image link
The Whole cycle:
Like and Dislike Button (The View):
<a href="#" class="like">{{ Auth::user()->likes()->where('post_id', $post->id)->first() ?
Auth::user()->likes()->where('post_id', $post->id)->first()->like == 1 ?
'You like this post':'Like' : 'Like' }}</a> |
<a href="#" class="like">{{ Auth::user()->likes()->where('post_id', $post->id)->first() ?
Auth::user()->likes()->where('post_id', $post->id)->first()->like == 0 ?
'You don\'t like this post':'Dislike' : 'Dislike' }}</a>
<script>
var urlLike = '{{ route('like') }}';
</script>
route:
Route::post('/like', [
'uses' => 'PostController#postLikePost',
'as' => 'like'
]);
listener + Ajax Call:
$('.like').on('click', function(event){
event.preventDefault();
postId = event.target.parentNode.parentNode.dataset['postid'];
var isLike = event.target.previousElementSibling == null;
//console.log(postId+' '+isLike);
$.ajax({
method: 'POST',
url: urlLike,
data: {isLike: isLike, postId: postId, _token: token}
})
.done(function(){
console.log(event.target.innerText);
event.target.innerText = isLike ? event.target.innerText == 'Like' ? 'You like this post':'Like' : event.target.innerText == 'Dislike' ? 'You don\'t like this post':'Dislike' ;
if(isLike){
event.target.nextElementSibling.innerText = 'Dislike';
} else{
event.target.nextElementSibling.innerText = 'Like';
}
});
});
Controller:
public function postLikePost(Request $request){
$post_id = $request['postId'];
$is_like = $request['isLike'] === 'true';
$update = false;
$post = Post::find($post_id);
if(!$post){
return null;
}
$user = Auth::user();
$like = $user->likes()->where('post_id', $post_id)->first();
if($like){
$already_like = $like->like;
$update = true;
if($already_like == $is_like){
$like->delete();
return null;
}
}else{
$like->like = $is_like;
$like->post_id = $post_id;
$like->user_id = $user_id;
}
// This is working when the controller is updating but broken when saving
if($update){
$like->update();
} else{
$like->save();
}
return null;
}
P.S:
I'm new to phpstorm and laravel, if you know a good way to debug/log/watch variable values like in eclipse, that would be appreciated.
from what I see the ajax request is using a wrong url it's requesting localhost/public/likes instead of localhost/your_project/public/like
$.ajax({
method: 'POST',
url: 'like',
data: {isLike: isLike, postId: postId, _token: token}
})
should work... or
<script>
var urlLike = '{{ URL::to('like') }}';
</script>
not sure why route() is not working though

how to run a laravel function and pass field val through ajax

hey I want to run a function in my controller using the $.get to pass what is the cod that I want to execute my querys then create my excel file
my route, that's working if I type in adreess bar of my browser my file downloads.
Route::get('relatorios/exportar', array('as' => 'relatorios.exportar', 'uses' => 'ReportsController#exportar'));
my controller: note that works if i change Input::get('cod') to any number
public function exportar()
{
$cod = Input::get('cod');
set_time_limit(0);
$datainicio = DB::table('tb_periodo')->where('cod', $cod)->pluck('periodo_inicio');
$datafinal = DB::table('tb_periodo')->where('cod', $cod)->pluck('periodo_fim');
$mes = DB::table('tb_periodo')->where('cod', $cod)->pluck('mes_referencia');
$horarioQuery = $this->horario->with(array('funcionario', 'item_contabil'))
->whereBetween('data', array($datainicio, $datafinal))
->whereNull('deleted_at')
->orderBy('cod_funcionario')
->orderBy('data', 'ASC')
->get();
$horarios = reset($horarioQuery);
$nome = 'Marcações'.$mes.'-'.Carbon::now()->year;
$this->horario->allToExcel($nome, $horarios);
}
my JS: the console log shows the right number but nothing happens
$('#exportar').on('click', function(){
var cod = $("#cod").val();
$.get('exportar', {cod: cod}, function(data) {
console.log(cod);
});
});
my view:
(edited) Hi! sorry I just could see right now. how my form would be ? i did like this:
{{Form::open(array("exportar","id"=>"ajaxForm"))}}
{{ Form::submit('Exportar', array('id' => 'exportar', 'class' => 'exportar')) }}
{{ Form::hidden('cod', $cod, array('id' => 'cod', 'class' => 'cod')) }}
{{ Form::close() }}
I want to pass the COD in the hidden field to the generate the file, my funcition works I just need to pass this number and dont know what's happening.
thanks!
Hello there fellow Laraveller!
At first please use POST, not GET! This means you have to change your route to Route::post...
After that use AJAX, not get like this:
$(".ajaxForm").submit(function(e) {
e.preventDefault();
var postData = $(this).serialize();
var url = $(this).attr('action');
$.ajax({
type: "POST",
data: postData,
dataType: 'JSON',
url: url,
beforeSend: function() {
$(".preloaderContainer").fadeIn(); // example
}
}).done(function(response) {
console.log(response);
}).fail(function() {
console.log(response);
});
So the trick in here is the following:
On submitting your form we need to catch the event 'e' and prevent the page from going to that controller by e.preventDefault();
After that the serialize method gets all iputs fields information and their names and creates query string that is posted to the certain url (method)
and the 'url' variable gets information from the forms attribute 'action'!
In your Method you should do this to check if everything is okay:
$inputs = Input::except('_token');
return Response::json($inputs);
Regards and tell me if you need any other help and explanation!
that worked
I gave up from using ajax and just tried with routes
Route::get('relatorios/exportar/{cod}', array('as' => 'relatorios.exportar', 'uses' => 'ReportsController#exportar'));
my controller
public function exportar($cod)
{
set_time_limit(0);
$datainicio = DB::table('tb_periodo')->where('cod', $cod)->pluck('periodo_inicio');
$datafinal = DB::table('tb_periodo')->where('cod', $cod)->pluck('periodo_fim');
$mes = DB::table('tb_periodo')->where('cod', $cod)->pluck('mes_referencia');
$horarioQuery = $this->horario->with(array('funcionario', 'item_contabil'))
->whereBetween('data', array($datainicio, $datafinal))
->whereNull('deleted_at')
->orderBy('cod_funcionario')
->orderBy('data', 'ASC')
->get();
$horarios = reset($horarioQuery);
$nome = 'Marcações'.$mes.'-'.Carbon::now()->year;
$this->horario->allToExcel($nome, $horarios);
}
view:
{{ link_to_route('relatorios.exportar', 'Exportar para excel', array($cod), array('class' => 'btn btn-success')) }}
that's solved for me, because dont load another page and download the correct file.
thx for the help!!

Laravel chained/linked select box failed to load resource status 500 internal server error

Complete Edit
I've edited my original question as I've refined my code which has put me in a much better position to define a better error
Hi I'm creating a chained select box that will once a client is selected find the clients projects.
The ajax is doing its job it knows which client has been selected and my console tells me the following:
Failed to load resource: the server responded with a status of 500 (Internal Server Error) http://itempus.dev/task/clientsprojects?option=5
The above option value refers to the client id which I want to pass into the projects db and find the clients projects. I'm not sure what I am doing wrong and would appreciate some help in a somewhat complex task for a newbie.
TaskController
public function create()
{
$tasks = Auth::user()->tasks;
$client_options = DB::table('clients')->orderBy('client_name', 'asc')->lists('client_name','id');
$team_options = DB::table('teams')->orderBy('team_member_name', 'asc')->lists('team_member_name','id', 'team_member_category');
return View::make('tasks.create', array('project_options' => $project_options, 'team_options' => $team_options, 'client_options' => $client_options));
}
public function clientsprojects() {
$input = Input::get('option');
$client_id = Project::find($input);
$projects = DB::table('projects')->where('client_id', $client_id->id)
->orderBy('project_name')
->lists('id','project_name');
$models = $project->projects();
return Response::eloquent($models->get(array('id','project_name')));
}
views/tasks/create.blade.php
{{ Form::open(array('action' => 'TaskController#store', 'id' => 'createuser')) }}
<div class="form-group">
#if(count($client_options)>0)
{{ Form::label('select_client', 'Assign to Client', array('class' => 'awesome client_option')); }}
{{ Form::select('client', $client_options , Input::old('client'), array('class' => 'tempus_select client_option', 'id' => 'select_client')) }}
#endif
</div>
<div class="form-group deletegates">
{{ Form::label('select_client', 'Assign to Project', array('class' => 'awesome')); }}
{{ Form::select('project', array_merge(array('default' => 'Please Select')), 'default', array('class' => 'tempus_select', 'id' => 'project_select')) }}
</div>
{{ Form::submit('Create the task!', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
<script>
$(document).ready(function($){
$('#select_client').change(function(){
$.get("{{ url('task/clientsprojects')}}",
{ option: $(this).val() },
function(data) {
var model = $('#project_select');
model.empty();
$.each(data, function(index, element) {
model.append("<option value='"+ element.id +"'>" + element.name + "</option>");
});
});
});
});
</script>
Route.php
I've also defined my route as so:
Route::get('task/clientsprojects', function(){
$input = Input::get('option');
$client_id = Project::find($input);
$projects = DB::table('projects')->where('client_id', $client_id->id)
->orderBy('project_name')
->lists('id','project_name');
$models = $project->projects();
return Response::eloquent($models->get(array('id','project_name')));
});
I assume that the create function in the TaskController works correctly and creates the first drop down menu for the clients.
When this drop down changes value, an ajax get request is sent to the server but you receive a 500 (Internal Server Error) because something is wrong with your queries.
So lets try to fix that.
Route::get('task/clientsprojects', function(){
// Get the option value which is the client_id
$client_id = Input::get('option');
// Get all projects that have client_id = $client_id
$projects = DB::table('projects')
->where('client_id', $client_id)
->orderBy('project_name')
->lists('id','project_name');
//Return the response to the client
return Response::json($projects);
});
Now the response is back to the client. Replace your JavaScript with the following.
$(document).ready(function($){
$('#select_client').change(function(){
$.get("{{ url('task/clientsprojects')}}", { option: $(this).val() },
function(data) {
var projects = $('#project_select');
projects.empty();
$.each(data, function(key, value) {
projects
.append($("<option></option>")
.attr("value",key)
.text(value));
});
});
});
});
And you're good to go.
You need some JavaScript (AJAX) to accomplish this, basically, a select element has a change event which fires upon changing any value, I mean, if user selects an item then the change event fires and you have to declare a change event handler in JavaScript for you client combo/select element. There are so many ways to use an event handler, for example (Your select should contain an id as id='select_client'):
window.onload = function(){
document.getElementById('select_client').onchange = function(){
// ...
};
};
Or you may use addEventListener and if you use a library like jQuery then you may do it using something like this:
$(function(){
$( "#select_client" ).change(function(e) { // i.e. '/get_progects/{clientId}'
e.preventDefault();
var clients = $(this);
$.getJson('yuordomain/get_projects/' + clients.val(), function(response){
// id = 'projects' for projects combo.select
var projects = $('#projects');
projects.empty();
$.each('response.projects', function(k, v){
var option = $('<option/>', {'id':v.id, 'text':v.projectName});
projects.append(option);
});
});
});
});
This will simply, fetch the data (projects depending on the selected client) from server when ever a user selects the client dropdown box and to make this work you need to declare a route for fetching the projects dasta, for example:
Route::get('/get_progects', function($client_id){
// I'm using a closure here but you should use a class method
$projects = Project::where('client_id', $client_id)
->orderBy('project_name')
->lists('id','project_name');
return Response::json(compact('projects'));
});
This is the very basic idea and hope you can implement it in your project now.

Categories