Link to a specific part of a page - php

I have a div that has lots of posts which is created dynamically from the database. The div has input for comment facility as well. I have no problems in posting the comments and I do it using a POST method. Then I redirect to the page using return redirect('/'); method. But it links to the beginning to the page which doesn't create a good impression on the user. The user might be in the middle of the page and when he/she comments he will go to the beginning of the page and will have to scroll down again. Luckily, I have the divs with class equal to the post_id. So, isn't there any method to go to the post in which the user posted using that class?

attach the id with the url like /#post-id

Inside your contorller where you are processing and saving the comments:
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
public function yourCommentSaveFunction()
{
...
//Get the Post ID and store in $postid
return Redirect::to(URL::previous() . '#' .$postid);
}
This should work fine.
But the best way would be to use AJAX to post comments.
Edit (As request by OP)
THE AJAX METHOD
Controller will be something like:
public function saveComment(Request $request)
{
//you do the saving part..
...
$comment = $request->comment;
//after saving the comment return a json response
//you can also send other varibales like username, created at etc..
return Response::json(array(
'success' => true,
'comment' => $comment,
));
}
Route:
Route::post('/save-comment', [
'as' => 'save-comment',
'uses' => 'yourController#saveComment',
]);
And your View:
<form action="{{ route('save-comment') }}" class="comment-form">
<input type="text" name="comment">
<input type="submit" name="submit">
<input type="hidden" name="_token" value="{{ csrf_token() }}"
<div class="comment"></div>
</form>
<script>
$('.comment-form').submit(function(event){
event.preventDefault();
var comment = $this.val();
var token = $('.token').val();
var $url = "{{ route('save-comment') }}";
$.ajax({
url: route,
type: 'POST',
data: {_token: token, comment: comment},
dataType: 'JSON',
success: function (data) {
$(".comment").append('<div class="new-comment">' +data.comment +'</div>');
},
error: function(data) {
console.log("Something went wrong");
}
});
});
</script>
Please note: this is just a sample code.

Related

Laravel undefined variable into blade after calling from JSON

I've Signup form in my website. It was properly submitting before. Now I wanted to submit my form using ajax and wanted to return a variable from controller into JSON that I will use into blade file.
The form is submitting and values are showing into database but after redirection, it returns error.
Undefined variable: seller in report blade
I tried to decode my variable to make it work but still the same error.
How would I make it work?
Report-Blade
#foreach(json_decode($seller, true) as $row)
<a href="{{route('Report', $row->id) }}" >
{{ __('Show Report of ')}} {{$row->car_title}}
</a>
#endforeach
Controller
$seller = Sellers::take(1)->latest()->get();
return response(view('report',array('seller'=>$seller)),200, ['Content-Type' =>
'application/json']);
JavaScript
$("#submit-all").click(function(e){
e.preventDefault();
var _token = $('input[name="_token"]').val();
$.ajax({
type: "post",
url: "{{ route('form_for_private_sellers') }}",
data : $('#msform').serialize() + "&_token=" + _token,
dataType: 'JSON',
beforeSend: function(){
// Show loading image
$("#se-pre-con").show();
},
success: function(data) {
window.location = "http://127.0.0.1:8000/report/";
},
complete:function(data){
// Hide loading image
$("#se-pre-con").hide();
}
});
});
As understood from your comments,
window.location = "http://127.0.0.1:8000/report/";
will hit the route
Route::get('/report', function () {
return view('report');
})->name('private_seller_report');
Report blade expects a variable named $seller, and it is not being sent from the route. You would need to change the route to something similar to this:
Route::get('/report', function () {
$sellers = Seller::get(); //your logic
return view('report', ['seller' => $sellers]);
})->name('private_seller_report');
Alternatively you can point the route to a method in a controller if you want to avoid bulking up your routes.
you need two route for this
first for rendering blade
return view('report');
and the second for fetch seller
$seller = Sellers::latest()->take(1)->get();
return $seller

Method not allow (PUT) With AJAX Call in Laravel 5.2

My Blade is:
{!! Form::open(['method' => 'PUT', 'id' => 'confirmTCU',
'action' => ['TournamentUserController#confirmUser', $tournament->slug, $categoryTournament->id,$user->slug ]]) !!}
It generates my Form:
<form method="POST" action="http://laravel.dev/tournaments/bisque/categories/1/users/admin/confirm" accept-charset="UTF-8" id="confirmTCU">
<input name="_method" type="hidden" value="PUT">
<input name="_token" type="hidden" value="tiaIHtctMbo1NwbEK8TqoKOyrN8ZSyeQELSyYL9A">
<button type="submit" class="btn btn-flat text-warning-600 btnConfirmTCU" id="confirm_bisque_1_admin" data-tournament="bisque" data-category="1" data-user="admin">
<i class="text-danger glyphicon glyphicon-remove-sign"></i>
</button>
</form>
My AJAX is:
$('.btnConfirmTCU').on('click', function (e) {
e.preventDefault();
$(this).prop("disabled", true);
var inputData = $('#formDeleteTCU').serialize();
//var tournamentSlug = $(this).data('tournament');
var categoryId = $(this).data('category');
var userSlug = $(this).data('user');
$.ajax(
{
type: 'PUT',
url: url + '/categories/' + categoryId + '/users/' + userSlug + '/confirm',
data: inputData,
success: function (data) {
...
},
error: function (data) {
...
}
}
)
});
My route is:
Route::put('tournaments/{tournamentId}/categories/{categoryTournamentId}/users/{userId}/confirm', 'TournamentUserController#confirmUser');
My Controller is:
public function confirmUser($tournamentSlug, $tcId, $userSlug)
{
$user = User::findBySlug($userSlug);
$ctu = CategoryTournamentUser::where('category_tournament_id', $tcId)
->where('user_id', $user->id)->first();
$ctu->confirmed ? $ctu->confirmed = 0 : $ctu->confirmed = 1;
$ctu->save();
return redirect("tournaments/$tournamentSlug/users");
}
I saw a lot of topics about it, but none resolved my issue.
As PUT is not allowed for most of browser, Laravel send it like POST, but includes a hidden field _method with PUT value.
Beside, I am able to perform DELETE actions, but not PUT...
Besides, method works perfect when not using AJAX.
Where is my problem???
Your code should work fine, but it looks like you are serializing the wrong form. Your current code shows var inputData = $('#formDeleteTCU').serialize();, but the id for the form you've shown is confirmTCU.
Change your ajax type from 'PUT' to 'POST', Laravel will read your parameter '_method' and will take that 'POST' like a 'PUT'.

Why is my Ajax Form submit not working in Laravel 5

I am working on this laravel 5 app and I can't seem to figure out why my Ajax call is not working for this particular form because it has been working well for other forms. Sample code below.
{!! Form::model($training, ['url' => 'trainings/' . $training->id,
'method' => 'PUT',
'class' => 'form-horizontal',
'id' => 'edit_training_form',
'role' => 'form']) !!}
// Form body
{{ Form::close() }}
Ajax Call Sample code below:
$("document").ready(function() {
$("#edit_academic_form").on('submit', updateAcademic);
$("#edit_training_form").on('submit', updateTraining);
}
function ajaxCall(context) {
$.ajax({
type: "PUT",
data: context.serialize(),
url: context.attr('action'),
dataType: 'json',
cache: false,
beforeSend: function() {
$(".validation-errors").hide().empty();
$(".success-message").hide().empty();
},
success: function(data){
$(".success-message").append(data.message).show();
$(".success-message").delay( 2000 ).fadeOut();
},
error: function(data){
var errors = data.responseJSON;
console.log(errors);
// Render errors with JS
$.each(errors, function(index, value)
{
if (value.length != 0)
{
$(".validation-errors").append('<li>'+ value +'</li>');
}
});
$(".validation-errors").show();
}
});
}
function updateTraining(e){
e.preventDefault();
ajaxCall($(this))
}
function updateAcademic(e){
e.preventDefault();
ajaxCall($(this))
}
The call for updateAcademic is working pretty well but updateTraining is not working. Firebug does not show any error. It's kind of doing some direct form submit. I have cleared browser cache to make sure the js is being read, change browser but no result. Looking at the source of the code from my browser the form is well defined (id is ok) as shown below:
<form method="POST" action="http://localhost:8000/trainings/1"
accept-charset="UTF-8" class="form-horizontal"
id="edit_training_form" role="form">
<input name="_method" type="hidden" value="PUT">
<input name="_token" type="hidden" value="QvvgMIWZN1VYGUOF2zGE8ALgVnAYaZUS5SseW4i5">
</form>
Edit
Firebug does not give any error. I have my controller like so:
public function update(UpdateTrainingRequest $request, $id)
{
$data = $request->all();
$this->training->save_training($data, $id);
$result['message'] = "Training Updated Successfully";
return response()->json($result);
}
When I hit save all I get is a blank browser page with the message:
{"message":"Training Updated Successfully"} suggesting the form is posting directly.
Appreciate help
The problem was with my js. My js look like so:
$("document").ready(function() {
limitCharacters();
$("#edit_academic_form").on('submit', updateAcademic);
$("#edit_training_form").on('submit', updateTraining);
}
The function limitCharacters() had some syntax errors thus preventing the codes beneath it from ever getting called hence reason why the Ajax didn't work. I resolved issues in limitCharacters and now everything is working fine.

500 internal server error while posting data to database with laravel 5 and ajax

Hi guys? am trying to post data to the database using laravel 5 and ajax..am also applying using csrf protection by adding
<meta name="_token" content="{!! csrf_token() !!}"/>
to my layout header and adding the following code to my footer:
<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
</script>
This is my form:
<form action="{{action('QuizController#postQuiz')}}" method="POST">
<div id="name-group" class="form-group">
<label for="name">Please type your question here</label>
<input type="text" class="form-control" name="question">
</div>
<button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>
</form>
This is my JS code:
var formData = {
'question' : $('input[name=question]').val(),
};
// process the form
$.ajax({
type : 'POST',
url : 'quiz',
data : formData,
dataType : 'json',
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console to see
console.log(data);
// ALL GOOD! just show the success message!
$('form').append('<div class="alert alert-success">' + data.message + '</div>');
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
This is my route:
Route::post('create/quiz', array(
'as' => 'post-quiz',
'uses' => 'QuizController#postQuiz'
));
When my controller is like the following:
public function postQuiz()
{
if(Request::ajax()) {
$question = Request::get('question');
$data['success'] = true;
$data['message'] = $question;
echo json_encode($data);
}
the ajax call works and it returns,
Object {success: true, message: "test question"}
but when I try posting data to the database using:
public function postQuiz()
{
if(Request::ajax()) {
$question = Request::get('question');
DB::table('questions')->insert([
'question' => $question,
]);
}
I get the following from the console
POST http://localhost/leoschool-laravel5/public/create/quiz 500 (Internal Server Error)
and
Object {readyState: 4, responseText: "{"success":true,"message":"test question"}<!DOCTYPE htm…l>↵</div>↵↵ </div>↵ </body>↵</html>", status: 500, statusText: "Internal Server Error"}
What could be the problem? Thanks..
A good place to start is with Chrome Developer tools. Load your page with the tools open and fire the event that does the AJAX request.
Under the network tab of the tools, it will show you every request made and allow you to preview the response as if you were not using AJAX. This will show you the laravel stack trace. I think the problem is that you're using facades and they're not namespaced correctly.
Change your controller function to this and see if it works:
public function postQuiz()
{
if(\Request::ajax()) {
$question = \Request::get('question');
\DB::table('questions')->insert([
'question' => $question,
]);
}
With the above instruction on how to use dev tools and with the corrected code, you should be able to fix your problem. A better way to write this code would look like this though:
// assuming you have these models setup
// this uses dependency injection
public function postQuiz(Request $request, Question $question)
{
if($request->ajax()) {
$newQuestion = $request->get('question');
//add fields here to create new question with
$question->create([ /*stuff*/ ]);
}

laravel 5 simple ajax retrieve record from database

How can I retrieve data using ajax? I have my ajax code that I've been using in some of my projects when retrieving records from database but dont know how to make it in laravel 5 because it has route and controller.
I have this html
<select name="test" id="branchname">
<option value="" disabled selected>Select first branch</option>
<option value="1">branch1</option>
<option value="2">branch2</option>
<option value="3">branch3</option>
</select>
<select id="employees">
<!-- where the return data will be put it -->
</select>
and the ajax
$("#branchname").change(function(){
$.ajax({
url: "employees",
type: "post",
data: { id : $(this).val() },
success: function(data){
$("#employees").html(data);
}
});
});
and in my controller, I declared 2 eloquent models, model 1 is for branchname table and model 2 is for employees table
use App\branchname;
use App\employees;
so I could retrieve the data like (refer below)
public function getemployee($branch_no){
$employees = employees::where("branch_no", '=', $branch_no)->all();
return $employees;
}
how to return the records that I pulled from the employees table? wiring from routes where the ajax first communicate to controller and return response to the ajax post request?
any help, suggestions, recommendations, ideas, clues will be greatly appreciated. Thank you!
PS: im a newbie in Laravel 5.
At first, add following entry in your <head> section of your Master Layout:
<meta name="csrf-token" content="{{ csrf_token() }}" />
This will add the _token in your view so you can use it for post and suchlike requests and then also add following code for global ajax setting in a common JavaScript file which is loaded on every request:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
So, you don't need to worry or add the csrf_token by yourself for methods who require this _token. Now, for a post request you may just use usual way to make an Ajax request to your Controller using jQuery, for example:
var data = { id : $(this).val() };
$.post(url, data, function(response){ // Shortcut for $.ajax({type: "post"})
// ...
});
Here, url should match the url of your route declaration for the employees, for example, if you have declared a route like this:
Route::post('employees/{branch_no}', 'EmployeeController#getemployee');
Then, employees is the url and return json response to populate the select element from your Controller, so the required code for this (including javaScript) is given below:
$.post('/employees/'+$(this).val(), function(response){
if(response.success)
{
var branchName = $('#branchname').empty();
$.each(response.employees, function(i, employee){
$('<option/>', {
value:employee.id,
text:employee.title
}).appendTo(branchName);
})
}
}, 'json');
From the Controller you should send json_encoded data, for example:
public function getemployee($branch_no){
$employees = employees::where("branch_no", $branch_no)->lists('title', 'id');
return response()->json(['success' => true, 'employees' => $employees]);
}
Hope you got the idea.
First check url of page from which ajax call initiates
example.com/page-using ajax
In AJAX
If you call $.get('datalists', sendinput, function())
You are actually making GET request to
example.com/page-using ajax/datalists
In Routes
Route::get('page-using-ajax/datalists', xyzController#abc)
In Controller Method
if (Request::ajax())
{
$text = \Request::input('textkey');
$users = DB::table('datalists')->where('city', 'like', $text.'%')->take(10)->get();
$users = json_encode($users);
return $users;
}
In Ajax Success Function
function(data) {
data = JSON.parse(data);
var html = "";
for (var i = 0; i < data.length; i++) {
html = html + "<option value='" + data[i].city + "'>";
};
$("#datalist-result").html(html);
}
Add in your route:
Route::post('employees', [
'as' => 'employees', 'uses' => 'YourController#YourMethod'
]);
Ajax:
Change:
url: "employees"
to:
url: "/employees"

Categories