Like and dislike buttons for every post - php

Guys I just created like/dislike buttons for every service! so I set a default grey color for each one of them, once the user click " like" it turns to green and for the opposite case it turns to red..
so I've created an ajax method for that...
I wanted to check if everything works fine with a simple alert()
but I got an error which is :
message: "Undefined property: Illuminate\Database\Eloquen\Builder::$like",…}
exception : "ErrorException"
— file : "C:\xampp\htdocs\dawerelzirou\app\Http\Controllers\ServiceController.php"
— line:164
message: "Undefined property: Illuminate\Database\Eloquent\Builder::$like"
trace : [
— { file: "C:\xampp\htdocs\dawerelzirou\app\Http\Controller\ServiceController.php", line: 164 }
]
This is like.js
$('.like').on('click', function() {
var like_s = $(this).attr('data-like');
var service_id = $(this).attr('data-serviceid');
$.ajax({
type: 'POST',
url: url,
data: {
like_s: like_s,
service_id: service_id,
_token: token
},
success: function(data) {
alert('ok');
}
});
});
This is the script:
<script type="text/javascript" src="{{ asset('js/like.js') }}"></script>
<script type="text/javascript">
var url="{{ route('like') }}";
var token="{{ Session::token() }}";
</script>
Here is the blade page :
#php
$like_count=0;
$dislike_count=0;
$like_statut="grey";
$dislike_statut="grey";
#endphp
#foreach ($services->likes as $like)
#php
if ($like->like ==1){
$like_count++;
}
else {
$dislike_count++;
}
if($like->like == 1 && $like->user_id==Auth::user()->id){
$like_statut="green";
}
else{
$dislike_statut="red";
}
#endphp
#endforeach
<div class="row">
<div class="col s12">
<button type="button"
data-like="{{$like_statut}}"
data-serviceid="{{$services->id}}"
class="like waves-effect waves-light btn {{$like_statut}}">
<i class="material-icons left">thumb_up</i>({{$like_count}})
</button>
</div>
</div>
<br>
<div class="row">
<div class="col s12">
<button type="button"
data-dislike="{{$dislike_statut}}"
class="dislike waves-effect waves-light btn {{$dislike_statut}}">
<i class="material-icons left">thumb_down</i>({{ $dislike_count}})
</button>
</div>
</div>
</div>
</div>
The route:
Route::post('/like','ServiceController#like')->name('like');
The "like" method in the controller:
public function like(Request $request)
{
$like_s = $request->like_s;
$service_id = $request->service_id;
$like = Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id, ]);
if (!$like) {
$new_like = new Like;
$new_like->service_id = $service_id;
$new_like->user_id = Auth::user()->id;
$new_like->like = 1;
$new_like->save();
} elseif ($like->like == 1) {
Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id,])
->delete()
;
} elseif ($like->like == 0) {
Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id,])
->update(array('like' => 1))
;
}
}

This row:
$like = Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id, ]);
seems incomplete, as it returns a query builder and not an object. The query builder has not a "like" property. If you want an object you should do: A first() at the end (or a get() followed by a foreach) seems to be missing.

Related

Laravel record not deleting with delete nor destroy

I am using laravel 7. In my CRUD application, I am having trouble deleting a user record. I have tried a variety of methods which I have left commented out so that you can see what I tried. I am using Sweetalert2 for the confirmation call and when I click confirm, it redirects to the correct page but I do not get a success message nor is the record deleted from the database. I am new to Laravel so if anyone can spot where I may have gone wrong, I would sure appreciate it.
Here are the following relevant codes.
(EDIT OF CODE BELOW!!!)
index.blade.php
#extends('layouts.admin')
#section('content')
<div class="container-fluid mt-5">
<!-- Heading -->
<div class="card mb-4 wow fadeIn">
<!--Card content-->
<div class="card-body d-sm-flex justify-content-between">
<h4 class="mb-2 mb-sm-0 pt-1">
Inicio
<span>/</span>
<span>Registered Users</span>
</h4>
</div>
</div>
<!-- Heading -->
<!--Grid row-->
<!--Grid column-->
<div class="row">
<!--Card-->
<div class="col-md-12 mb-4">
<!--Card content-->
<div class="card">
<!-- List group links -->
<div class="card-body">
<h5>Users Online:
#php $u_total = '0'; #endphp
#foreach ($users as $user)
#php
if($user->isUserOnline()) {
$u_total = $u_total + 1;
}
#endphp
#endforeach
{{ $u_total }}
</h5>
<table id="datatable1" class="table table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Role</th>
<th class="text-center">Online/Offline</th>
<th class="text-center">Banned/Unban</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($users as $user)
<tr>
<input type="hidden" name="id" value="{{ $user->id }}">
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->role_as }}</td>
<td>
#if($user->isUserOnline())
<label class="py-2 px-3 badge btn-success" for="">Online</label>
#else
<label class="py-2 px-3 badge btn-warning" for="">Offline</label>
#endif
</td>
<td>
#if($user->isBanned == '0' )
<label class="py-2 px-3 badge btn-primary">Not Banned</label>
#elseif($user->isBanned == '1')
<label class="py-2 px-3 badge btn-danger">Banned</label>
#endif
</td>
<td>
<a class="badge badge-pill btn-primary px-3 py-2" href="{{ url('role-edit/'.$user->id) }}">Editar</a>
<a class="delete badge badge-pill btn-danger px-3 py-2" data-toggle="modal" href="{{ url('user-delete/'.$user->id) }}" data-target="#delete" data-id="{{ $user->id }}">Borrar</a>
</td>
</tr>
#endforeach
</tbody>
</table>
{{-- <div>
{{ $users->links() }}
</div> --}}
</div>
<!-- List group links -->
</div>
</div>
<!--/.Card-->
</div>
<!--Grid row-->
</div>
#endsection
#section('scripts')
<script>
$(document).ready(function() {
$(document).on('click', '.delete', function (e) {
e.preventDefault();
var id = $(this).data('id');
swal.fire({
title: "¿Estás Seguro/a?",
text: "¡No podrás revertir esto!",
icon: 'warning',
showCancelButton: true,
cancelButtonText: 'Cancelar',
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Sí, Borralo!'
},
function() {
$.ajax({
type: "POST",
url: "{{url('/user-delete/{id}')}}",
data: {id:id},
success: function (data) {
//
}
});
});
});
});
</script>
#endsection
Within my web.php (relevant code only)
Route::group(['middleware' => ['auth', 'isAdmin']], function () {
Route::get('/dashboard', function () {
return view('admin.dashboard');
});
Route::get('registered-user', 'Admin\RegisteredController#index');
Route::delete('/user-delete/{id}', 'Admin\RegisteredController#destroy');
Route::get('registered-empresa', 'Admin\EmpresaController#index');
Route::get('registered-empleado', 'Admin\EmpleadoController#index');
Route::get('role-edit/{id}', 'Admin\RegisteredController#edit');
Route::put('role-update/{id}', 'Admin\RegisteredController#updaterole');
Route::post('save-empresa', 'Admin\EmpresaController#store');
Route::get('/edit-empresa/{id}', 'Admin\EmpresaController#edit');
Route::put('/empresa-update/{id}', 'Admin\EmpresaController#update');
Route::get('/edit-empleado/{id}', 'Admin\EmpleadoController#edit');
Route::put('/empleado-update/{id}', 'Admin\EmpleadoController#update');
Route::post('save-empleado', 'Admin\EmpleadoController#store');
});
RegisteredController.php (delete function only)
public function destroy(Request $request, $id)
{
// $user = User::findOrFail($id)->delete();
// return redirect()->back()->with('status', 'Usuario ha sido borrado.');
// $user = User::find($id);
// $user->delete();
// return redirect()->back()->with('status', 'Usuario ha sido borrado.');
User::destroy($id);
}
EDIT!!!
I changed the way I am calling the sweetalert2 but am still getting errors. I changed my delete button in index.blade.php to
<a class="delete badge badge-pill btn-danger px-3 py-2" onclick="deleteConfirmation({{ $user->id }})">Borrar</a>
In the same file, I changed the script to the following:
function deleteConfirmation(id) {
swal.fire({
title: "Borrar?",
text: "¿Estás seguro/a?",
icon: "warning",
showCancelButton: !0,
confirmButtonText: "Sí,Borralo!",
cancelButtonText: "Cancelar",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('/user-delete')}}/" + id,
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal.fire("Done!", results.message, "success");
} else {
swal.fire("Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
I also removed the .ready function as it was causing a conflict with sweetalert2
My Delete function in my RegisteredController now looks like this:
public function delete($id)
{
$delete = User::where('id', $id)->delete();
// check data deleted or not
if ($delete == 1) {
$success = true;
$message = "Usuario borrado exitosamente";
} else {
$success = true;
$message = "Usuario no encontrado";
}
// Return response
return response()->json([
'success' => $success,
'message' => $message,
]);
}
}
And in my web.php, I changed the route to:
Route::post('/user-delete/{id}', 'Admin\RegisteredController#delete');
The sweet alert now pops up and when I click delete, I get the console error:
POST http://ecomsivendo.test/user-delete/4 419 (unknown status)
You also need the headers section for jquery ajax calls.
$.ajax({
type: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
//.......
Also make sure you have the meta tag in the <head> on the page.
<meta name="csrf-token" content="{{ csrf_token() }}">
Thank you for all those who tried to help me on this. I ended up giving the code another overhaul and this is what I had to do to get it to work.
I had to change my ajax request in the index.blade.php
function deleteConfirmation(id) {
swal.fire({
title: "Borrar?",
text: "¿Estás seguro/a?",
icon: "warning",
showCancelButton: true,
confirmButtonText: "Sí,Borralo!",
cancelButtonText: "Cancelar"
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('/user-delete')}}/" + id,
headers: {
'X-CSRF-TOKEN': '<?php echo csrf_token() ?>'
},
data: {"id": id, _method: 'delete'},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal.fire("¡Hecho!", results.message, "success");
setTimeout(function() {
location.reload();
}, 1000);
} else {
swal.fire("¡Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
I am not happy with the setTimout function to get the page to reload and if someone can offer a better solution to avoid reload, I would really appreciate it.
in the controller, I had to change the delete function to the following:
public function delete($id)
{
$delete = User::where('id', $id)->delete();
// check data deleted or not
if ($delete == 1) {
$success = true;
$message = "Usuario borrado exitosamente";
} else {
$success = true;
$message = "Usuario no encontrado";
}
// Return response
return response()->json([
'success' => $success,
'message' => $message,
]);
}
And finally in my web.php, I have the route as:
Route::delete('/user-delete/{id}', 'Admin\RegisteredController#delete');
like I mentioned earlier, I feel like the setTimeout is a hack and I would prefer something a bit more elegant.
In the end, the code does what it is supposed to do and that is delete the entry and update the view.

Load More option not working in Laravel AJAX

I'm trying to fetch blogs using AJAX function in Laravel. But it is not working, neither showing any error. What I want is to display a load more button from where more blogs will be loaded using AJAX request. Here is my front-end code:
<div class="panel-body">
{{ csrf_field() }}
<div id="post_data"></div>
</div>
And my ajax script:
$(document).ready(function(){
var _token = $('input[name="_token"]').val();
load_data('', _token);
function load_data(id="", _token)
{
$.ajax({
url:"{{ route('loadmore.load_data') }}",
method:"POST",
data:{id:id, _token:_token},
success:function(data)
{
$('#load_more_button').remove();
$('#post_data').append(data);
}
})
}
$(document).on('click', '#load_more_button', function(){
var id = $(this).data('id');
$('#load_more_button').html('<b>Loading...</b>');
load_data(id, _token);
});
});
Here is my route:
web.php
Route::post('/loadmore', 'LoadMoreController#load_data')->name('loadmore.load_data');
Here is the controller function:
LoadMoreController.php
class LoadMoreController extends Controller
{
public function load_more(){
function load_data(Request $request)
{
if($request->ajax())
{
if($request->id > 0)
{
$data = DB::table('blogs')
->where('blog_id', '<', $request->id)
->orderBy('blog_id', 'DESC')
->limit(6)
->get();
}
else
{
$data = DB::table('blogs')
->orderBy('blog_id', 'DESC')
->limit(6)
->get();
}
$output = '';
$last_id = '';
if(!$data->isEmpty())
{
foreach($data as $row)
{
$output .= '
<div class="row">
<div class="col-md-12">
<h3 class="text-info"><b>'.$row->blog_title.'</b></h3>
<p>'.$row->blog_content.'</p>
<br />
<br />
<hr />
</div>
</div>
';
$last_id = $row->id;
}
$output .= '
<div id="load_more">
<button type="button" name="load_more_button" class="btn btn-success form-control" data-id="'.$last_id.'" id="load_more_button">Load More</button>
</div>
';
}
else
{
$output .= '
<div id="load_more">
<button type="button" name="load_more_button" class="btn btn-info form-control">No Data Found</button>
</div>
';
}
echo $output;
}
}
}
}
I'll be happy to provide any other details if needed or asked. Any suggestions/solutions will be highly appreciated.
Laravel version 8
web.php
Here is route file below:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/loadmore', [App\Http\Controllers\LoadMoreController::class, 'index']);
Route::post('/loadmore/load_data', [App\Http\Controllers\LoadMoreController::class, 'load_data'])->name('loadmore.load_data');

laravel vue.js The GET method is not supported for this route. Supported methods: POST

I am creating commenting system. Now, I want to post a new comment, but when I send a comment, I got an error in http://127.0.0.1:8000/comments/51.
The GET method is not supported for this route. Supported methods:
POST.
I want to post a comment in this URL http://127.0.0.1:8000/results/51.
In my chrome dev tool console, I have this error
Failed to load resource: the server responded with a status of 500
(Internal Server Error)
web.php
Route::middleware(['auth'])->group(function(){
//post a comment
Route::POST('comments/{post}', 'CommentController#store')->name('comment.store');
});
//comment area
Route::get('results/{post}/comments', 'CommentController#index');
Route::get('comments/{comment}/replies', 'CommentController#show');
comments.vue
<template>
<div class="commentarea" >
<div class="comment-posts" >
<div v-if="!auth" class="user-comment-area" >
<div class="user-post">
<!---<img src="{{asset('people/person7.jpg')}}" class="image-preview__image">--->
<input v-model="newComment" type="text" name="comment">
</div>
<div class="comments-buttons">
<button class="cancel-button">Cancel</button>
<button #click="addComment" class="comment-button" type="submit">Comment</button>
</div>
</div>
<h4>Comments ()</h4>
<div class="reply-comment" v-for="comment in comments.data" :key="comment.id">
<div class="user-comment">
<div class="user">
<!---<img src="{{ $comment->user->img }}" class="image-preview__image">--->
<avatar :username="comment.user.name"></avatar>
</div>
<div class="user-name">
<span class="comment-name">{{ comment.user.name }}</span>
<p>{{ comment.body }}</p>
</div>
</div>
<div class="reply">
<button class="reply-button">
<i class="fas fa-reply"></i>
</button>
</div>
<replies :comment="comment"></replies>
</div>
</div>
<div>
<button v-if="comments.next_page_url" #click="fetchComments" class="load">Load More</button>
</div>
</div>
</template>
<script>
import Avatar from 'vue-avatar'
import Replies from './replies.vue'
export default {
props: ['post'],
components: {
Avatar,
Replies
},
mounted() {
this.fetchComments()
},
data: () => ({
comments: {
data: []
},
newComment: '',
auth: ''
}),
methods: {
fetchComments() {
const url = this.comments.next_page_url ? this.comments.next_page_url : `/results/${this.post.id}/comments`
axios.get(url).then(({ data }) => {
this.comments = {
...data,
data: [
...this.comments.data,
...data.data
]
}
})
.catch(function (error) {
console.log(error.response);
})
},
addComment() {
if(! this.newComment) return
axios.post(`/comments/${this.post.id}`, {
body: this.newComment
}).then(( {data} ) => {
this.comments = {
...this.comments,
data: [
data,
...this.comments.data
]
}
})
}
}
}
</script>
commentsController.php
public function store(Request $request, Post $post)
{
return auth()->user()->comments()->create([
'body' => $request->body,
'post_id' => $post->id,
'comment_id' => $request->comment_id
])->fresh();
}
comment.php
protected $appends = ['repliesCount'];
public function post()
{
return $this->belongsTo(Post::class);
}
public function getRepliesCountAttribute()
{
return $this->replies->count();
}
I am glad if someone helps me out.
your URL is : http://127.0.0.1:8000/results/51.
your routes should be :
Route::group(['middleware' => 'auth'],function () {
Route::post('comments/{post_id}', 'CommentController#store')->name('comment.store');
});
your controller will be :
public function store(Request $request,$post_id)
{
return auth()->user()->comments()->create([
'body' => $request->body,
'post_id' => $post_id,
'comment_id' => $request->comment_id
])->fresh();
}
Thank you, I put catch method, and the issue was I did not include protected $fillable ['body','post_id', 'comment_id'] in comment model.

401 Unauthorized DELETE request to RESTful API in laravel via Ajax

I've created a restful API using laravel controllers. I have a PhotosController which has a destroy($id) method for resource deletion. also I have a piece of javascript code that sends a DELETE request to my app. the result should be the deletion of the photo with $id id. but laravel doesn't route my request to destroy method. instead it sends an 401 Unauthorized error.
the thing is that I want to send DELETE request to my app via Ajax, but laravel doesn't let my request to be routed!
routes.php file :
Route::resource('photos', 'PhotosController');
destroy method :
public function destroy($id)
{
try{
unlink($_SERVER["DOCUMENT_ROOT"].'/uploads/doctors/' . $id);
Session::forget('photo');
$msg = Notification::where('flag', 's')->where('code', 'user-update-delete-photo-gallery')->first()->msg;
return Response::json(array('success' => $msg));
}catch (Exception $e){
App::abort(500, $e->getMessage());
}
}
my Ajax request :
$.ajax(
{
url: "/photos/" + name,
method : "DELETE", // Or POST : result is the same
data :{
_token : $("input[name=_token]").val(),
_method : 'DELETE'
},
success: function(data, textStatus, jqXHR ){
parent.replaceWith("");
toastr.success(data['success']);
$("#overlay").hide();
},
beforeSend : function(jqXHR, settings ){
$("#overlay").show();
},
error : function(jqXHR, textStatus, errorThrown ){
toastr.error(jqXHR.responseText);
$("#overlay").hide();
}
}
);
Thanks for your help.
I do this sort of thing all the time in my Laravel Apps with no issues. This code allows the user to delete a resource through AJAX while presenting a bootstrap confirmation dialog first. The code is laid out in the order the events would occur.
VIEW WITH RESOURCE TO DELETE
<a class="delete-plan" href="{{ route('admin.plans.destroy', $plan['id']) }}" data-redirect="{{ route('admin.plans.index') }}" data-plan-name="{{ $plan['name'] }}" data-lang="billing.plans">
<i class="fa fa-trash fa-lg"></i>
</a>
JQUERY TO PROMPT CONFIRMATION MODAL
$('.delete-plan').on('click', function(e) {
e.preventDefault();
var data = {
'route': $(this).attr('href'),
'redirect': $(this).data('redirect'),
'modal_title': 'Delete Plan',
'content_view': 'Are you sure you want to delete plan: <strong>' + $(this).data('plan-name') + '</strong>?',
'lang': $(this).data('lang')
};
loadDestroyModal(data);
});
function loadDestroyModal(data) {
$.get('/ajax/destroy-modal', { data: data }, function(modal) {
$('body').append(modal);
$('#destroy-modal').modal('show');
});
}
AJAX CONTROLLER
// routed by /ajax/destroy-modal
public function destroyModal() {
$data = Input::get('data');
$params = [
'route' => $data['route'],
'redirect' => $data['redirect'],
'title' => $data['modal_title'],
'content' => $data['content_view'],
'lang' => $data['lang']
];
return View::make('_helpers.modal-destroy', $params);
}
DESTROY CONFIRMATION MODAL (_helpers.modal-destroy)
<div id="destroy-modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true"><i class="fa fa-times"></i></span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title">{{ $title }}</h4>
</div>
<div class="modal-body">
{{ $content }}
</div>
<div class="modal-footer">
<button id="modal-confirm" type="button" class="btn btn-primary" data-route="{{ $route }}"
data-redirect="{{ $redirect }}" data-lang="{{ $lang }}">Confirm</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JQUERY TO PROCESS DESTROY METHOD AND REDIRECT FLASH MESSAGE
$('body').on('click', '#destroy-modal #modal-confirm', function(e) {
var redirect = $(this).data('redirect');
var lang = $(this).data('lang');
$(this).html('<i class="fa fa-spinner fa-spin"></i> Please Wait');
$.ajax({
'url': $(this).data('route'),
'type': 'DELETE',
'success': function(response) {
if (response) {
redirectWithFlashMessage(redirect, 'destroy', 'success', lang);
} else {
redirectWithFlashMessage(redirect, 'destroy', 'errors', lang);
}
}
});
});
PLANS CONTROLLER
public function destroy($id)
{
try
{
Stripe::plans()->destroy(['id' => $id]);
return Response::json(TRUE);
}
catch (Exception $e)
{
return Response::json(FALSE);
}
}
JQUERY FOR REDIRECTION
function redirectWithFlashMessage(redirect, type, status, lang) {
var params = {
type: type,
status: status,
lang: lang
};
$.get('/ajax/flash', params, function(response) {
window.location.href = redirect;
});
}
AJAX CONTROLLER (Redirect with Flash)
public function flashData() {
$message_type = 'success' == Input::get('status') ? 'success' : 'failure';
$message = Lang::get(Input::get('lang'))[Input::get('type') . '_' . $message_type];
Session::flash($message_type, $message);
return ['status' => $message_type, 'message' => $message];
}
It's a lot of code but once setup it's extremely easy to replicate.
I think your system's requiring the authentication for controller action "destroy" method. So you need to login before calling that method.
If you're using the middleware "auth" (app\Http\Middleware\Authenticate.php), you can easy find the "handle" function that returning "Unauthorized" error.
Hope this will help.

Angular.js xeditable $http.post data processing

I need to edit the data to db and make it a view on instant and using angular xeditables, but i am unable to pass the data to process.php (to update the db and retrieve back the data)
How can I pass the data using $http.post
Code snippet
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="http://code.angularjs.org/1.0.8/angular-mocks.js"></script>
<link href="angular-xeditable-0.1.8/css/xeditable.css" rel="stylesheet">
<script src="angular-xeditable-0.1.8/js/xeditable.js"></script>
<script>
var app = angular.module("app", ["xeditable", "ngMockE2E"]);
app.run(function(editableOptions) {
editableOptions.theme = 'bs3';
});
app.controller('Ctrl', ['$scope','$filter','$http', function($scope, $filter,$http) {
$scope.user = {
name: 'awesome user',
status: 2,
group: 4
};
$scope.statuses = [
{value: 1, text: 'status1'},
{value: 2, text: 'status2'},
{value: 3, text: 'status3'},
{value: 4, text: 'status4'}
];
$scope.groups = [
{value: 1, text: 'user'},
{value: 2, text: 'customer'},
{value: 3, text: 'vip'},
{value: 4, text: 'admin'}
];
$scope.errors = [];
$scope.msgs = [];
$scope.saveUser = function()
{ // $scope.user already updated!
return $http.post('/saveUser', $scope.user).error(function(err) {});
$scope.errors.splice(0, $scope.errors.length); // remove all error messages
$scope.msgs.splice(0, $scope.msgs.length);
$http.post('include/process.php', {'name': $scope.name, 'status': $scope.status, 'group': $scope.group}
).success(function(data, status, headers, config) {
if (data.msg != '')
{
$scope.msgs.push(data.msg);
}
else
{
$scope.errors.push(data.error);
}
}).error(function(data, status) { // called asynchronously if an error occurs
// or server returns response with an error status.
$scope.errors.push(status);
});
};
}]);
app.run(function($httpBackend) {
$httpBackend.whenPOST(/\/saveUser/).respond(function(method, url, data) {
data = angular.fromJson(data);
});
});
</script>
HTML
.....
<div ng-app="app" ng-controller="Ctrl">
<form editable-form name="editableForm" >
<ul>
<li class="err" ng-repeat="error in errors"> {{ error}} </li>
</ul>
<ul>
<li class="info" ng-repeat="msg in msgs"> {{ msg}} </li>
</ul>
<div class="pull-right">
<!-- button to show form -->
<button type="button" class="btn btn-default btn-sm" ng-click="editableForm.$show()" ng-show="!editableForm.$visible"> Edit </button>
<!-- buttons to submit / cancel form -->
<span ng-show="editableForm.$visible">
<button type="submit" class="btn btn-primary btn-sm" ng-disabled="editableForm.$waiting" onaftersave="saveUser()"> Save </button>
<button type="button" class="btn btn-default btn-sm" ng-disabled="editableForm.$waiting" ng-click="editableForm.$cancel()"> Cancel </button>
</span> </div>
<div>
<!-- editable username (text with validation) -->
<span class="title">User name: </span> <span editable-text="user.name" e-id="myid" e-name="name" e-required>{{ user.name || 'empty' }}</span>
</div>
<div>
<!-- editable status (select-local) -->
<span class="title">Status: </span> <span editable-select="user.status" e-name="status" e-ng-options="s.value as s.text for s in statuses"> {{ (statuses | filter:{value: user.status})[0].text || 'Select' }} </span> </div>
<div>
<!-- editable group (select-remote) -->
<span class="title">Group: </span> <span editable-select="user.group" e-name="group" e-ng-options="g.value as g.text for g in groups"> {{ (groups | filter:{value: user.group})[0].text || 'Select' }} </span> </div>
</form>
</div>
....
PROCESS.PHP
<?php
$data = json_decode(file_get_contents("php://input"));
$name = mysql_real_escape_string($data->name);
$status = mysql_real_escape_string($data->status);
$group = mysql_real_escape_string($data->group);
if ($group == 'vip') {
if ($qry_res) {
$arr = array('msg' => "User Created Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
print_r($jsn);
} else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
print_r($jsn);
}
} else {
$arr = array('msg' => "", 'error' => 'User Already exists with same email');
$jsn = json_encode($arr);
print_r($jsn);
}
?>
I don't know if it would be useful to you or someone else.
Afaik, you cannot use http.post with angular to update a database (at least in my case, with php and mysql). You need to use $http() like follows:
var request = $http({
method: "post",
url: "include/process.php",
data: {
name: $scope.name,
status: $scope.status,
group: $scope.group
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
Then, in PHP, retrieve it like:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
#$name = $request->name;
#$status = $request->status;
#$group = $request->group;
...
?>
With the values at $name, $status and $group you'll be able to update your database.
UPDATE: Your process.php is not called because you have a "return $http.post('/saveUser', $scope.user)" line first in $scope.saveUser = function(), which immediately ends execution of the saveUser function. See return statement in Javascript:
When a return statement is called in a function, the execution of this function is stopped. If specified, a given value is returned to the function caller. If the expression is omitted, undefined is returned instead.

Categories