JavaScript & Ajax not working in laravel 5.2 - javascript

I have my category page. I need when i click Create category button it add new category. But when I click on the submit button nothing happend and it shows no error message. Where the problem is? Please Help
My Category blade template is
#extends('layouts.admin-master')
#section('styles')
<link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
{!! Html::style('src/css/categories.css') !!}
#endsection
#section('content')
<div class="container">
<section id="category-admin">
<form action="" method="post">
<div class="input-group">
<label for="Category">Category Name</label>
<input type="text" name="name" id="name">
<button type="submit" class="btn">Create Category</button>
</div>
</form>
</section>
<section class="list">
#foreach($categories as $category)
<article>
<div class="category-info" data-id="{{ $category->id }}">
<h3>{{ $category->name }}</h3>
</div>
<div class="edit">
<nav>
<ul>
<li class="category-edit"><input type="text" name=""></li>
<li>Edit</li>
<li>Delete</li>
</ul>
</nav>
</div>
</article>
#endforeach
</section>
#if($categories->lastPage() > 1)
<section class="pagination">
#if($categories->currentPage() !== 1)
<i class="fa fa-caret-left"></i>
#endif
#if($categories->currentPage() !== $categories->lastPage())
<i class="fa fa-caret-right"></i>
#endif
</section>
#endif
</div>
#endsection
#section('scripts')
<script type="text/javascript">
var token = "{{ Session::token() }}";
</script>
{!! Html::script('src/js/categories.js') !!}
#endsection
My categories.js file is
var docReady = setInterval(function() {
if(document.readyState !== "complete") {
return;
}
clearInterval(docReady);
document.getElementsByClassName('btn')[0].addEventListener('click',createNewCategory);
}, 100);
function createNewCategory(event) {
event.preventDefault();
var name = event.target.previousElementsSibling.value;
if(name.length === 0) {
alert("Please create A valid Category");
return;
}
ajax("POST", "/admin/blog/category/create", "name=" + name, newCategoryCreated, [name]);
}
function newCategoryCreated(params, success, responseObj) {
location.reload();
}
function ajax(method, url, params, callback, callbackParams) {
var http;
if(window.XMLHttpRequest) {
http = new XMLHttpRequest();
} else {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
http.onreadystatechange = function() {
if (http.readyState == XMLHttpRequest.DONE) {
if (http.status == 200) {
var obj = JSON.parse(http.responseText);
callback(callbackParams, true, obj);
} else if (http.status == 400) {
alert("Category could not be saved. Please Try Again");
callback(callbackParams, false);
} else {
var obj = JSON.parse(http.responseText);
if (obj.message) {
alert(obj.message);
} else {
alert("please Check the name");
}
}
}
}
http.open(method, baseUrl + url, true);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
http.send(params + "&_token=" + token);
}
my route file is
Route::get('/blog/categories', [
'uses' => 'CategoryController#getCategoryIndex',
'as' => 'admin.blog.categories'
]);
Route::post('/blog/category/create', [
'uses' => 'CategoryController#postCreateCategory',
'as' => 'admin.blog.category.create'
]);
And my Category controller is
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Category;
use Illuminate\Support\Facades\Response;
class CategoryController extends Controller
{
public function getCategoryIndex() {
$categories = Category::orderBy('created_at','desc')->paginate(5);
return view('admin.blog.categories',['categories' => $categories]);
}
public function postCreateCategory(Request $request) {
$this->validate($request, [
'name' => 'required|unique:categories'
]);
$category = new Category();
$category->name = $request['name'];
if($category->save()) {
return Response::json(['message' => 'Category Created'], 200);
}
return Response::json(['message' => 'Error during Creation'], 404);
}
}

Send the token either in the headers or as a parameter to the server. More information here:
https://laravel.com/docs/5.2/routing#csrf-protection

Related

Invalid reCAPTCHA client id: 1 - Multiple Captcha render, something wrong with my code?

I have 2 modal that each have a grecaptcha. I load the script once the first modal is opened and render the captcha for that specific modal afterwards. This is working as expected. But once i submit the form with the captcha, i get the following error:
Uncaught Error: Invalid reCAPTCHA client id: 1
This is the JS code of the captcha render
var grecaptcha_contact = 0;
var grecaptcha_newsletter = 0;
function renderCaptcha(grecaptchatype) {
// Render Google Captcha
function renderCall(grecaptchatype) {
var captcha = grecaptcha.render(grecaptchatype, {
'sitekey': 'SITEKEY_censored',
'theme': 'light'
});
}
// Check if Google Captcha already rendered
if(grecaptchatype === 'g-recaptcha-newsletter'){
if(grecaptcha_newsletter !== 0){
return false;
}
else{
// Render Google Captcha
renderCall(grecaptchatype);
grecaptcha_newsletter++;
}
}
else if(grecaptchatype === 'g-recaptcha-contact'){
if(grecaptcha_contact !== 0){
return false;
}
else{
// Render Google Captcha
renderCall(grecaptchatype);
grecaptcha_contact++;
}
}
}
// load google captcha script on show modal newsletter & contact us
$('#newsletterModal').on('shown.bs.modal', function () {
if(window.grecaptcha) {
renderCaptcha('g-recaptcha-newsletter');
}
else{
var attempts = 0;
$.getScript('https://www.google.com/recaptcha/api.js')
.done(function() {
var setIntervalID = setInterval(function() {
if (window.grecaptcha) {
clearInterval(setIntervalID);
renderCaptcha('g-recaptcha-newsletter');
return false;
}
else if (attempts >= 100) {
clearInterval(setIntervalID);
return false;
}
attempts++;
}, 100);
});
}
});
$('#contactModal').on('shown.bs.modal', function () {
if(window.grecaptcha) {
renderCaptcha('g-recaptcha-contact');
}
else{
var attempts = 0;
$.getScript('https://www.google.com/recaptcha/api.js')
.done(function() {
var setIntervalID = setInterval(function() {
if (window.grecaptcha) {
clearInterval(setIntervalID);
renderCaptcha('g-recaptcha-contact');
return false;
}
else if (attempts >= 100) {
clearInterval(setIntervalID);
return false;
}
attempts++;
}, 100);
});
}
});
This is the Newsletter Form:
<button aria-label="Newsletter" type="button" class="newsletterbutton" data-toggle="modal"
data-target="#newsletterModal">#lang('footer.blade.newsletter')</button>
<div class="modal fade" id="newsletterModal" tabindex="-1" role="dialog" aria-labelledby="newsletterModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<div class="modal-title" id="newsletterModalLabel">#lang('footer.blade.receive_newsletter')</div>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{{ Form::open(['id' => 'newsletterform']) }}
{{ csrf_field() }}
<div class="modal-body">
<div class="alert"></div>
<div class="form-group">
{{ Form::label('newsletter_email', __('footer.blade.contact.email'), ['class' => 'col-form-label']) }}
{{ Form::email('newsletter_email', '', ['required', 'class' => 'form-control']) }}
</div>
<div class="row form-group">
<div class="col-sm-12 acceptrules">
{{ Form::checkbox('acceptrules', 'value', null, ['id' => 'acceptrules', 'required']) }}
<label for="acceptrules" class="control-label">
#lang('add_app.blade.acceptrules')<a class="privacypolicy_link" target="_blank" href="{{ route('privacy-policy') }}">#lang('add_app.blade.acceptrules_link')</a>#lang('add_app.blade.acceptrules_link2')
</label>
</div>
</div>
<div class="form-group g-recaptcha-div">
<div class="g-recaptcha-newsletter g-recaptcha-count" id="g-recaptcha-newsletter"></div>
#if($errors->has('g-recaptcha-response'))
<span>{{$errors->first('g-recaptcha-response')}}</span>
#endif
</div>
</div>
<div class="modal-footer modal-footer-recaptcha">
{{ Form::submit(__('footer.blade.apply_newsletter'), ['class' => 'btn btn-primary']) }}
{{ Form::button(__('footer.blade.close_newsletter'), ['class' => 'btn btn-secondary', 'data-dismiss' => 'modal']) }}
</div>
{{ Form::close() }}
</div>
</div>
</div>
I'm not sure but i think the captcha was working before. I'm not sure if i changed something in the code which broke it or something else that broke it (server/laravel configs). Someone has an idea where to go from here?
I checked on my php code and the error appears here in the captcha.php:
public function passes($attribute, $value)
{
$client = new Client();
$response = $client->post('https://www.google.com/recaptcha/api/siteverify',
[
'form_params' => [
'secret' => env('CAPTCHA_SECRET', false),
'remoteip' => request()->getClientIp(),
'response' => $value
]
]
);
$body = json_decode((string)$response->getBody());
return $body->success;
}
The getbody() response if success=false
The $attribute is g-recaptcha-response and the $value is a long key probably the public key encrypted.
The secret form_params seems false all the time. I'm not sure why is that, my env file has the captcha_secret set. I tried it with my secret key inside this function instead which did it. So there seems to be something wrong with my env secret key call. Maybe a caching problem or so, will try to figure it out myself from here.

File not uploading when uploading with AJAX using symfoy

I am developing an application and i want to upload a picture using Ajax with symfony 3.4. Sorry if i am missing anything because i am new to AJAX. I am following the step from https://codepen.io/dsalvagni/pen/BLapab
I am getting the 200 response from symfony but the files doesnt upload.
Entity:
/**
* #ORM\Column(type="string", length=255)
* #var string
*/
private $image;
/**
* #Vich\UploadableField(mapping="profile_image", fileNameProperty="image")
* #var File
*/
private $imageFile;
Here is my controller:
public function testAction(Request $request)
{
$testEntry = new Test();
$form = $this->createForm(TestType::class, $testEntry);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$file = $testEntry->getImageFile();
$fileName = md5(uniqid()) . '.' . $file->guessExtension();
$photoDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/images';
$file->move($photoDir, $fileName);
$testEntry->setImage($fileName);
$em = $this->getDoctrine()->getManager();
$em->persist($testEntry);
$em->flush();
if ($request->isXmlHttpRequest()) {
return new JsonResponse(array('message' => 'Success!', 'success' => true), 200);
}
if ($request->isMethod('POST')) {
return new JsonResponse(array('message' => 'Invalid form', 'success' => false), 400);
}
return $this->redirect($this->generateUrl('homepage'));
}
return $this->render('#Alumni/Default/test.html.twig',
['form' => $form->createView()]);
}
and here is my html.twig
{{ form_start(form) }}
{{ form_errors(form) }}
{{ form_row(form.name) }}
<div class="profile">
<div class="photo">
{{ form_widget(form.imageFile, {'attr': {'class': 'file-upload'}}) }}
<div class="photo__helper">
<div class="photo__frame photo__frame--circle">
<canvas class="photo__canvas"></canvas>
<div class="message is-empty">
<p class="message--desktop">Drop your photo here or browse your computer.</p>
<p class="message--mobile">Tap here to select your picture.</p>
</div>
<div class="message is-loading">
<i class="fa fa-2x fa-spin fa-spinner"></i>
</div>
<div class="message is-dragover">
<i class="fa fa-2x fa-cloud-upload"></i>
<p>Drop your photo</p>
</div>
<div class="message is-wrong-file-type">
<p>Only images allowed.</p>
<p class="message--desktop">Drop your photo here or browse your computer.</p>
<p class="message--mobile">Tap here to select your picture.</p>
</div>
<div class="message is-wrong-image-size">
<p>Your photo must be larger than 350px.</p>
</div>
</div>
</div>
<div class="photo__options hide">
<div class="photo__zoom">
<input type="range" class="zoom-handler">
</div><i class="fa fa-trash"></i>
</div>
<button type="button" id="uploadBtn">Upload</button>
</div>
</div>
{{ form_row(form.submit, { 'label': 'Submit me' }) }}
{{ form_end(form) }}
here is my route
test:
path: /test
defaults: {_controller: AlumniBundle:Default:test}
here is my js
$(function() {
/**
* DEMO
*/
var p = new profilePicture('.profile', null,
{
imageHelper: true,
onRemove: function (type) {
$('.preview').hide().attr('src','');
},
onError: function (type) {
console.log('Error type: ' + type);
}
});
$('#uploadBtn').on('click', function() {
var image = p.getAsDataURL();
$.post("/test", { image: image });
});
and i am getting 200 response but i cannot locate the file:
Many thanks in advance for your help
It won't upload because your function isn't sending any file.
It's just sending the file name at most.
The Function
function ajaxSubmit(node) {
$.ajax({
type: node.attr("method"), // Method on form tag
url: node.attr("action"), // Action on form tag
enctype: "multipart/form-data", //needed to upload files
data: new FormData(node[0]), // The form content
processData: false,
contentType: false,
cache: false
}).done(function(response, status, xhr) {
console.info(response);
}).fail(function(request, status, error) {
console.error(request);
console.error(status);
console.error(error);
});
}
The Action
$(body).on("submit", ".ajs", function(e) {
e.preventDefault(); // Prevent default HTML behavior
ajaxSubmit($(this)); //Handle submit with AJAX
});
The View
// Add 'ajs' class to forms that should be submited with AJAX
{{ form_start(form, {'class': 'ajs'}) }}

Symfony2: manually submit a form without class via AJAX

We have an old website where I have implemented a form that is sent by AngularJS to a PHP script and after processing an email message get sent. If the form is not valid the PHP script returns a JSON with the validation errors. Since we already use Symfony for some other applications (REST APIs), I thought it would be nice to reimplement my plain PHP script in Symfony.
For the sake of simplicity I put only a small but relevant fragment of my code. This is what I have:
HTML (ng-app is bound on body tag, not shown here):
<form name="infoscreenForm" class="form-horizontal" enctype="multipart/form-data" ng-controller="FormController">
<div class="form-group">
<div class="col-lg-1 control-label">*</div>
<div class="col-lg-11 input-group">
<input type="text" class="form-control" id="contact_person"
name="contact_person" ng-model="formData.contactPerson"
placeholder="Kontaktperson">
</div>
<span class="text-warning" ng-show="errors.contactPerson">
{{ errors.contactPerson }}
</span>
</div>
<div class="form-group">
<div class="col-lg-1 control-label">*</div>
<div class="col-lg-11 input-group">
<span class="input-group-addon">#</span>
<input type="email" class="form-control" id="email" name="email"
ng-model="formData.email" placeholder="E-Mail">
</div>
<span class="text-warning" ng-show="errors.email">
{{ errors.email }}
</span>
</div>
<div class="form-group">
<div class="col-lg-1 control-label"> </div>
<div class="col-lg-11 input-group">
<input type="file" class="form-control" id="file" name="file"
file-model="formData.file"
accept="application/pdf,image/jpeg,image/png">
</div>
<span class="text-warning" ng-show="errors.file">
{{ errors.file }}
</span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default" id="submit"
name="submit" ng-click="submitForm()">
Formular absenden
</button>
</div>
</form>
JS:
var app = angular.module('InfoscreenApp', []);
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
app.factory('multipartForm', ['$http', function ($http) {
return {
post : function (uploadUrl, data) {
var fd = new FormData();
for (var key in data) {
fd.append(key, data[key]);
}
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers : { 'Content-Type': undefined }
});
}
};
}]);
app.controller('FormController', ['$scope', 'multipartForm', function ($scope, multipartForm) {
$scope.formData = {};
$scope.submitForm = function () {
var uploadUrl = 'http://localhost:8000/infoscreen';
multipartForm.post(uploadUrl, $scope.formData)
.then(function (data) {
console.log(data);
if (data.success) {
$scope.message = data.data.message;
console.log(data.data.message);
} else {
$scope.errors = data.data.errors;
}
});
};
}]);
With the plain PHP script everything works fine. Here is what I tried to do in Symfony:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Email;
class DefaultController extends Controller
{
/**
* #Route("/infoscreen", name="infoscreen")
*/
public function infoscreenAction(Request $request)
{
$defaultData = array('message' => 'infoscreenForm');
$form = $this->createFormBuilder($defaultData)
->add('contactPerson', TextType::class, array(
'constraints' => array(
new NotBlank(),
)
))
->add('email', EmailType::class, array(
'constraints' => array(
new NotBlank(),
new Email(),
)
))
->add('file', FileType::class)
->add('submit', SubmitType::class)
->getForm();
;
$form->submit($request->request->get($form->getName()));
$data = $form->getData();
if ($form->isValid()) {
echo 'Alles ok';
// send an email
}
$errors = array();
$validation = $this->get('validator')->validate($form);
foreach ($validation as $error) {
$errors[$error->getPropertyPath()] = $error->getMessage();
}
$response = new Response();
$response->setContent(json_encode(array(
'form_data' => $data,
'errors' => $errors,
)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
CSRF is disabled in config.yml. The form is not bound to an entity class. After submitting the form I get the following object in the console:
{
data: Object,
status: 200,
config: Object,
statusText: "OK"
}
The important part is in data: Object:
{
form_data: {
contactPerson: null,
email: null,
message: "infoscreenForm",
file: null
},
errors : {
children[contactPerson].data = "This value should not be blank",
children[email].data = "This value should not be blank"
}
}
This happens when I submit the form with some values entered in the fields. It seems that the submitted data is not bound to the form in the controller. I'm probably missing something, but I stuck here and have no idea how to proceed. I tried with $form->bind($request), $form->handleRequest($request) and few other things, but it didn't work. Even if I bind the fields individually, I still don't get their values in the form.
Can somebody please help me.
Thanks in advance.
Try
$this->get('form.factory')->createNamedBuilder(null, 'form', $defaultData)
instead of
$this->createFormBuilder($defaultData)

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

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