Post Error 500 adding a new row using Eloquent - php

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

Related

Not getting ajax response on the server even with 200 status

I have added an ajax call on the blur of input and click on submit button to verify the email exist or not.
Code is simple to just check the existing data and return true false in response.
On local it is working totally fine but on client's server the ajax is not responding as expected. The response status is 200 but nothing in the preview of response on the console of the browser. For more clarity adding the picture.
Ajax code:
jQuery.ajax({
url : "{{ path('sales_account_email_exist') }}",
type : "POST",
cache : false,
data : {email:email_val,user_id:$("#user-id").val()},
success : function(data){
$(".loader").hide();
var obj = $.parseJSON(data);
if(obj===false)
{
$("#duplicate_email_exist").css("display","inline-block");
errorMessage = '<i class="warning sign icon"></i>' + email_val + ' : Email already exists in the system.';
$("#duplicate_email_exist").html(errorMessage);
email_exist_valid = false;
}
else
{
$("#duplicate_email_exist").css("display","none");
$("#duplicate_email_exist").html("");
email_exist_valid = true;
}
}
})
Ajax backend code:
/**
* #Route("/exist-email", name="sales_account_email_exist",methods={"GET","POST"})
*/
public function emailExist(Request $request): Response
{
$email = $request->get('email');
$user_id = $request->get('user_id');
if (isset($email) && !empty($email)) {
if (isset($user_id) && !empty($user_id)) {
$query = $this->em->createQueryBuilder()
->select('u.id', 'u.email')
->from('App\Entity\User', 'u')
->andWhere('u.email =\'' . str_replace("'", '', $email) . '\'')
->andWhere('u.id !=' . $user_id)
->getQuery();
} else {
$query = $this->em->createQueryBuilder()
->select('u.id', 'u.email')
->from('App\Entity\User', 'u')
->where('u.email = :email')
->setParameter('email', $email)
->getQuery();
}
$email_exist = $query->getArrayResult();
if (!empty($email_exist)) {
return new response('false');
} else {
return new response('true');
}
}
return new response('true');
}
jQuery.ajax({
url : "{{ path('sales_account_email_exist') }}",
type : "POST",
cache : false,
data : {email:email_val,user_id:$("#user-id").val()},
success : function(data){
$(".loader").hide();
var obj = $.parseJSON(data);
if(obj===false)
{
$("#duplicate_email_exist").css("display","inline-block");
errorMessage = '<i class="warning sign icon"></i>' + email_val + ' : Email already exists in the system.';
$("#duplicate_email_exist").html(errorMessage);
email_exist_valid = false;
}
else
{
$("#duplicate_email_exist").css("display","none");
$("#duplicate_email_exist").html("");
email_exist_valid = true;
}
},
// add this
error: function (request, status, error) {
alert(request.responseText); // <-- your code will be here
}
})
Check logs
Add error: statement after success:, probably this will help to find problem.

Laravel 5.4 - Undefined variable: passing variable from controller to view

I'm new to Laravel. I have searched this site but can't find specific help. I'm trying to pass a value of a variable(which is $Like) from Controller to the blade view, but the browser gives an error of
Undefined variable: Like
Here is the part of my view code (dashboard.blade.php):
#foreach($posts as $post)
<article class="post" data-postid="{{ $post->id }}">
<div class="interaction">
{{$Like }} |
</div>
</article>
#endforeach
<script>
var token = '{{ Session:: token() }}';
var urlLike = '{{ route('like') }}';
</script>
part of my controller(PostController.php) code:
public function LikePost(Request $request) // post type
{
$post_id = $request['postId']; // postId from script.js
$is_Like = $request['isLike'] === 'true'; // from script.js ...
$update = false;
$post = Post::find($post_id);
$user = Auth::user();
$like = $user->likes()->where('post_id', $post_id)->first();
$like->like = $is_Like;
$like->user_id = $user->id;
$like->post_id = $post->id;
$Like = $like ? $like->like == 1 ? 'You like this' : 'Like' : 'Like';
return redirect()->route('dashboard')->with('Like', $Like);
}
here is the part of my route code:
//for like post
Route::post('/like', [
'uses'=> 'PostController#LikePost',
'as'=> 'like'
]);
here is my script.js:
$('.like').on('click', function (event) {
event.preventDefault();
postId = event.target.parentNode.parentNode.dataset['postid'];
// check whether previous element of like/dislike is null or not
var isLike = event.target.previousElementSibling == null;
$.ajax({
method: 'POST',
url: urlLike,
data: {
isLike: isLike,
postId: postId,
_token: token
}
}).done(function () {
event.target.innerText = isLike ? event.target.innerText == 'Like' ? 'You like this' : 'Like' : event.target.innerText == 'Dislike' ? 'You dislike this' : 'Dislike';
if (isLike) {
event.target.nextElementSibling.innerText = 'Dislike';
} else {
event.target.previousElementSibling.innerText = 'Like';
}
});
});
I tried in many ways. but every time it shows me an error,
undefined variable: Like in dashboard.blade.php
Anyone help please.....
You are redirecting to a route, which in turn calls its own controller method that passes down variables to dashboard.blade.php
When you do redirect()->route('dashboard')->with('Like', $Like) you are essentially flashing some data to the session.
You need to use session('Like')to access variables in blade when redirecting to a route and flashing variables.
#foreach($posts as $post)
<article class="post" data-postid="{{ $post->id }}">
<div class="interaction">
#if (session('Like'))
<div class="alert alert-success">
{{ session('Like') }} |
</div>
#endif
</div>
</article>
#endforeach
<script>
var token = '{{ Session:: token() }}';
var urlLike = '{{ route('like') }}';
</script>
Read more here https://laravel.com/docs/5.4/responses#redirecting-with-flashed-session-data

How to pass the data to route using jquery in Laravel

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

JQuery Ajax Post results in 500 Internal Server Error (using Laravel 5.1)

I am trying to update or insert in my database table(user_shows) whenever i click a link without going to another page. So, I used ajax and below is my code:
$("#fave").click(function(){
var url = $(this).attr("data-link");
var data = {
_token: $(this).data('token'),
id: $(this).attr("name")
};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "/addFavorites",
type:"post",
data: data,
success:function(data){
alert(data);
},error:function(){
alert("error!!!!");
}
}); //end of ajax
});
</script>
For the html:
<a id="fave" name="{{ $query[0]->tvSeriesID }}" href="#" data-link="{{ url('/addFavorites') }}" data-token="{{ csrf_token() }}" title="Mark this TV show a favorite!"><span class="glyphicon glyphicon-star" aria-hidden="true"></span> Favorites</a>
For the routes:
Route::post('/addFavorites', function() {
$id = Input::get('id');
$data = $id;
return $data;
});
Output: data fetch is correct
enter image description here
But when I put some codes in my routes I get POST http://localhost:8000/addFavorites 500 (Internal Server Error)
Here is my new routes code
Route::post('/addFavorites', function() {
$id = Input::get('id');
$query = DB::table('user_shows')
->where('tvSeriesID', '=', $id)
->where('userID', '=', Auth::id())
->get(['favorite']);
if(empty($query))
{
//saving to DB
$faves = new UserShow;
$faves->tvSeriesID = $id;
$faves->userID = Auth::id();
$faves->favorite = 1;
$faves->save();
$data = "Show is added to Favorites";
return $data;
}
else
{
if($query[0]->favorite == 1) {
$data = "Show is already in Favorites";
}
else {
UserShow::where('tvSeriesID', $id)
->where('userID', Auth::id())
->update(['favorite' => 1]);
$data = "Show is added to Favorites";
}
$data = "Show is added to Favorites";
return $data;
}
});
Is my coding wrong? Hope you can help me. Thanks in advance.
I finally figured out why it errors. I did not include the namespace of the model that I used which is UserShow. When I added the namespace it worked!
This is the line I added use App\UserShow; .
Thank you so much #Jay Blanchard for your quick response.

AJAX throws error 500 only when PHP function is empty

I'm completely puzzled to why this happens, I've been messing on this for a few hours and I'm going crazyyyy! I am trying to update my DB when a checkbox is toggled on or off. The success response works if my PHP function I'm calling is empty, but fails whenever I add PHP. Note I'm on Laravel 3, and I've tried enabling or disabling CSRF filtering, no luck.
My JS:
$seenTD = $('td.seen_by_user');
$seenTD.each(function() {
$this = $(this);
var $seenLabel = $this.find('label');
var $seenInput = $this.find(':checkbox');
$seenInput.change(function() {
var _csrf = $('input[name="csrf_token"]').val();
var chkName = $(this).attr('name');
var checkVal = $(':checkbox[name='+chkName+']').prop('checked'); //true or false
var id = $this.find('input[name="reminder_id"]').val();
$.ajax({
url: 'update',
type: 'POST',
data: 'seen='+checkVal+'&reminder_id='+id+'&csrf_token='+_csrf,
success: function(data) {
console.log(data);
if($seenInput.is(':checked')) {
$seenLabel.removeClass('unchecked').addClass('checked');
$seenLabel.find('span').text('Oui');
}
else {
$seenLabel.removeClass('checked').addClass('unchecked');
$seenLabel.find('span').text('Non');
}
}
});
});
});
My PHP
public function post_update() {
$request = Request::instance();
$content = $request->getContent();
$id = $content['id'];
$seen = $content['seen'];
if($seen == 'true') {
$seen = 1;
}
if($seen == 'false') {
$seen = 0;
}
DB::table('reminders')->where('id', '=', $id)->update(
array(
'seen_by_user' => $seen
));
}
For the sake of maybe helping someone, as this is my first working AJAX, I'll explain how I got it to work, as well as supply working code. I'm not claiming this is the best way to do it, so if anyone has their word to say, don't hesitate :)
There were multiple issues, from Javascript insconsistency returning the row ID I needed for the database update, to the PHP function, and the way I was grabbing the POST data.
To get it to work, I played on Fiddler, retrieved the error message that Laravel throws at me. And I could debug from there :)
My working code is :
JS:
$('td.seen_by_user :checkbox').change(function() {
$this = $(this);
var $label = $this.siblings('label');
var id = $this.attr('data-id');
var _csrf = $this.siblings('input[name="csrf_token"]').val();
var value = $this.prop('checked');
$.ajax({
url: 'update',
type: 'POST',
data: {"seen_by_user": value, "id": id, "csrf_token": _csrf},
success: function(data) {
if($this.is(':checked')) {
$label.removeClass('unchecked').addClass('checked');
$label.find('span').text('Oui');
}
else {
$label.removeClass('checked').addClass('unchecked');
$label.find('span').text('Non');
}
}
});
});
PHP
function post_update() {
$id = $_POST['id'];
$seen = $_POST['seen_by_user'];
if($seen == 'true') {
$seen = 1;
}
if($seen == 'false') {
$seen = 0;
}
$update_reminder = DB::table('reminders')->where('id', '=', $id)->update(
array('seen_by_user' => $seen));
}
And my HTML (Blade Template from Laravel, where {{ }} brackets are simply echo's, and #foreach is a )
#foreach ($reminders as $reminder)
...
<td class="seen_by_user">
<form class="ajax" action="update" method="POST">
{{ Form::token() }}
{{ Form::checkbox('seen_'.$reminder->id, 1, $reminder->seen_by_user, array('id' => 'seen_'.$reminder->id, 'data-id' => $reminder->id)) }}
<label class="seen {{ ($reminder->seen_by_user == 1 ? 'checked' : 'unchecked' ) }}"for="{{ 'seen_'.$reminder->id }}"><i class="read"></i><span>{{ ($reminder->seen_by_user == 1 ? 'Oui' : 'Non') }}</span></label>
</form>
</td>
...
#endforeach
data should be an object like this
data: {"seen": checkVal, "reminder_id": id, "csrf_token": _csrf},
The $.ajax method will take care of the presentation and transmission.

Categories