In ajax I have 3 objects 'emp_info, leave_detail, and leave_items' in controller I don't know how to get record of each object. Could you help me please?
$.ajax({
type: 'POST',
url: '/leave-request-initiator/store',
data: {_token: $('#_token').val(), emp_info: $('#frm_emp_info').serialize(), leave_detail: $('#frm_leave_detail').serialize(), leave_items: leave_items},
beforeSend: function () {
console.log('sending');
},
success: function (response) {
console.log(response);
}
});
Controller.
public function store(Request $request)
{
$data = $request->all();
foreach ($data->emp_info as $item){
$empcode = $item['EMPCODE'];
}
$leaveDetail = new HREmpLeave([
'EMPCODE' => $empcode,
'LEAVECODE' => $request->get('LEAVECODE'),
'FROMDATE' => $request->get('FROMDATE'),
'TODATE' => $request->get('TODATE'),
'BACKTOWORKON' => $request->get('BACKTOWORKON'),
'NODAY' => $request->get('NODAY'),
'REMARK1' => $request->get('REMARK1')
]);
$leaveDetail->save();
}
Change this:
$data = $request->all();
foreach ($data->emp_info as $item){
$empcode = $item['EMPCODE'];
}
to this:
$emp_info = parse_str($request->emp_info); //parse into a array
$empcode = $emp_info['EMPCODE'];
Related
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)
}
})
}
i want to set condition, if teacher already exist in database then update record, if id doesn't exist then add record in database. how can i achieve it using ajax in laravel?
Update.js:
jQuery(document).ready(function($) {
$('#update-data').on('click',function(){
alert("ok");
$.ajax({
type: "POST",
url: "teachers/" + $('#update-data').attr("value"),
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data : $(this).serialize(),
beforeSend: function() {
},
success: function (data) {
alert("ok");
},
});
});
});
Store.Js:
jQuery(document).ready(function($) {
$("#add-data").submit(function (e) {
$.ajax({
type: "POST",
url: "teachers",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
data.responseJSON;
refreshTable();
},
});
});
});
Update Controller:
public function update(TeacherRequest $request, $id)
{
$teacher = Teacher::find($id);
if($teacher->save()){
return response()->json([
'status' => 'success',
'msg' => 'esecond has been updated'
]);
}
}
Store Controller:
public function store(Request $request)
{
$teacher = new Teacher;
$teacher=teacher::create($request);
}
There's a custom method for this
$teacher = Teacher::firstOrCreate($id, [
// Pass data here
]);
And if you want to check manually and traverse the request to another method
public function update(TeacherRequest $request, $id)
{
$teacher = Teacher::find($id);
if (is_null($teacher)) { // If model not found, pass request to store method
$this->store($request);
}
if($teacher->save()){
return response()->json([
'status' => 'success',
'msg' => 'esecond has been updated'
]);
}
}
From the docs
Hope this helps
Eloquent provides a updateOrCreate method so you can update or create a record.
$teacher = Teacher::updateOrCreate([
// attributes to search for
'name' => 'Test Teacher',
], [
// values
'grade' => 6,
]);
This would find a teacher with name 'Test Teacher' and update grade to 6 or create a new teacher with name 'Test Teacher' and grade set to 6.
"You may also come across situations where you want to update an existing model or create a new model if none exists. Laravel provides an updateOrCreate method to do this in one step. Like the firstOrCreate method, updateOrCreate persists the model ..." - Laravel 6.0 Docs - Eloquent - Other Creation Methods - updateOrCreate
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.
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)
I'm new here :). I have a problem with my code. I'm working with laravel 5.1 and Blade. In my view I have:
function getNumber(){
values = [];
values[0] = $('#receipt_type_id').val();
values[1] = $('#provider_id').val();
$.ajax({
url: "{{{ url('receipts/showByNumber') }}}",
type: "get",
data: {ids: values},
dataType: "json",
success: function (data) {
//i do something
}
});
}
In my route:
Route::get('receipts/showByNumber', ['as' => 'receipt.showByNumber', 'uses' => 'ReceiptsController#showByNumber']);
And in my controller:
public function showByNumber($values){
$receipt_type_id = $values[0];
$provider_id = $values[1];
//Find the receipt to edit
...
...
}
The error is GET http://manchego.app/receipts/showByNumber?ids%5B%5D=1&ids%5B%5D=2 500 (Internal Server Error). I read another topics with the same problem that I have but I can't understand where is my problem.
Thanks in advance! :)
You could type-hint the Request class (recommended):
public function showByNumber(\Illuminate\Http\Request $request)
{
$allParams = $request->all(); // returns an array
$provider_id = $request->get('provider_id');
}
Or you could use the Request facade:
public function showByNumber()
{
$allParams = \Request::all(); // returns an array
$provider_id = \Request::get('provider_id');
}