Sending data from Angular to Laravel - javascript

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

Related

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>

Uncaught (in promise) TypeError: Cannot read property 'uid' of undefined

I am using laravel 5.4 and Vue.js 2 to save some information along with file(video) in DB.But i got error like this
error: http://imgur.com/a/7XGERPUT
http://localhost:8000/videos/null 404 (Not Found)
Uncaught (in promise) TypeError: Cannot read property 'uid' of undefined
NotFoundHttpException in Handler.php line 131:
No query results for model [App\Models\Video].
Route:
Route::group(['middleware'=>['auth']],function(){
Route::get('/upload','VideoUploadController#index');
Route::post('/videos','VideoController#store');
Route::put('/videos/{video}','VideoController#update');
Route::get('/channel/{channel}/edit','ChannelSettingsController#edit');
Route::put('/channel/{channel}/edit','ChannelSettingsController#update');
});
Controler:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\VideoUpdateRequest;
use App\Models\Video;
class VideoController extends Controller
{
public function store(Request $request)
{
$uid = uniqid(true);
$channel = $request->user()->channel()->first();
$video = $channel->video()->create([
'uid'=>$uid,
'title'=>$request->title,
'description'=>$request->description,
'visibility'=>$request->visibility,
'video_filename'=>"{$uid}.{$request->extension}",
]);
return response()->json([
'data' => [
'uid' => $uid
]
]);
}
public function update(VideoUpdateRequest $request, Video $video)
{
//authentication checked here .......
$video->update([
'title' => $request->title,
'description' => $request->description,
'visibility' => $request->visibility,
'allow_votes' => $request->has('allow_votes'),
'allow_comments' => $request->has('allow_comments')
]);
if ($request->ajax()) {
return response()->json(null, 200);
}
return redirect()->back();
}
}
Uplod.vue
<template>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Example Component</div>
<div class="panel-body">
<input type="file" name="video" id="video" #change="changfileInputChange" v-if="!uploading">
<div id="video-form" v-if="uploading&&!failed">
<div class="form-group">
<label for="title">Title</label>
<input type="" name="" v-model="title" class="form-control">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control"v-model="description"></textarea>
</div>
<div class="form-group">
<label for="visibility">Visibility</label>
<select class="form-control" v-model="visibility">
<option value="private">Private</option>
<option value="public">Public</option>
<option value="unlisted">Unlisted</option>
</select>
</div>
<span class="help-block pull-right">{{saveStatus}}</span>
<button class="btn btn-default" type="submit"#click.prevent="update">Save changes</button>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
mounted() {
console.log('Component mounted.')
},
data()
{
return{
uid:null,
uploading:false,
uplodComplete:false,
failed:false,
title:'unlisted',
description:null,
visibility:'private',
saveStatus:null
}
},
methods:{
changfileInputChange()
{
this.uploading=true;
this.failed=false;
this.file=document.getElementById('video').files[0];
this.storeVideo().then(()=>{
})
},
storeVideo(){
return this.$http.post('/videos',{
title:this.title,
description:this.description,
visibility:this.visibility,
extension:this.file.name.split('.').pop()
}).then((response)=>{
this.uid = response.json().data.uid;
});
},
update() {
this.saveStatus = 'Saving changes.';
return this.$http.put('/videos/' + this.uid, {
title: this.title,
description: this.description,
visibility: this.visibility
}).then((response) => {
this.saveStatus = 'Changes saved.';
setTimeout(() => {
this.saveStatus = null
}, 3000)
}, () => {
this.saveStatus = 'Failed to save changes.';
});
}
}
}
</script>
In first i save video to db along with some default value for title,description etc with ajax request,Please see Video.vue code for this
I am getting uid(unique id for video)in console from store method but when i update by clicking the save chages button i got error like this:
when i used i default uid in controller in
public function store(Request $request)
{
$uid = '158cfff622e1b7';
//....some code here
//finally return $uid
return response()->json([
'data' => [
'uid' => $uid
]
]);
}
and in Upload.vuein this line if i change uid to default 158cfff622e1b7,it works fine ie:result updated
return this.$http.put('/videos/' +'158cfff622e1b7', {
//code
});
it means i am not getting `uid` ,or something is wrong,please help me
Here is screenshot of error: http://imgur.com/a/7XGER
Error: PUT http://localhost:8000/videos/null 404 (Not Found)
I can see you are using route model binding.
Route::put('/videos/{video}','VideoController#update');
Route model binding works out of the box with ID field. If you use a different key, you need to tell your model to use that key for route model binding.
In Video model add
public function getRouteKeyName() {
return 'uid';
}
Update
In providers/RouteServiceProvider, add this inside boot()
Route::bind('video', function ($value) {
return App\Models\Video::where('uid', $value)->first();
});
If it still does not work, simply get the video and update it, the good old way
public function update(VideoUpdateRequest $request, $uid)
{
$video = Video::where('uid', $uid)->first();
$video->title = $request->title;
$video->description = $request->description;
...
$video->update();
if ($request->ajax()) {
return response()->json(null, 200);
}
return redirect()->back();
}
Replace this this.uid = response.json().data.uid; by this.uid = response.body.data.uid;
it must work,if not let me hear
Read Docs for more

fetching the data from database using angularjs and JSON

Hi iam trying to fetch the data from database using angularjs but it is not displaying any data.I just started to learn AngularJs.Can any one help me this.Here is my code
income.html
<div class="container jumbotron" ng-init= "getIncomeSource()" ng-controller="IncomeSourcesController" id="homejumbotron">
<table>
<thead>
<th>Name of the Employer</th>
<th>Income From Salary</th>
<th>TDS Deducted</th>
<th></th>
</thead>
<tbody>
<tr ng-repeat="x in incomesources" >
<td>{{x.company_name}}</td>
<td>{{x.user_income}}</td>
<td>{{x.tax_deducted_salary}}</td>
</tbody>
js
var app = angular.module('accountantApp', []);
app.controller('IncomeSourcesController', function($scope,$http) {
console.log("inside homecontroller:::");
$scope.getIncomeSource = function(){
$scope.user = "";
console.log("Inside getPersonalInfo::::::");
$http({
method : 'POST',
url : '../model/incomesources.php',
headers : {
'Content-Type': 'application/json'
},
data : {"action": "GetIncomeSources"}
})
.success(function( data,status, headers) {
console.log("Response data:"+ JSON.stringify(data));
if (data.success != undefined && data.success != '')
{
$scope.user = data;
}
})
.error(function(data, status, headers) {
alert("Error occured while retrieving:"+status);
console.log("Error data::::"+ data);
console.log("status::::"+ status);
});
};
});
incomesources.php
function getIncomeSources()
{
session_start();
$userInfo = $_SESSION['USER'];
$userEmailid= $userInfo-> getEmailid();
$res="SELECT * FROM user_salary_details WHERE email ='$userEmailid'";
$result=mysql_query($res);
if ($row = mysql_fetch_assoc($result))
{
$companyname = $row["company_name"];
$userincome = $row["user_income"];
$employetype = $row["employe_type"];
$tan = $row["tan_employer"];
$tax = $row["tax_deducted_salary"];
$address = $row["address"];
$state = $row["state"];
$city=$row["city"];
$pin=$row["pincode"];
$data = array(
"success" => "success",
"companyname" => $companyname,
"userincome" => $userincome,
"employetype" => $employetype,
"tan" => $tan,
"tax" => $tax,
"address" => $address,
"state" => $state,
"city" =>$city,
"pin"=>$pin,
);
echo json_encode($data);
}else{
echo "No record exists for this user::";
}
}
Is your incomesources.php was working initially?
The WHERE clause in the select statement is looking for email='$userEmailid'
i think you want the content of $userEmailid. So try change to
$res="SELECT * FROM user_salary_details WHERE email ='". $userEmailid ."'";
EDIT
Since your php file is working, and you mentioned in above comments that you are able to see the return value in console, lets see your html and js code.
In your html please change to
<tr ng-repeat="x in user" >
<td>{{x.companyname}}</td>
<td>{{x.userincome}}</td>
<td>{{x.tax}}</td>
The properties in {{x.something}} is based on the php return properties, not from database column name.
In your js file, try initialize the $scope.user outside $scope.getIncomeSource function and init it as an array. For example
console.log("inside homecontroller:::");
$scope.user = []; // this
$scope.getIncomeSource = function(){
console.log("Inside getPersonalInfo::::::");
$http({
Hope this help

Can't override FOSUserBundle ProfileFormType buildForm() function

I've been trying to override the ProfileFormType from the FOSUserBundle. I followed the steps from my previous problem which has been solved since my current task is somehow similar to the previous one. (I use AngularJS for frontend)
Unfortunately, I can't seem to override the buildForm() function from the parent class.
I've logged the form errors and it says:
ERROR: This form should not contain extra fields.
current_password:
ERROR: This value should be the user's current password.
services.yml
services:
acme.profile.form.type:
class: Acme\BulletinBundle\Form\Type\ProfileFormType
arguments: ["%fos_user.model.user.class%"]
tags:
- { name: form.type, alias: acme_user_profile }
config.yml
fos_user:
profile:
form:
type: acme_user_profile
ProfileFormType.php
namespace Acme\BulletinBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ProfileFormType extends AbstractType {
private $class;
public function __construct($class) {
$this->class = $class;
}
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('username', null, array('label' => 'form.username', 'translation_domain' => 'FOSUserBundle'))
->add('email', 'email', array('label' => 'form.email', 'translation_domain' => 'FOSUserBundle'));
}
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array(
'data_class' => $this->class,
'intention' => 'profile',
'csrf_protection' => false,
));
}
public function getParent() {
return 'fos_user_profile';
}
public function getName() {
return 'acme_user_profile';
}
}
UserController.php
/**
* #Method("POST")
* #Route("/user/edit", name="user_edit", options={"expose"=true})
*/
public function editAction(Request $request) {
$id = $request->request->get('id');
$user = $this->getDoctrine()
->getManager()
->getRepository("AcmeBulletinBundle:User")
->find($id);
/** #var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
$formFactory = $this->get('fos_user.profile.form.factory');
$form = $formFactory->createForm();
$form->setData($user);
$form->handleRequest($request);
if ($form->isValid()) {
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
$userManager->updateUser($user);
return new JsonResponse(['valid' => true]);
}
$errs = (string) $form->getErrors(true, false);
return new JsonResponse(['valid' => $errs]);
}
edit.html
<form class="form-group text-left" ng-submit="submit()" novalidate name="userFrm">
<div class="form-group">
<label for="user.email" class="required">Email</label>
<input id="user.email" name="user.username" class="form-control" required type="text" ng-model="user.email" />
</div>
<div class="form-group">
<label for="user.username" class="required">Username</label>
<input id="user.username" name="user.username" class="form-control" required type="text" ng-model="user.username" />
</div>
<input type="submit" value="Update" ng-disabled="userFrm.$invalid" class="btn btn-primary center-block col-lg-2" />
</form>
edit.js
angular.module('myApp', [])
.controller('EditUserCtrl', ["$scope", "$http", "$state", "$stateParams", function ($scope, $http, $state, $stateParams) {
//returns {username: data1, email: data2, enabled: data3}
$http.get(Routing.generate('get_user', {id: $stateParams.id}))
.then(function (response) {
var user = response.data.user;
$scope.user = user;
});
$scope.submit = function () {
var formData = {
fos_user_profile_form: $scope.user,
id : $stateParams.id
};
var success = function (response) {
var valid = response.data.valid;
console.log(valid);
};
var error = function (reason) {
alert('error');
};
console.log($scope.user);
$http.post(Routing.generate('user_edit'), $.param(formData), {
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(success, error);
}
}
}]);
The problem is that you extending profile form, but in your form template none of main fields exist. Remove this lines from your form type:
public function getParent() {
return 'fos_user_profile';
}
or add missing field current_password to edit.html.

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