DB is not update when ajax has successfully called controller method laravel - javascript

From my console output, I can see that the success message has been displayed from the controller method that ajax called, but i have no idea why the value in db is not changing according to the value.
this is my html code
#foreach($system_functions as $function)
<input type="hidden" id="id" value="{{$function->id}}" />
#if($function->group_id == 1)
<tr>
<td>{!! $function->name !!}</td>
<td><input class="toggle_status" type="checkbox" #if($function->is_active) checked #endif id="is_active" name="is_active" data-on="启用" data-off="禁用" value="on" data-toggle="toggle"></td>
</tr>
#endif
#endforeach
my ajax in the same file
#section('script')
<script type="text/javascript">
$(document).ready(function() {
$('.toggle_status').change(function (e) {
e.preventDefault();
var is_active = 0
if ($(this).is(':checked')) {
is_active = 1;
}
$.ajax({
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/admin/system-functions',
async: true,
data: {
is_active: is_active,
id: {{ $function->id }}
},
success: function (data) {
$.confirm({
title:'edit?',
content:'confirm to edit?',
buttons:{
confirm: {
text: 'edit',
btnClass: 'btn-danger',
action: function () {
}
},
cancel: {
text: 'cancel',
btnClass: 'btn-default',
action: function () {
}
}
}
});
}
});
});
});
</script>
#endsection
this is my method in controller
public function update(Request $request)
{
$id = Input::get('id');
$function=SystemFunction::where('id',$id)->first();
if($request->get('is_active')==='on'){
$is_active=1;
} else{
$is_active=0;
}
$function->update([
'is_active' => $is_active
]); return response()->json(['success' => 'successful']);
}
this is my route
Route::post('/system-functions', 'SystemFunctionController#update');
this is my modal class
class SystemFunction extends Model
{
protected $fillable=['name','group_id','is_active'];
static function isFunctionActive($function_name){
$function=SystemFunction::whereName($function_name)->first();
if(!$function){
return false;
}
return $function->is_active==true;
}
}

try this :
public function update(Request $request) {
$id = Input::get('id');
if($request->get('is_active')==='on'){
$is_active=1;
} else {
$is_active=0;
}
$function=SystemFunction::where('id',$id)->update([
'is_active' => $is_active
]);
return response()->json(['success' => 'successful']);
}
hopefully that can help

Try this, if DB doesn't get updated then you can track it through error messages:
try {
$id = Input::get('id');
$is_active = empty(Input::get('is_active')) ? 0 : 1;
$function = SystemFunction::findOrFail($id)->update(['is_active' => $is_active]);
if ($function) {
return response()->json(['success' => 'successful'], 200);
}
$error = ['errors' => ['message' => 'no data']];
return response()->json($error, 204);
} catch (Exceptoin $e) {
$error = ['errors' => ['message' => $e->getMessage()]];
return response()->json($error, 200);
}

Related

Method App\Http\Controllers\ConfigSplitCleansingController::show does not exist

I got this error and I cant seem to find the bug.
This is the function in my controller.
class ConfigSplitCleansingController extends Controller
{
public function storeNewArea(Request $request)
{
$setArea = $request->setNewArea;
$decode = json_decode($setArea, true);
$activity = Activities::where('activityCode', $request->activityId)->first();
$lastrow = PubCleansingScheduleStreet::join('pubcleansingschedule_activity','pubcleansingschedule_street.pubCleansingActivityId', '=', 'pubcleansingschedule_activity.id')
->select('pubcleansingschedule_street.rowOrder')
->where('pubcleansingschedule_activity.pubCleansingScheduleParkId',$request->scheduleparkId)
->where('pubcleansingschedule_activity.activityId',$activity->id)
->orderBy('pubcleansingschedule_street.rowOrder','desc')
->limit(1)->first();
$row = $lastrow->rowOrder;
foreach ($decode as $key => $value) {
$row = $row + 1;
if($value['id'] == 0){
$schedulestreet = PubCleansingScheduleStreet::find($request->schedulestreetId);
$newsplit = new CleansingSplit;
$newsplit->pubCleansingId =$schedulestreet->pubCleansingId;
$newsplit->streetId =$schedulestreet->streetId;
$newsplit->activityCode =$schedulestreet->activityCode;
$newsplit->serviceType =$schedulestreet->serviceType;
$newsplit->value =$value['value'];
$newsplit->frequency =$schedulestreet->frequency;
$newsplit->save();
$newstreet->pubCleansingActivityId =$schedulestreet->pubCleansingActivityId;
$newstreet->pubCleansingId =$schedulestreet->pubCleansingId;
$newstreet->streetId =$schedulestreet->streetId;
$newstreet->streetName =$schedulestreet->streetName;
$newstreet->streetType =$schedulestreet->streetType ;
$newstreet->activityCode =$schedulestreet->activityCode;
$newstreet->serviceType =$schedulestreet->serviceType;
$newstreet->value =$value['value'];
$newstreet->frequency =$schedulestreet->frequency;
$newstreet->frequency_PJ =$schedulestreet->frequency_PJ;
$newstreet->rowOrder =$row;
$newstreet->save();
}
else {
$newstreet = CleansingSplit::find($value['id']);
$newstreet->value = $value['value'];
$newstreet->save();
}
}
return response()->json($newstreet);
}
}
This is my model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CleansingSplit extends Model
{
//
protected $table = 'publiccleansingsplit';
protected $fillable = [
'id',
'pubCleansingId',
'streetId',
'activityCode',
'serviceType',
'value',
'frequency'
];
}
Route
Route::post('splitpembersihan/storeNewArea', ['as' => 'storeNewArea', 'uses' => 'ConfigSplitCleansingController#storeNewArea']);
And this is the ajax
$.ajax(
{
url: '{{url("splitpembersihan/storeNewArea")}}',
type: 'post',
data: {
"setNewArea": setarray,
"scheduleparkId": scheduleparkId,
"schedulestreetId": schedulestreetId,
"splitId": splitId,
"activityId" : #if(isset($schedulestreet->activityCode))"{{ $schedulestreet->activityCode}}"#endif,
"_token": token
},
success: function (data)
{
alert("success");
window.location.replace('/splitpembersihan/splitBin/'+ PubCleansingID +'/splitValueArea');
},
error: function (data)
{
alert("error");
}
});
The error is the opposite. The data is stored successfully. However, it shows the error alert instead of the success alert. And if I just press the submit button without submitting anything, it shows the success alert.

Trying to implement a comments system with laravel

Trying to implement a comments system using pusher on my laravel project. Everything seems to be in order, however every post request which is meant to send the input data to the database returns with error 500.
Used F12 on firefox to monitor what gets sent to /tip/select, it seems that it passes the text of the comment just fine, so it could be the issue with the controller.
Routes
Route::get('/tip/select','TipController#select');
Route::post('/tip/select', 'TipController#addComment');
Comment model
namespace App;
use Illuminate\Database\Eloquent\Model;
use Zttp\Zttp;
use App\model\User;
use App\Tip;
class Comment extends Model
{
protected $guarded = [];
protected $table='comments';
//protected $fillable=['tip_id','user_id','body'];
public static function moderate($comment)
{
$response = Zttp::withoutVerifying()->post("https://commentator.now.sh", [
'comment' => $comment,
'limit' => -3,
])->json();
if ($response['commentate']) {
abort(400, "Comment not allowed");
}
}
public function tip(){
return $this->belongsTo('App\Tip');
}
public function user(){
return $this->belongsTo('App\model\User');
}
}
Controller
use Pusher\Laravel\Facades\Pusher;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Input;
use DB;
use Image;
use App\Tip;
use App\model\User;
use App\Subcategories;
use App\Category;
use App\City;
use App\Comment;
use App\CityAreas;
//use App\Http\Requests\TipFormRequest;
class TipController extends Controller
{
public function select(){
//$db=DB::table('tips')->orderBy('created_at','desc');
$data=Tip::get();
$url = Storage::disk('s3');
//$data=Tip::paginate(10);
//$data=$db->get();
// dd($data);
$comments = Comment::orderBy('id')->get();
return view('tip', compact('data', 'url','comments'));
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function create(){
$categories=Category::all();
$cities=City::all();
return view('tip.create',compact('categories','cities'));
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function store(Request $request, City $city, Category $category){
$this->validate($request, [
'image' => 'image|nullable|max:1999']);
$tipsnew = new Tip;
$tipsnew->title = $request->title;
$tipsnew->description = $request->description;
$tipsnew->category_id = $request->category;
$tipsnew->city_id = $request->city;
$tipsnew->user_id = auth()->id();
$tipsnew->url = $request->url;
if ($request->hasFile('image')) {
try{
$file = $request->file('image');
$name = time() . '.' . $file->getClientOriginalExtension();
$img = \Image::make($file->getRealPath());
$img->fit(1080);
$img->stream();
Storage::disk('s3')->put('tip'.'/'.$name, $img->__toString());
$tipsnew->image = 'tip'.'/'.$name;
}
catch (\Exception $e)
{
$response = [
'information' => 'Error. Something went wrong. Please try again',
];
$statusCode = 400;
return response()->json($response, $statusCode);
}
}
$tipsnew->save();
return redirect ('tip/create')->with('status','your tip is created');
}
public function edit($id){
$tip=Tip::whereId($id)->firstOrFail();
$categories=Category::all();
$selectedCategories=$tip->categories->lists('id')->toArray();
return view('tip.edit',compact('tip','categories','selectedCategories'));
}
public function search(Request $request, City $city, Category $category, User $user){
$q = $request->get('q');
if ($q != ""){
$tips = Tip::where('title','LIKE','%'.$q.'%')
->orWhere('description','LIKE','%'.$q.'%')
->orWhereHas('user', function($id) use($q){
return $id->where('name', 'LIKE','%'.$q.'%');
})
->orWhereHas('city', function($id) use($q){
return $id->where('name', 'LIKE','%'.$q.'%');
})
->orWhereHas('category', function($id) use($q){
return $id->where('name', 'LIKE','%'.$q.'%');
})
->get();
if(count($tips) > 0)
return view('tip.search', ['tips' => $tips]);
}
}
public function addComment(Request $request)
{
$data = $request;
Comment::moderate($data['text']);
$comment = Comment::create($data);
Pusher::trigger('comments', 'new-comment', $comment, request()->header('X-Socket-Id'));
//add creation of new comment to DB
$commentnew = new Comment;
$commentnew->user_id = Auth::user()->id();
//$commentnew->tip_id= $request->post(['tip_id']);
$commentnew->body = $request->text;
$commentnew->save();
return $comment;
}
}
Snippet of the blade
<h3>Comments</h3>
<form onsubmit="addComment(event);">
<input type="text" placeholder="Add a comment" name="text" id="text" required>
<input type="hidden" name="tip_id" id="tip_id" value="{{$val->tip_id}}">
<input type="hidden" name="username" id="username" value="{{Auth::user()->name}}">
<button id="addCommentBtn">Comment</button>
</form>
<div class="alert" id="alert" style="display: none;"></div>
<br>
<div id="comments">
#foreach($comments as $comment)
<div>
<small>{{ $comment->username }}</small>
<br>
{{ $comment->text }}
</div>
#endforeach
</div>
<!--jQuery script used to be here -->
<script>
function displayComment(data) {
let $comment = $('<div>').text(data['text']).prepend($('<small>').html(data['username'] + "<br>"));
$('#comments').prepend($comment);
}
function addComment(event) {
function showAlert(message) {
let $alert = $('#alert');
$alert.text(message).show();
setTimeout(() => $alert.hide(), 4000);
}
event.preventDefault();
$('#addCommentBtn').attr('disabled', 'disabled');
var data = {
text: $('#text').val(),
username: $('#username').val(),
tipid: $('#tip_id').val(),
};
fetch('/tip/select', {
body: JSON.stringify(data),
credentials: 'same-origin',
headers: {
'content-type': 'application/json',
'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
'x-socket-id': window.socketId
},
method: 'POST',
mode: 'cors',
}).then(response => {
$('#addCommentBtn').removeAttr('disabled');
displayComment(data);
showAlert('Comment posted!');
})
}
</script>

Sending data from Angular to Laravel

Ok, so I'm stuck again. I'm doing an todo-list application, using Laravel and Angular. I can fetch data from the database via the Laravel- and Angular controllers but when I try do write data, I can't get it working.
So I have a form, whing uses ng-submit to post the data. When I - in the Angular controller - log the data to the console, the data from the form is correct. But when I try to pass it on to the Laravel Controller, I get stuck.
I can't find out whats wrong and browing the web for answers hasn't helped me.
Laravel routes:
<?php
Route::get('/', function () {
return view('index');
});
Route::get('/notes', 'NoteController#index');
Route::delete('/notes', 'NoteController#destroy');
Route::post('/notes', 'NoteController#store');
//Route::post('/notes', 'NoteController#update');
Route::get('/projects', 'ProjectController#index');
Route::get('/users', 'UserController#index');
Route::group(['middleware' => ['web']], function () {
//
});
?>
Laravel controllers:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Note;
use App\User;
use App\Project;
use Input;
use Response;
use Redirect;
class NoteController extends Controller
{
public function index()
{
try {
$statusCode = 200;
$notes = Note::where('removed', 0)->get()->toArray();
$response = [];
foreach ($notes as $note) {
$user = User::find($note['user_id']);
$project = Project::find($note['project_id']);
$this_row = array(
'id' => $note['id'],
'user' => $user['uname'],
'project' => $project['pname'],
'content' => $note['content'],
'completed' => $note['completed'],
'removed' => $note['removed'],
'created' => $note['time_created'],
'deadline' => $note['time_deadline']
);
$response[] = $this_row;
}
} catch (Exception $e) {
$statusCode = 400;
} finally {
return Response::json($response, $statusCode);
}
}
public function store()
{
$note = Input::json()->get()->toArray();
var_dump($note);
/*
$note->user_id = $note['user'];
$note->project_id = $note['project'];
$note->content = $note['content'];
$note->time_deadline = $note['deadline'];
$note->save();*/
}
}
class ProjectController extends Controller
{
public function index()
{
try {
$statusCode = 200;
$projects = Project::orderBy('pname', 'asc')->get()->toArray();
$response = [];
foreach ($projects as $project) {
$this_row = array(
'id' => $project['id'],
'name' => $project['pname'],
);
$response[] = $this_row;
}
} catch (Exception $e) {
$statusCode = 400;
} finally {
return Response::json($response, $statusCode);
}
}
}
class UserController extends Controller
{
public function index()
{
try {
$statusCode = 200;
$users = User::orderBy('uname', 'asc')->get()->toArray();
$response = [];
foreach ($users as $user) {
$this_row = array(
'id' => $user['id'],
'name' => $user['uname'],
);
$response[] = $this_row;
}
} catch (Exception $e) {
$statusCode = 400;
} finally {
return Response::json($response, $statusCode);
}
}
}
Angular controller:
angular.module('todoApp', []).controller('MainController', function($scope, $http) {
var thisApp = this;
$http({method : 'GET', url : 'http://localhost:8000/notes'})
.then (function(response) {
thisApp.todos = response.data;
}, function() {
alert("Error getting todo notes");
});
$http({method : 'GET',url : 'http://localhost:8000/users'})
.then(function(response) {
thisApp.users = response.data;
}, function() {
alert("Error getting users");
});
$http({method : 'GET', url : 'http://localhost:8000/projects'})
.then(function(response) {
thisApp.projects = response.data;
}, function() {
alert("Error getting projects");
});
thisApp.addTodo = function(note) {
console.log($scope.note);
$http({
method : 'POST',
url : 'http://localhost:8000/notes',
data : $.param($scope.note),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
});
};
});
HTML:
<!doctype html>
<html ng-app="todoApp">
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="/js/MainController.js"></script>
</head>
<body ng-controller="MainController as myControl">
<h2>Todo</h2>
<div>
<table>
<tr>
<th>Note:</th>
<th>Author:</th>
<th>Project:</th>
<th>Created:</th>
<th>Deadline:</th>
</tr>
<tr ng-repeat="todo in myControl.todos">
<td> {{ todo.content }} </td>
<td> {{ todo.user }} </td>
<td> {{ todo.project }} </td>
<td> {{ todo.created }} </td>
<td> {{ todo.deadline }} </td>
<td><button>Update</button></td>
<td><button>Delete</button></td>
</tr>
</table>
</div>
<h2>Add new:</h2>
<div>
<form ng-submit="myControl.addTodo()">
User:<br/>
<select ng-model="note.user">
<option ng-repeat="user in myControl.users" value="{{ user.id }}">{{ user.name }}</option>
</select><br/>
Project:<br/>
<select ng-model="note.project">
<option ng-repeat="project in myControl.projects" value="{{ project.id }}">{{ project.name }}</option>
</select><br/>
Note:<br/>
<textarea rows="5" cols="30" ng-model="note.content"></textarea><br/>
Deadline (format YYYY-MM-DD HH:MM):<br/>
<input type="text" ng-model="note.deadline" /><br/>
<input type="submit" value="Add" />
</form>
</div>
</body>
</html>
The result can be seen in this image: http://imgur.com/60hIzSb
I have no idea what I'm doing wrong. I guess my problem is in the Angular controller in the addTodo function, but I really don't know. Any suggestions?
I also wonder if anyone knows if I have to do anything else than change method : 'POST' to method : 'PUT' if I want to use the PUT method for creating new notes?
I feel like it has something to do with this:
$note = Input::json()->get()->toArray();
var_dump($note);
In angular you are sending form encoded data not json. And I believe Laravel automatically decodes received json anyway, so this should work:
$note = Input::all();
var_dump($note);
If it is the CSRF token then inject the CSRF TOKEN to your view
angular.module("todoApp").constant("CSRF_TOKEN", '{!! csrf_token() !!}');
and to your addTodo function in the headers pass the token....
thisApp.addTodo = function(note) {
console.log($scope.note);
$http({
method : 'POST',
url : 'http://localhost:8000/notes',
data : $.param($scope.note),
headers : {'Content-Type': 'application/x-www-form-urlencoded',
'x-csrf-token': CSRF_TOKEN}
});

angularjs+cakephp black-holed request

I have created in the UsersController a method to add new users in database. In the cakephp ctp views files everything is okay, as my request is not black-holed. I am using post for this. But when I move the view to angularjs the request is black-holed. I don't get it. Can some one pls help me.
Here is the UsersController.php code,the function called add is the one doing the stuff:
<?php
class UsersController extends AppController {
public $components = array(
'RequestHandler',
'Security',
'Session',
'Auth'
);
public function login() {
if ($this->Session->read('Auth.User')) {
$this->set(array(
'message' => array(
'text' => __('You are logged in!'),
'type' => 'error'
),
'_serialize' => array('message')
));
}
if ($this->request->is('post')) {
if(!empty($this->request->data)){
$userDetails = $this->User->find('first', array(
'conditions' => array(
'User.username' => $this->request->data['username'],
'User.password' => $this->request->data['password']
)));
debug($userDetails);
debug($this->Auth->login());
}
if ($this->Auth->login()) {
$this->set(array(
'user' => $this->Session->read('Auth.User'),
'_serialize' => array('user')
));
} else {
$this->set(array(
'message' => array(
'text' => __('Invalid username or password, try again'),
'type' => 'error'
),
'_serialize' => array('message')
));
$this->response->statusCode(401);
}
}
}
public function logout() {
if ($this->Auth->logout()) {
$this->set(array(
'message' => array(
'text' => __('Logout successfully'),
'type' => 'info'
),
'_serialize' => array('message')
));
}
}
public function add(){
if($this->request->is('post')){
if(!empty($this->request->data)){
$password = $this->request->data['User']['password'];
$username = $this->request->data['User']['username'];
//$password = Security::hash($this->request->data['User']['password'], 'sha1', true);
$password = Security::hash($password.$username, 'sha1', true);
debug($password);
}
}
//$this->set(array('message',array('error' => __("No data sent")), '_serialize' => array('message')));
}
public function index() {
$this -> user = $this -> Auth -> user();
if ($this -> user) {
$this -> set('users', $this -> User -> find('all'));
$this -> set('_serialize', array('users'));
}
else {
$this -> set('error', 'user not logged in');
$this -> set('_serialize', array('error'));
}
}
public function user($id = null) {
$this -> layout = null;
if (!$id) {
throw new NotFoundException(__('Invalid user'));
}
$user = $this -> User -> findById($id);
if (!$user) {
throw new NotFoundException(__('Invalid user'));
}
$this -> set('user', $user);
}
}
?>
And this is the angular controller:
angular.module('addUser.controllers', []).controller('addUserCtrl', function($scope, $http) {
$scope.register = function() {
data = {'User':{
'username' : $scope.username,
'password' : $scope.password
}};
if(data.User.username != undefined && data.User.password != undefined){
$http.post('API/users/add', data).success(function(data) {
$scope.users = data.users;
console.log(data);
});
}else{
console.log('can\'t login');
}
/**/
};
});
PS: I am a beginner with cakephp.
Thanks a lot and happy coding ;)
I found the solution to the problem, as I went through the entire cakephp book and got this solution, don't know if it is the right one, but for me works okay.
This is the reference link and for me it was like the lines are in the book:
public function beforeFilter() {
$this -> Security -> blackHoleCallback = 'blackhole';
}
public function blackhole($type) {
return $type;// don't know if it is good or bad practice like this feel free to comment
}

Symfony2 and jquery checkbox

I want to use checkbox with symfony2. I want to update a field value in a table (0/1) dynamically using the checkbox value.
Here is my wrong code :
index.html.twig :
<div class="slider demo" id="slider-1">
{% if plate.share == true %}
<input type="checkbox" value="1" checked>
{% else %}
<input type="checkbox" value="1">
{% endif %}
</div>
<script type="text/javascript">
$("input[type='checkbox']").on('click', function(){
var checked = $(this).attr('checked');
if (checked) {
var value = $(this).val();
$.post("{{ path('plate_share', { 'id': plate.id }) }}", { value:value }, function(data){
if (data == 1) {
alert('the sharing state was changed!');
};
});
};
});
</script>
routing.yml
plate_share:
pattern: /{id}/share
defaults: { _controller: "WTLPlateBundle:Plate:share" }
PlateController.php:
public function shareAction($id)
{
if($_POST && isset($_POST['value'])) {
$link = mysql_connect('127.0.0.1', 'admin', 'wtlunchdbpass');
if (!$link) {
print(0);
}
mysql_select_db('wtlunch');
$value = mysql_real_escape_string($POST['value']);
$sql = "INSERT INTO table (value) VALUES ('$value')";
if (mysql_query($sql, $link)) {
print(1);
}
else {
print(0);
}
}
}
But this solution is wrong and not working.
Is it possible to create a form and submit it with only a checkbox?
Is there an idea? Thanks.
This for example the edit form action in the controller :
public function editAction($id)
{
$user = $this->container->get('security.context')->getToken()->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException('This user does not have access to this section.');
}
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('WTLPlateBundle:Plate')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Plate entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('WTLPlateBundle:Plate:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}

Categories

Resources