fetching the data from database using angularjs and JSON - javascript

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

Related

Issue with filtering data using array in Angularjs

I apologies if I did any mistake here I am new to AngularJs and Stackoverflow.
I am having a table with 2 different filters first filter works by api calling accepts payload - fromDate and toDate to filter data based on the dates provided by the user from frontend.
Second filter is 2 buttons which is used to filter data for showing myData and allData. From the JSON response I am matching the email of response object and current loggedIn person's email, to identify myData. allData is the entire response.
Issue that I am facing is when I filter my data using API by passing from and to date, my allData filtering logic is not working properly.
code-
<div class="card-body">
<div id="buttonsDiv" class="mb-2">
<button ng-disabled="currentFilterDeal==='ALL'" class="btn btn-primary mr-2" ng-click="filterTable('ALL')">All Data</button>
<button ng-disabled="currentFilterDeal==='MY'" class="btn btn-primary mr-2" ng-click="filterTable('MY')">My Data</button>
</div>
<table style="width: 100%;" id="dataTable" class="table table-hover table-striped table-bordered">
<tbody>
<tr ng-repeat="data in finalData track by $index">
<td class="text-center">{{data.id}}</td>
<td class="text-center">{{data.email}}</td>
<td class="text-center">{{data.address}}</td>
<td class="text-center">{{data.phoneNumber}}</td>
</tr>
</tbody>
</table>
</div>
AngularJs-
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope,$window) {
$scope.allData=[];
$scope.getInitialData = function() {
let dataInit= {
"fromDate":null,
"toDate": null
}
var settings = {
"url": "//BackendUrl",
"method": "POST",
"headers": {
"Authorization": "Bearer Token",
"Content-Type": "application/json"
},
"data": JSON.stringify(dataInit),
};
$.ajax(settings).done(function (response) {
$scope.allData = response.allData;
$scope.data = [];
//to get myData
$scope.allData.forEach(function (element) {
if(element.data != null){
if (element.data.email== $scope.loggedInUser) {
$scope.data.push(element)
}
$scope.currentFilterDeal = "MY";
}
})
$scope.finalData = $scope.data;
$scope.$apply();
var table = $('#dataTable').DataTable({});
table.order( [ 0, 'desc' ] ).draw();
var requestedType ="<?=$allCallbacks;?>";
if(requestedType === "true"){
$scope.filterTable('ALL');
$scope.$apply();
}
}).fail(function(err){
console.log(err);
});
}
$scope.getInitialData();
$scope.getFilteredData = function (data2){
let data = Object.assign({},data2)
var setting = {
"url": "BackendUrl/Filter",
"method": "POST",
"headers": {
"Authorization": "Bearer Token",
"Content-Type": "application/json"
},
"data": JSON.stringify(data)
};
$.ajax(setting).done(function (response) {
$scope.allData = response.allData;
$scope.data = [];
$scope.allData.forEach(function (element) {
if(element.data != null){
if (element.data.email== $scope.loggedInUser) {
$scope.data.push(element)
}
$scope.currentFilterDeal = "MY";
}
})
$scope.finalData = $scope.data;
$scope.$apply();
}).fail(function(data){
toastr["error"]("We could not filter your contacts.", "Contacts list not loaded!");
$('#filterButton').attr('disabled',false).html('Filter');
});
$('#filterButton').attr('disabled',false).html('Filter');
}
$scope.filterTable = (deal) => {
$scope.currentFilterDeal = deal;
if(deal==='ALL') {
$('#dataTable').DataTable().destroy();
$scope.finalData = $scope.allData;
console.log("all numbers list ->", $scope.fnalData); //getting correct numbers after filtering
$('#dataTable').ready(function () {
var table = $('#dataTable').DataTable({});
table.order( [ 0, 'desc' ] ).draw();
})
}else if(deal==='MY'){
$scope.data = [];
$scope.allData.forEach(function (element) {
if(element.data != null){
if (element.data.email=== $scope.loggedInUser){
$scope.data.push(element)
}
$scope.currentFilterDeal = "MY";
}
})
$('#dataTable').DataTable().destroy();
$scope.finalData = $scope.data;
$('#dataTable').ready(function () {
var table = $('#dataTable').DataTable();
table.order( [ 0, 'desc' ] ).draw();
})
}
else{}
}
});
Issue - I am struggling with the logic of showing myData and allData after filtering. My current code works perfectly fine until I filter data using API and got new JSON response with more json objects, my allData filter doesn't work there and shows all data from initial response only.
For Example - Initially I got 3 objects as response in an array on which 2 responses are myData and 1 is not myData so I am showing it in allData.
When I filter by giving from date and to date I got 10 objects in response.
This time if 5 is myData I can see that in the table it works fine. But If I want to see allData by clicking on All Data button I got to see only 3 data there which was the response I've got initially.
You can use filter for filtering the response objects.
You can make a function that receives the data and filter criteria. If you need all data then simply return the object and filter when there is a criteria. Hope this helps

Trouble with datatables reload()

I want to populate a jQuery datatable based on the content of a textarea. Note: my datatables implementation is not serverside. That is: sorting/filtering happens on the client.
I know my php works as it returns expected results in my test scenario (see below). I have included a lot of code to provide context. I am new to datatables and php.
My html looks like this:
// DataTable Initialization
// (no ajax yet)
$('#selectedEmails').DataTable({
select: {
sytle: 'multiple',
items: 'row'
},
paging: false,
scrollY: '60vh',
scrollCollapse: true,
columns: [
{data: "CONICAL_NAME"},
{data: "EMAIL_ADDRESS"}
]
});
// javascript that defines the ajax (called by textarea 'onfocus' event)
function getEmails(componentID) {
deselectTabs();
assignedEmails = document.getElementById(componentID).value.toUpperCase().split(",");
alert(JSON.stringify(assignedEmails)); //returns expected json
document.getElementById('email').style.display = "block";
//emailTable = $('#selectedEmails').DataTable();
try {
$('#selectedEmails').DataTable().ajax =
{
url: "php/email.php",
contentType: "application/json",
type: "POST",
data: JSON.stringify(assignedEmails)
};
$('#selectedEmails').DataTable().ajax.reload();
} catch (err) {
alert(err.message); //I get CANNOT SET PROPERTY 'DATA' OF null
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- table skeleton -->
<table id="selectedEmails" class="display" style="width: 100%">
<thead>
<tr>
<th colspan='2'>SELECTED ADDRESSES</th>
</tr>
<tr>
<th>Conical Name</th>
<th>Email Address</th>
</tr>
</thead>
</table>
<!-- textarea definition -->
<textarea id='distribution' name='distribution' rows='3'
style='width: 100%' onblur="validateEmail('INFO_DISTRIBUTION', 'distribution');"
onfocus="getEmails('distribution');">
</textarea>
The following code returns the expected json:
var url = "php/email.php";
emailList = ["someone#mycompany.com","someoneelse#mycompany.com"];
fetch(url, {
method: 'post',
body: JSON.stringify(emailList),
headers: {
'Content-Type': 'application/json'
}
}).then(function (response) {
return response.text();
}).then(function (text) {
alert( JSON.stringify( JSON.parse(text))); //expencted json
}).catch(function (error) {
alert(error);
});
php code:
require "openDB.php";
if (!$ora) {
$rowsx = array();
$rowx = array("CONICAL_NAME" => "COULD NOT CONNECT", "EMAIL_ADDRESS" => "");
$rowsx[0] = $rowx;
echo json_encode($rowsx);
} else {
//basic query
$query = "SELECT CONICAL_NAME, EMAIL_ADDRESS "
. "FROM SCRPT_APP.BCBSM_PEOPLE "
. "WHERE KEY_EMAIL LIKE '%#MYCOMANY.COM' ";
//alter query to get specified entries if first entry is not 'everybody'
if ($emailList[0]!='everybody') {
$p = 0;
$parameters = array();
foreach ($emailList as $email) {
$parmName = ":email" . $p;
$parmValue = strtoupper(trim($email));
$parameters[$p] = array($parmName,$parmValue);
$p++;
}
$p0=0;
$query = $query . "AND KEY_EMAIL IN (";
foreach ($parameters as $parameter) {
if ($p0 >0) {
$query = $query.",";
}
$query = $query.$parameter[0];
$p0++;
}
$query = $query . ") ";
$query = $query . "ORDER BY CONICAL_NAME";
$getEmails = oci_parse($ora, $query);
foreach ($parameters as $parameter) {
oci_bind_by_name($getEmails, $parameter[0], $parameter[1]);
}
}
oci_execute($getEmails);
$row_num = 0;
try {
while (( $row = oci_fetch_array($getEmails, OCI_ASSOC + OCI_RETURN_NULLS)) != false) {
$rows[$row_num] = $row;
$row_num++;
}
$jsonEmails = json_encode($rows, JSON_INVALID_UTF8_IGNORE);
if (json_last_error() != 0) {
echo json_last_error();
}
} catch (Exception $ex) {
echo $ex;
}
echo $jsonEmails;
oci_free_statement($getEmails);
oci_close($ora);
}
Looking at a couple of examples on the DataTables site, I found I was making this more difficult than it needed to be: Here is my solution:
HTML: (unchanged)
<table id="selectedEmails" class="display" style="width: 100%">
<thead>
<tr>
<th colspan='2'>SELECTED ADDRESSES</th>
</tr>
<tr>
<th>Conical Name</th>
<th>Email Address</th>
</tr>
</thead>
</table>
<textarea id='distribution' name='distribution' rows='3'
style='width: 100%'
onblur="validateEmail('INFO_DISTRIBUTION', 'distribution');"
onfocus="getEmailsForTextBox('distribution');">
</textarea>
javascript:
Note: The key was the function for data: which returns json. (My php code expects json as input, and of course, outputs json).
[initialization]
var textbox = 'developer'; //global variable of id of textbox so datatables can use different textboxes to populate table
$(document).ready(function () {
$('#selectedEmails').DataTable({
select: {
sytle: 'multiple',
items: 'row'
},
ajax: {
url: "php/emailForList.php",
contentType: "application/json",
type: "post",
data: function (d) {
return JSON.stringify(document.getElementById(textbox).value.toUpperCase().split(","));
},
dataSrc: ""
},
paging: false,
scrollY: '60vh',
scrollCollapse: true,
columns: [
{data: "CONICAL_NAME"},
{data: "EMAIL_ADDRESS"}
]
});
});
[code that redraws table]
function getEmailsForTextBox(componentID) {
deselectTabs();
document.getElementById('email').style.display = "block";
textbox = componentID; //textbox is global variable that DataTable uses as source control
$('#selectedEmails').DataTable().ajax.reload();
}

Laravel Ajax not updating

I have Laravel project for fire department and I have competitions with results of each team. I made a page where I can edit competition. In result controller
public function update (Request $request){
$item = new Items();
$item->item = $request->item;
$item->data = $request->data;
$item->miejscowosc = $request->miejscowosc;
$item->gmina = $request->gmina;
$item->wojewodztwo = $request->wojewodztwo;
$item->poziom = $request->poziom;
$item->komisja1 = $request->komisja1;
$item->komisja2 = $request->komisja2;
$item->komisja3 = $request->komisja3;
$item->komisja4 = $request->komisja4;
$item->komisja5 = $request->komisja5;
$item->sedzia_glowny = $request->sedzia_glowny;
$item->komisje_powolal = $request->komisje_powolal;
$item->protesty = $request->protesty;
$item->kontuzje = $request->kontuzje;
$item->uwagi = $request->uwagi;
$item->update();
return 'Done';
}
When I change :
$item->update();
To :
$item->save();
It perfectly adds new competition. But when I have
$item->update();
It doesn't update.
Here is my ajax code :
$(document).ready(function() {
$('#updateComp').click(function (event){
$.ajax({
type: 'post',
url: '',
data: {
'_token': $('input[name=_token]').val(),
'item': $("#item").val(),
'data': $('#data').val(),
'miejscowosc': $('#miejscowosc').val(),
'gmina': $('#gmina').val(),
'wojewodztwo': $('#wojewodztwo').val(),
'poziom': $('#poziom :selected').text(),
'komisja1': $('#komisja1').val(),
'komisja2': $('#komisja2').val(),
'komisja3': $('#komisja3').val(),
'komisja4': $('#komisja4').val(),
'komisja5': $('#komisja5').val(),
'sedzia_glowny': $('#sedzia_glowny').val(),
'komisje_powolal': $('#komisje_powolal').val(),
'protesty': $('#protesty').val(),
'kontuzje': $('#kontuzje').val(),
'uwagi': $('#uwagi').val()
},
success: function(data){$('#alert').append('<div class="alert alert-success">Dodano do bazy</div>')},
error: function(){$('#alert').html('<div class="alert alert-danger">Błąd, nie udało się dodać do bazy. Wprowadź dane ponownie</div>')}
});
});
Do I have to change something in ajax code to make it work? Or is it another reason?
(really sorry for other language in project)
For eloquent update, change your code like below code:
Items::find($id)->update(['column' => 'value']);
Here $id is id which you want to update the record. See document
UPDATE
$id = $request->id;//Item id to update...
$arrItem = array(
'item' => $request->item,
'data' => $request->data,
.
.
.
'uwagi' => $request->uwagi,
);
//Update item data...
Items::find($id)->update($arrItem);
you have to send the item id to, so it can point which item need to update
$.ajax({
type: 'post',
url: 'your_url',
data: {
'id':$('#your_id_field'),
'your other field':$('#your_other_field),
.
.
},
success: function(data){$('#alert').append('<div class="alert alert-success">Dodano do bazy</div>')},
error: function(){$('#alert').html('<div class="alert alert-danger">Błąd, nie udało się dodać do bazy. Wprowadź dane ponownie</div>')}
});
//controller, find the data using items model by searching the item's id
public function update (Request $request){
$item = Items::find($request->get('id'));
$item->item = $request->get('item');
.....
.....
....
$item->update();
return 'Done';
}

Ajax Message not displaying

I try to display an error message but it does'nt work.
When the email does'nt exist,
I have this message : Thank you : your email is added
But if the email is always in mailchimp or other error, I haven't message under the button submit.
Do you have an idea to resolve this point ?
Thank you
The detail of the error come from server.
string(88) "400: ****** is already a list member. Use PUT to insert or update list members."
array(5) {
["type"]=>
string(77) "http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/"
["title"]=>
string(13) "Member Exists"
["status"]=>
int(400)
["detail"]=>
string(83) "********* is already a list member. Use PUT to insert or update list members."
["instance"]=>
string(0) ""
}
my javascript is
$footer .= '
<script>
$(document).ready(function() {
$('#signup').submit(function() {
$("#message").html("<div class=\"alert alert-info\" style=\"padding:05px; margin-top:5px;\" role=\"alert\">Thank you : your email is added</div>");
$.ajax({
url: 'ext/api/mailchimp_v3/subscribe.php', // proper url to your "store-address.php" file
type: 'POST', // <- IMPORTANT
dataType: 'json',
data: $('#signup').serialize() + '&ajax=true',
success: function(msg) {
var message = '';
var result = '';
message = $.parseJSON(msg);
if (message.status === 'pending') { // success
result = '<div class=\"alert alert-success\" role=\"alert\">Thank you: an email has sent you for confirmation</div>';
} else { // error
result = '<div class=\"alert alert-danger\" role=\"alert\">Error ' + message.detail + '</div>';
}
},
complete: function(message) {
$('#message').html('<div> ' + message.title + '</div>'); // display the message
}
});
$('#fname').attr('value',''); // reset input field
$('#lname').attr('value',''); // reset input field
$('#email').attr('value',''); // reset input field
return false;
});
});
</script>';
PHP code
if ( isset($_POST['anonymous'])) {
$list_id = MODULES_HEADER_TAGS_MAILCHIMP_LIST_ANONYMOUS;
$merge_vars = [
'FNAME' => '',
'LNAME' => ''
];
} else {
$list_id = MODULES_HEADER_TAGS_MAILCHIMP_LIST_CUSTOMERS;
$merge_vars = [
'FNAME' => $_POST['firstname'],
'LNAME' => $_POST['lastname']
];
}
$array = [
'email_address' => $_POST['email'],
'merge_fields' => $merge_vars,
'status' => MODULES_HEADER_TAGS_MAILCHIMP_STATUS_CHOICE
];
if (MODULES_HEADER_TAGS_MAILCHIMP_STATUS_CHOICE == 'pending') {
$status = 'pending';
} else {
$status = 'subscribed';
}
$mc = new \MailChimp($key);
// add the email to your list
$result = $mc->post('/lists/' . $list_id . '/members', $array);
//send
json_encode($result);
// If being called via ajax, run the function, else fail - console
if ( MODULES_HEADER_TAGS_MAILCHIMP_DEBUG == 'True') {
if ($_POST['ajax']) {
var_dump($result); // send the response back
} else {
var_dump('Method not allowed - please ensure JavaScript is enabled in this browser');
}
}

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

Categories

Resources