The Ajax pagination to my account not run - ajax

I would like to create an Ajax pagination of my articles in my account, here is my code that I created but it does not work I do not know how to do.
MyaccountController
public function viewProfile($username) {
if($username) {
$user = User::where('username', $username)->firstOrFail();
} else {
$user = User::find(Auth::user()->id);
}
return view('site.user.account', [
'user' => $user,
'articles' => $user->articles()->orderByDesc('created_at')->paginate(4),
]);
}
I would like to have the javascript code
$(document).ready(function () {
$(document).on('click','.pagination a',function(e){
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
var url = $(this).attr('href');
$.ajax({
url: url,
method: 'GET',
data: {},
dataType: 'json',
success: function (result) {
if (result.status == 'ok'){
$('#userListingGrid').html(result.listing);
}else{
alert("Error when get pagination");
}
}
});
return false;
})
});

I would have a check on your controller for an ajax request like so:
public function viewProfile($username) {
if($username) {
$user = User::where('username', $username)->firstOrFail();
} else {
$user = User::find(Auth::user()->id);
}
if(request()->ajax()){
return response()->json(['user' => $user, 'articles' => $user->articles()->orderByDesc('created_at')->paginate(4);
}
return view('site.user.account', [
'user' => $user,
'articles' => $user->articles()->orderByDesc('created_at')->paginate(4),
]);
}
Then you don't have to load your view every time and you can let your javascript functions take care of the DOM manipulating of the results. Not sure if that's what you are looking for. I know that you would probably need a {{$articles->links()}} at the end of your view to go through each page.

Related

Larave/Ajax PUT 500 internal server error possible reasons

My console shows this error whenever I try to update my form using my ajax code:
PUT http://127.0.0.1:8000/clinical/bbr-category-configuration-update/1 500 (Internal Server Error)
Route:
Route::put('/bbr-category-configuration-update/{category_id}', [BBRCategoryConfigurationController::class,'update']);
Ajax:
$(document).on('click', '.update_category', function (e){
e.preventDefault();
var cat_id = $('#edit_cat_id').val();
var update_data = {
'category_name' : $('#edit_category_name').val(),
'category_description' : $('#edit_category_description').val(),
}
//token taken from laravel documentation
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "PUT",
url: "/clinical/bbr-category-configuration-update/"+cat_id,
data: update_data,
dataType: "json",
success: function (response){
// console.log(response);
if(response.status == 400) {
$('#category_formCheckUpdate').html("");
$('#category_formCheckUpdate').addClass('alert alert-danger');
$.each(response.errors, function (key, err_values) {
$('#category_formCheckUpdate').append('<li>'+err_values+'</li>');
});
} else if(response.status == 404) {
$('#category_formCheckUpdate').html("");
$('#category_notif').addClass('alert alert-success');
$('#category_notif').text(response.message);
} else {
$('#category_formCheckUpdate').html("");
$('#category_notif').html("");
$('#category_notif').addClass('alert alert-success');
$('#category_notif').text(response.message);
$('#editCategoryModal').modal('hide');
fetchcategory();
}
}
});
});
Controller:
public function update(Request $request, $category_id) {
$validator = Validator::make($request->all(), [
'category_name'=>'required|max:191',
'category_description'=>'required|max:191',
]);
if($validator->fails()) {
return response()->json([
'status'=>400,
'errors'=>$validator->messages(),
]);
} else {
$category_update = HmsBbrCategory::find($category_id);
if ($category_update) {
$category->category_name = $request->input('category_name');
$category->category_description = $request->input('category_description');
$category->update();
return response()->json([
'status'=>200,
'message'=>'Category Edited!',
]);
} else {
return response()->json([
'status'=>404,
'message'=>'Category Not Found',
]);
}
}
}
Things to note:
As you can see, my category_id is being read properly in: url: "/clinical/bbr-category-configuration-update/"+cat_id,. Also, I went ahead and did a console.log to show in my console that the whole table is getting retrieved. My main issue is this 500 internal server error. Not sure if it is by the PUT.
I also tried to change the PUT to POST or GET just to see if there is any change or other errors, but it's still the same 500 internal server issue. PS, my form has csrf.
Your problem is surely $category, you are using $category_update, not $category

Symfony 5 / Request Response : Get data with Ajax

when I try to get data in ajax, the returned object is empty
I send the id of the data I want to get in js :
function selectMessage(id) {
$.ajax({
url: '{{ path('back_translation_update') }}',
method: 'GET',
data: {id: id}
}).done(function (response) {
console.log(response)
})
}
$('.updateMessage').click(function (evt) {
evt.stopPropagation()
selectMessage($(this).data('id'))
})
in the controller I look for the data to return :
/**
* #Route("/update", name="back_translation_update", methods="GET|POST")
*/
public function getById(Request $request): Response
{
if ($request->isXMLHttpRequest()) {
$id = $request->get('id');
// dd($id);
$message = $this->translationService->getTranslationById($id);
// return new JsonResponse(['data' => $message]);
$response = new Response();
$response->setContent(json_encode([
'data' => $message,
]));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
I use a service because with the repository I get an error: getById () must be an instance of Symfony\Component\HttpFoundation\Response
with :
$repositoryMessage = $this->em->getRepository(TranslationMessage::class);
$message = $repositoryMessage->findOneBy(['id' => $id]);
so the service will look in the database:
public function getTranslationById($translation_id)
{
$query = $this->em->createQueryBuilder()
->from(TranslationMessage::class,'message')
->select('message')
->where('message.id = ?1')
->setParameter(1, $translation_id);
$message = $query->getQuery()->getResult();
// dd($message);
return $message;
}
all the dd() give the expected values:
into getById(): the id of the row sought
into getTranslationById(): the sought object
but in the XHR, data contains an empty object: uh:
same with a new JsonResponse, commented here
what did I miss? help
Use Aurowire to get messageRepository object and use $this->json() to return JsonResponse
/**
* #Route("/update", name="back_translation_update", methods="GET|POST")
*/
public function getById(Request $request, TranslationMessageRepository $messageRepository): JsonResponse
{
$id = $request->query->get('id');
$message = $messageRepository->find($id);
if(!$message) { return new NotFoundHttpException(); }
return $this->json([
'success' => true,
'data' => $message
]);
}
Define success function instead of done function
function selectMessage(id) {
$.ajax({
url: "{{ path('back_translation_update') }}",
method: 'GET',
data: { id: id }
success: function(data) {
console.log(data)
}
})
}

Eloquent not removing record from database on AJAX call

I'm trying to implement a "like" system for posts and there's an animated button by CSS and three AJAX calls through post.
One that will check if the post is already liked and will apply certain style to the button.
One that will add a record to the table in case that an user clicks the button.
One that will delete the record in case the user click it again.
AJAX code:
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url : '/like/alreadyLiked',
method : 'POST',
dataType : 'json',
data : {
slug : '{{Request::segment(2)}}',
user_id : '{{Auth::user()->user_id}}'
},
success : function (data) {
if(data.display === true){
$('#likelink').attr('class', 'like active')
}else{
$('#likelink').attr('class', 'like');
}
}
});
if($('#likelink').hasClass('like') && $('#likelink')[0].classList.length == 1){
$('#likelink').on('click', function(e){
e.preventDefault();
$.ajax({
url : '/like',
method : 'POST',
dataType : 'json',
data : {
slug : '{{Request::segment(2)}}',
user_id : '{{Auth::user()->user_id}}'
},
success : function(data){
if(data.display === true){
$('#likelink').attr('class', 'like');
}
}
});
});
}else{
$('#likelink').on('click', function(e){
e.preventDefault();
$.ajax({
url : '/dislike',
method : 'POST',
dataType : 'json',
data : {
slug : '{{Request::segment(2)}}',
user_id : '{{Auth::user()->user_id}}'
},
success : function(data){
if(data.display === true){
$('#likelink').attr('class', 'like');
}
}
});
});
}
});
PHP (Laravel code):
public function hasHeAlreadyLikedThisPost()
{
if(request()->ajax()){
$post = Post::where('slug', '=', request()->input('slug'))->first();
$post_id = $post->post_id;
$like = Like::where(['user_id' => request()->input('user_id'), 'post_id' => $post_id])->first();
if($like != null){
return response()->json(['display' => true]);
}else{
return response()->json(['display' => false]);
}
}
}
public function addLike()
{
if(request()->ajax()){
$slug = request()->input('slug');
$user_id = request()->input('user_id');
$post = Post::where('slug', '=', $slug)->first();
$like = Like::create(array(
'user_id' => $user_id,
'post_id' => $post->post_id
));
if($like->exists){
return response()->json(['display' => true]);
}else{
return response()->json(['display' => false]);
}
}
}
public function dislike()
{
$slug = request()->input('slug');
$user_id = request()->input('user_id');
$post = Post::where('slug', '=', $slug)->first();
$like = Like::where(['post_id' => $post->post_id, 'user_id' => $user_id])->delete();
return response()->json(['display' => false]);
}
The issue is that the "check" and the "insert" calls work but the "delete" one doesn't. In any case it will add a new record to the db and won't change the style.
I think that you have forgot to call first (or get)
$like = Like::where(['post_id' => $post->post_id, 'user_id' => $user_id])->first()->delete();
where() returns a query,but delete seems to work on eloquent model objects. So to get model object from query so you will call first() (like you did before), or get() to get an array and iterate through it applying delete() on each
Try by putting
$(document).on('click', '#likelink', function(e)
instead of $('#likelink').on('click', function(e)

Username Available Check Using Laravel 5 in Ajax

Username available check in my register form if I am enter the username after loader.gif is loading but I am not getting the result for username available or not.. give me any suggestion
This is My Controller:
public function name()
{
$username = Input::get('username');
$users = DB::table('user')
->where('username', $username)
->first();
if ( $users !== null )
{
return true;
}
return false;
return view('test/username');
}
This is My Route:
Route::get('test/name', 'PageController#name');
This is My Blade Template Ajax:
<script type="text/javascript">
$(document).ready(function(){
$("#username").change(function(){
$("#message").html("<img src='../images/loader.gif' /> checking...");
var username=$("#username").val();
//alert(username);
$.ajax({
type:"post",
dataType: "json",
url :"{{URL::to('test/name') }}",
data: {username: username},
success:function(data){
if(data==0){
$("#message").html("<img src='../images/yes.png' /> Username available");
}
else{
$("#message").html("<img src='cross.png' /> Username already taken");
}
}
});
});
});
ajax is not response to the controller this is my problem
This is because you need to send json using the response() method from the controller to your view file.
Try out this way:
Controller:
public function name(Request $request)
{
// your validation logic ..
$userFound = User::find($request->input('username'))
if($userFound !== null) {
return response([
'status' => 'failed',
'message' => 'User Not Found'
]);
}
return response([
'status' => 'success',
'message' => 'User Found'
]);
}
And then update your success method of AJAX handler:
$.ajax({
// ..
success: function(receivedData) {
console.log(receivedData);
}
// ..
});

AJAX Laravel Update Database

My issue is that I'm doing a simple AJAX Post to update a database record, but I'm not getting any error and it's still not updating the record. What am I overlooking?
Thanks!
JS:
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
if ($('.abc-status').css('display') == 'block')
{
abc.api({method: 'user'}, function(error, user) {
var userId = $('.oath_id').text();
var username = user.display_name;
console.log(username);
$.ajax({
type: "POST",
url: "oauth_authorization/abc/"+username,
data: {abc_username: username},
error: function(data){
console.log(data);
}
});
});
}
Controller:
public function postabcOAuth(Request $request, $username)
{
Auth::user()->update([
'abc_username' => $username,
]);
}
Route:
Route::post('/oauth_authorization/abc/{username}', [
'uses' => '\abc\Http\Controllers\OAuthController#postAbcOAuth',
'middleware' => ['auth'],
]);
You can change the post method in route path and also in ajax function
Using the following in the Controller, I was able to get it to work.
public function postAbcOAuth(Request $request, $username)
{
DB::table('users')
->where('id',Auth::user()->id)
->update(['abc_username' => $username]);
}

Resources