I am uploading a file using spring boot and angular js but when i click on import i have the erros mentioned in the title.
Here's my controller js
var app=angular.module("MyCat",[]);
app .directive("fileread", [function ()
{ return { scope: { fileread: "=" }, link: function (scope, element, attributes)
{ element.bind("change", function (changeEvent)
{ scope.$apply(function () { scope.fileread = changeEvent.target.files[0];
}); }); } } }]); // } }
//Upload files
$scope.upload=function(){
var fd = new FormData();
var url="http://localhost:8080/upload";
fd.append("file", $scope.rap.file);
fd.append("name",$scope.rap.name);
$http.post(url,fd,{
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
Here's my java controller
upload Files
#RequestMapping(value="/upload",headers=("content-type=multipart/*"),consumes = {"multipart/form-data"}, method=RequestMethod.POST)
public #ResponseBody String handleFileUpload(#RequestParam("name") String name,#RequestParam("file") MultipartFile file){
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(name)));
stream.write(bytes);
stream.close();
return "You successfully uploaded " + name + "!";
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name + " because the file was empty.";
}
}
Here's my html page
<section id="contact-page">
<div class="container">
<div class="center">
<p class="lead">Import reports</p>
</div>
<div class="row contact-wrap">
<div class="status alert alert-success" style="display: none"></div>
<form id="main-contact-form" class="contact-form" name="contact-form" method="POST" enctype="multipart/form-data" >
<div class="col-sm-5 col-sm-offset-1">
<div class="form-group">
<label>name *</label>
<input type="text" name="name" class="form-control" required="required" ng-model="rap.name">
</div>
<div class="form-group">
<label>DateOfUploade</label>
<input type="Date" class="form-control" ng-model="rap.dateOfUpload" >
</div>
<div class="form-group">
<label for="t">Type of File</label>
<select
class="form-control" id="t" ng-model="rap.type">
<option>.word</option>
<option>.xsl</option>
<option>.pdf</option>
</select>
</div>
<div class="form-group">
<label>file</label>
<input type="file" name="file" class="form-control" fileread="rap.file">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg" ng-click="upload()">Import File</button>
</div>
</div>
<table class="table">
<tr>
<th>NameOfUploader</th>
<th>DateOfUpload</th>
<th>TypeOfFile</th>
<th>File</th>
</tr>
<tr ng-repeat="rap in reports">
<td>{ {rap.NameOfUploader}}</td>
<td>{ {rap.DateOfUpload}}</td>
<td>{ {rap.TypeOfFile}}</td>
<td>{ {rap.File}}</td>
</tr>
</table>
</form>
</div><!--/.row-->
</div><!--/.container-->
</section><!--/#contact-page-->
enter code here
Any ideas ?
Unexpected token 'Y' - is starting of your message from java controller 'You successfully ...' that comes from the server instead of valid JSON string. Try to return something parseable: {"result": "You successfully bla-bla-bla..."}
Related
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.submitForm = function(cl) {
console.log(cl);
$http({
method: 'POST',
url: "updated-profile",
data: {
cl: cl
},
}).then(function successCallback(response) {
console.log("updated successfully");
$scope.success = "Updated successfully";
}, function errorCallback(response) {
console.log("not updated");
$scope.error = "Unable to update";
});
}
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="cl in clientList">
<div id="error-messages" ng-show="error">{{error}}</div>
<div id="success" ng-show="success">{{success}}</div>
<div class="form-group">
<div class="col-lg-4 col-md-4">
<label for="fname">First Name</label>
</div>
<div class="col-lg-8 col-md-8 ">
<input type="text" class="form-control" placeholder="First Name" ng-model="cl.fname" />
</div>
</div>
<div class="form-group">
<div class="col-lg-4 col-md-4">
<label for="lname">Last Name</label>
</div>
<div class="col-lg-8 col-md-8">
<input type="text " class="form-control" ng-model="cl.lname" />
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-4 col-md-4">
<label for="submit" class="sr-only">Update</label>
</div>
<div class="col-lg-8 col-md-8">
<input type="button" class="form-control btn btn-success" id="update" ng-click="submitForm(cl)" name="Update" value="Update" />
</div>
</div>
</div>
I am using above code to send data to server.
My server code is
public class Update extends ActionSupport {
private Client cl = new Client();
private String fname;
public String update() {
System.out.println("testing this");
System.out.println("client detail " + cl.getFname() + " " +
cl.getLname());
System.out.println("fname"+getFname());
}
}
I am getting
client detail null null
fnamenull
If I am using data: {fname: cl.fname}, then also fnamenull.
I am unable to pass any value using angular post to action.
What is wrong here?
What changes to made here to work it properly?
Your button
<input type="button" class="form-control btn btn-success" id="update" ng-click="submitForm(cl)" name="Update" value="Update" />
has to be inside the ng-repeat loop, otherwise it will not have access to the cl object as that is local to the ng-repeat scope.
Alternatively, if you want the button to be "global", you can submit the entire clientList in the ng-submit and then loop through the array inside your controller. It depends on your flow and what kind of UX/UI you need for the project.
$http({
method: 'POST',
url: "www.mylocalhost.com/api/updated-profile",
data: {
cl: cl
},
});
When you are calling a $http service "url" parameter shoul contain a proper api path. just use a valid api url . I hope it will work.
Or
change "cl":$scope.clientList
I want to display http response (JSON response) on html page in a table. To achieve this I wrote below controller function.
$scope.getSensorInfo=function(){
var strippeddata = [];
$http({
method: "GET",
url: "http://xx.xx.xx.xx:4000/config",
params: {did: $scope.cid}
}).then(function (success) {
if (success.data[0] === undefined) { //no device is available with this id
$http({
method: "GET",
url: "http://xx.xx.xx.xx:4000/info"
}).then(function(success1){
$scope.sinfo = success1.data;
},function(error1){
console.log('Error ' + JSON.stringify(error1));
});
} else {
Object.getOwnPropertyNames(success.data[0].obj).forEach(function (item, idx, list) {
Object.defineProperty(strippeddata, idx, {
enumerable: true,
configurable: true,
get: function () {
return {
name: item,
periodicity: success.data[0].obj[item].periodicity,
}
}
});
});
$scope.sinfo = strippeddata;
}
}, function (error) {
console.log('Error ' + JSON.stringify(error));
});
}
My html code is as follows.
<div class="row">
<div class="form-inline form-group">
<div class="col-md-3">
<label for="cnfdeviceid">Device ID</label>
<input class="form-control input-md" type="text" id="cnfdeviceid" placeholder="e.g. HYD01" ng-model="confdeviceid" ng-blur="getSensorInfo()"/>
</div>
</div>
</div>
<div ng-repeat="y in sinfo" class="[ form-group form-inline ]">
<input class="form-control input-md" type="checkbox" id="{{y.name}}" ng-model="name" ng-change="verify(y.name,y.periodicity,y.formula,name,$index)" autocomplete="off"/>
<div class="[ btn-group ]">
<label for="{{y.name}}" class="[ btn btn-success ]">
<span class="[ glyphicon glyphicon-ok ]"></span>
<span> </span>
</label>
<label for="{{y.name}}" class="[ btn btn-default active ]">
{{y.name}}
</label>
</div>
<input class="form-control input-md" type="text" ng-model="y.periodicity" placeholder="periodicity" id="{{y.periodicity}}" autocomplete="off"/>
</div>
When I am executing this code I am getting $digest 10 iterations reached aborting error. The following line is causing the problem but I am unable to rectify it.
$scope.sinfo = strippeddata;
Changing $scope.sinfo = strippeddata; to $scope.sinfo = strippeddata.slice(); resolved the issue.
I wrote the edit method to run when the edit link is clicked. I want it to load the data into text box, and is passing correct way but data is still not showing up in the text boxes.
Admin.js
var app = angular.module("adminmdl", [])
app.controller("admincontroller", function ($scope, AdminService) {
$scope.Action = 'Add';
GetAllCustomer();
function GetAllCustomer() {
var getcust = AdminService.getCustomer();
getcust.then(function (cust) {
$scope.customers = cust.data;
}, function () {
alert('Error');
});
}
$scope.data = {
cus_code: '',
cus_name: ''
}
$scope.savecu = function () {
if ($scope.Action == 'Add') {
AdminService.saveCustomerDdetails($scope.cusmodel).then(function (d) {
GetAllCustomer();
$scope.msg = "Insert Successfully";
}, function () {
$scope.msg = "Error Insert Customer";
});
}
}
$scope.EditCustomer = function (cust) {
$scope.Action = "Update";
AdminService.EditCustomersDetails(cust.cus_code).then(function (d) {
$scope.cust = d.data;
$scope.cust.cus_code = cust.cus_code;
$scope.cust.cus_name = cust.cus_name;
}, function () {
alert('Error Update Records');
});
//GetAllCustomer();
}
})
.service('AdminService', function ($http) {
this.getCustomer = function () {
return $http.get('GetCustomer');
}
this.saveCustomerDdetails = function (customer) {
var request = $http({
method: 'POST',
url: '/Admin/AddCutomer',
data: customer
});
return request;
}
this.EditCustomersDetails = function (CustomerCode) {
var request = $http({
method: 'POST',
url: '/Admin/EditCustomer',
params:{
id:CustomerCode
}
});
return request;
}
})
ASP MVC Method
[HttpPost]
public JsonResult EditCustomer(string id) {
var customerdetails = te.Customerss.Find(id);
return Json(customerdetails, JsonRequestBehavior.AllowGet);
}
HTML Form
<form class="form-horizontal" method="post" name="basic_validate" id="basic_validate" novalidate="novalidate">
<div class="control-group">
<label class="control-label">Customer Code</label>
<div class="controls">
<input type="text" ng-model="cusmodel.cus_code" name="required" id="required" >
</div>
</div>
<div class="control-group">
<label class="control-label">Customer Name</label>
<div class="controls">
<input type="text" ng-model="cusmodel.cus_name" name="name" id="name" >
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" value="Save" ng-click="savecu()" class="btn btn-success">
<input type="submit" value="Clear" class="btn btn-success" />
</div>
</div>
<div class="control-group">
<div class="controls">
<p style="color:green">{{msg}}</p>
</div>
</div>
#*<div class="form-actions">
</div>*#
</form>
Table
<div class="widget-content nopadding">
<table class="table table-bordered data-table">
<thead>
<tr>
<th>Customer Code</th>
<th>Customer Name</th>
</tr>
</thead>
<tbody>
<tr class="gradeX" ng-repeat="cust in customers">
<td>{{cust.cus_code}}</td>
<td>{{cust.cus_name}}</td>
<td>Edit</td>
<td> </td>
</tr>
</tbody>
</table>
</div>
its not working because you are trying to access data object which is not passed in json so either pass data object like
return Json(new {data = customerdetails}, JsonRequestBehavior.AllowGet);
or change
$scope.cust = d.data; To $scope.cust = d;
I want to update data from laravel controller to database,
I am able tto update data in model but I am not able to update data into database
here is my View or HTML coding
function editdata(data)
{
//alert(data);
$(function(){
$.ajax({
method : "GET",
url: "welcome",
data: {id: data},
success : function(response)
{
//debugger;
/*if(response==true)
alert("success");
else
alert("Failure");*/
var a=response;
//$('#fname').value(a.fname);
$('#firstName').val(a.fname);
$('#lastName').val(a.lname);
$('#qualification').val(a.qualification);
$('#emailAddress').val(a.email);
$('#contactmessage').val(a.desc);
var elem = document.getElementById("add");
elem.value="Update";
}
});
});
}
function disableData(data)
{
//alert(data);
//if (confirm('Are You Sure You Want To Delete Data ?')) {
$(function(){
$.ajax({
method : "GET",
url: "welcome/disable",
data: {id: data},
success : function(response)
{
//alert(response);
window.location.reload();
//debugger;
/*if(response==true)
alert("success");
else
alert("Failure");*/
//alert('Data is deleted Successfully!!!');
}
});
});
//} else {
//alert('Data is not deleted');
//}
}
function addUpdateData(data)
{
var btnvalue = document.getElementById("add").value;
//alert($('#firstName').val)
//alert(btnvalue);
if(btnvalue=="Add")
{
$(function(){
$.ajax({
method : "GET",
url: "welcome",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: dataToSend,
success : function(response)
{
alert("data sent successfully");
//debugger;
/*if(response==true)
alert("success");
else
alert("Failure");*/
}
});
});
}
else
{
$(function(){
$.ajax({
method : "GET",
url: "welcome",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: dataToSend ,
success : function(response)
{
alert("data sent successfully");
//debugger;
/*if(response==true)
alert("success");
else
alert("Failure");*/
}
});
});
}
}
/*function addData(data)
{
$function(){
$.ajax({
method : "post",
url: "welcome",
data: {id: data,}
})
}
}*/
</script>
</head>
<body>
<div class="container-fluid" style="background-color: #CCCCCC">
<h1>Temp Form</h1>
<form method="post" action="" role="form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="panel panel-default ">
<div class="container">
<div class="panel-body">
<div class="form-group">
<label for="firstName">First Name *</label>
<input name="fname" type="text" class="form-control" id="firstName" placeholder="Enter First Name" required>
</div>
<div class="form-group">
<label for="lastName">Last Name *</label>
<input name="lname" type="text" class="form-control" id="lastName" placeholder="Enter Last Name" required>
</div>
<div class="form-group">
<label for="qualification">Qualification *</label>
<input name="qualification" type="text" class="form-control" id="qualification" placeholder="BE, MCA, MBA Etc." required>
</div>
<div class="form-group">
<label for="emailAddress">Email address *</label>
<input name="email" type="email" class="form-control" id="emailAddress" placeholder="Enter Email" required>
</div>
<div class="form-group">
<label for="contactmessage">Message</label>
<textarea name="desc" type="text" class="form-control" id="contactmessage" placeholder="Message" rows="2"></textarea>
</div>
<input type="submit" id="add" class="btn btn-primary" onClick="addUpdateData(id)" value="Add"></button>
</div>
</div>
</div></form>
</div>
<div class="container">
<div class="container-fluid">
<h1>All Data</h1>
<div class="row">
<table class="table table-hover">
<thead>
<tr>
<th> First Name </th> <th> Last Name </th>
<th> Qualification </th> <th> E-mail </th> <th> Description </th>
</tr>
</thead>
<tbody>
#foreach ($forms as $form)
<tr>
<td> {{ $form->fname }} </td>
<td> {{ $form->lname }} </td>
<td> {{ $form->qualification }} </td>
<td> {{ $form->email }} </td>
<td> {{ $form->desc }} </td><br>
<td> <a id="{{ $form->id }}" onClick="editdata(id)" class="btn btn-info">
<span class="glyphicon glyphicon-edit"></span></a></td>
<td><a id="{{ $form->id }}" onClick="disableData(id)" class="btn btn-danger">
<span class="glyphicon glyphicon-trash"></span>
</a></td>
</td>
</tr>
#endforeach
</tbody>
</div>
</div>
</table>
</body>
</html>
Here is code for controller
<?php
namespace App\Http\Controllers;
use DB;
use App\Basicusers;
use Request;
use App\Http\Requests;
class FormController extends Controller
{
//$flag = "Add";
public function show()
{
//return 'FormController';
$forms = Basicusers::all()->where('flag',1);
//$name = ['Nix','Shiv'];
//return view('welcome',compact('name'));
return view('welcome',compact('forms'));
}
/*public function addNew(Request $req)
{
$bs = new Basicusers;
$bs->fname = $req->fname;
$bs->lname = $req->lname;
$bs->qualification = $req->qualification;
$bs->email = $req->email;
$bs->desc = $req->desc;
$bs->save();
return back();
//return "Success";
}*/
public function editdata()
{
//return "Editdata called";
//$data = Basicusers::find($id);
//$flag = "Update";
//return view('edit',compact('data')));
$id = $_GET['id'];
//$id = Request::get();
$data = Basicusers::find($id);
//return view('welcome',compact('id'));
return $data;
//return $id;
// $category = Input::get('productCategory');
//$id = Request::get('id');
//$data = Basicusers::find($id);
//return $data;
// 1exit;
//return $data;
/*htmlForm::open();
Form::textarea('fname','Nirav');
Form::close();
return back()*/;
//$form = Basicusers::find($id);
//return view('welcome',compact('form'));
}
public function disableData()
{
$id = $_GET['id'];
//$update = DB::table('basicusers')->where('id',$id)->update('flag','0' );
$alldata = Basicusers::find($id);
//$original = $alldata->flag;
$alldata->flag = 0;
$alldata->save();
//$alldata.update('flag',0);
//$alldata.save();
//$update->save();
return $alldata->flag;
//Basicusers::find($id)->delete();
//Basicusers::where('id',$id)->update('flag',0);
//return "success";
}
/*public function addUpdateData(Request $request)
{
/*$formupdate = Request::all();
$form = Basicusers::find($id);
$form->update($formupdate);
return redirect('/');*/
//if($flag=="Add")
//print_r("Data Will be Added");
// if($flag=="Update")
// print_r("Data Will be Updated");
//else
//print_r("Error");
//print_r($formupdate);
//$input = Input::all();
//return response()->json($input); //- See more at: http://yuluer.com/page/dehbedif-laravel-5-controller-wont-receive-data-from-ajax-form.shtml#sthash.gj2cIar7.dpuf
}*/
}
I am able to get data using following commands
$id = $_GET['id'];//id of data to be disabled
$alldata = Basicusers::find($id);//row for which data will be disabled
$alldata->flag = 0;//setting values
$alldata->save();//saving data
return $alldata->flag;//returning new value
However from the above code Data is not updated in database
How to update data in database please guide
after clicking on delete button, I just want to disable data(don't want to fetch that row)
I have column called flag where binary values 0 or 1 stored.
I am fetching only those records where the value of flag is 1
so on delete I want to make flag value for that record to 0
Perhaps you can try the alternative laravel update method $alldata->update(['flag' => 0]); and see if you have better luck with that...
I'm new to angular, currently having a problem with updating a table data on form submit. This is my view:
<div class="container-fluid">
<div class="row">
<div class="col-md-12" ng-controller="feeStatement">
<panel panel-class="panel-sky" heading="Add Fee Details">
<panel-controls>
<panel-control-collapse></panel-control-collapse>
</panel-controls>
<div id="alert" class="alert alert-danger hide">
<strong>Error</strong> Unable to save the course data.<br><br>
<ul>
<li id="error"></li>
</ul>
</div>
<form ng-submit="submit(credentials)" ng-controller="feeStatement" class="form-horizontal row-border">
<div class="form-group">
<label for="fieldname" class="col-md-3 control-label">Item Description</label>
<div class="col-md-6">
<textarea name="description" id="fieldabout" class="form-control autosize" rows="2" ng-model="credentials.description"></textarea>
</div>
</div>
<div class="form-group">
<label for="fieldname" class="col-md-3 control-label">Due Date</label>
<div class="col-md-6">
<datepicker ng-model="dt" min-date="minDate" show-weeks="true" class="datepicker"></datepicker>
</div>
</div>
<div class="form-group">
<label for="fieldname" class="col-md-3 control-label">Amount Payable</label>
<div class="col-md-6">
<input name="amount_payable"
type="number"
placeholder="Numbers only"
required
ng-model="credentials.amount_payable"
class="form-control">
</div>
</div>
<div class="form-group">
<label for="fieldname" class="col-md-3 control-label">Total Collected</label>
<div class="col-md-6">
<input name="total_collected"
type="number"
placeholder="Numbers only"
required
ng-model="credentials.total_collected"
class="form-control">
</div>
</div>
<div class="form-group">
<label for="fieldname" class="col-md-3 control-label"></label>
<div class="col-md-6">
<input type="submit" class="finish btn-success btn" value="Submit" />
</div>
</div>
</form>
</panel>
<panel panel-class="panel-sky" heading="Fee Details">
<panel-controls>
<panel-control-collapse></panel-control-collapse>
</panel-controls>
<p ng-hide="isValid(feedetails)" class="ng-hide">No fee statements for the student.</p>
<div ng-show="isValid(feedetails)" class="table-responsive">
<table class="table">
<thead>
<tr>
<th style="padding-right:100px">Item Description</th>
<th>Due Date</th>
<th>Amount Payable</th>
<th>Total Collected</th>
<th>Outstanding</th>
<th>Fine</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in feedetails">
<td align="left"><i>{{item.description}}</i></td>
<td align="left"><i>{{item.duedate}}</i></td>
<td align="left"><i>{{item.amount_payable}}</i></td>
<td align="left"><i>{{item.total_collected}}</i></td>
<td align="left"><i>{{item.outstanding}}</i></td>
<td align="left"><i>{{item.fine}}</i></td>
</tr>
</tbody>
<form ng-controller="feeStatement"><input type="submit" class="finish btn-success btn" ng-click="test()" value="Submit" /></form>
</table>
</div>
</panel>
</div>
</div>
</div> <!-- container-fluid -->
This is my controller function:
$scope.submit = function(credentials) {
var outstanding = ($scope.credentials.amount_payable - $scope.credentials.total_collected);
var base_url = $("meta[name='base_url']").attr('content');
$scope.student_id = ($routeParams.student_id || "");
var data = {
'user_id': $scope.student_id,
'description': $scope.credentials.description,
'duedate': $scope.dt,
'amount_payable': $scope.credentials.amount_payable,
'total_collected': $scope.credentials.total_collected,
'outstanding': outstanding
};
$http({
method: 'post',
url: base_url + '/student/postfees',
data: data
}).
success(function(data, status, headers, config) {
if(data['success']) {
$scope.feedetails.push(data);
} else {
}
}).
error(function(data, status, headers, config) {
$('#error').html('code: ' + status);
$('#alert').fadeIn(1000).removeClass('hide');
});
};
When I submit a form $scope.feedetails updates, but the table data in rows still the same. But if i click on button with test() function which is within a table tag, the data updates dynamically.I've went through simillar topics, but that didn't helped. I assume that the problem with a $scope, can somebody give me a direction please.
PS. I've tried to put data in a rootScope, but still the same result.
The reason why:
Actually the issue is that $scope doesn't exist in success and you can neither try to inject from the function because in the code is happening this:
promise.success = function(fn) {
assertArgFn(fn, 'fn');
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
in particular note fn(response.data, response.status, response.headers, config); it means that is going to pass to your function only those arguments and there is not $scope or $rootScope at all in there.
How to fix the problem:
One thing you can do is generate a function that has access to $scope and inject it in .success.
One possible implementation is :
$scope.submit = function(credentials) {
var outstanding = ($scope.credentials.amount_payable - $scope.credentials.total_collected);
var base_url = $("meta[name='base_url']").attr('content');
$scope.student_id = ($routeParams.student_id || "");
var data = {
'user_id': $scope.student_id,
'description': $scope.credentials.description,
'duedate': $scope.dt,
'amount_payable': $scope.credentials.amount_payable,
'total_collected': $scope.credentials.total_collected,
'outstanding': outstanding
};
var callback = function(data) {
$scope.feedetails.push(data);
};
$http({
method: 'post',
url: base_url + '/student/postfees',
data: data
})
.success(function(data, status, headers, config) {
if(data['success']) {
callback(data);
} else {
}
})
.error(function(data, status, headers, config) {
$('#error').html('code: ' + status);
$('#alert').fadeIn(1000).removeClass('hide');
});
};