AngularJs Form Model Not Submitting via Ajax - angularjs

I can't get the values of the form passed via ajax. I used angularJs model. Please help. My codes below.
for hmtl:
<form role="form" ng-submit="submit_new_rpo(new_rpo)">
<div class="box-body">
<table class="table table-striped">
<tbody>
<tr>
<td>RPO# :
<input type="text"
class="form-control" ng-model="new_rpo.po_number" required="required">
</td>
</tr>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Ajax:
$scope.submit_new_rpo=function(rpo)
{
$http({
method : "POST",
url : burl + "po/insert_po_manual"
,data:{"rpo":rpo}
}).then(function(response){
alert(response.data);
}, function myError(response) {
$scope.err_content=response.data;
});
}
php
public function insert_po_manual()
{
$params = json_decode(file_get_contents('php://input'),true);
if(!isset($params))
{
show_404();
}
echo $params['rpo']['po_number'];
}
I am getting empty array in my server. I used the code in other modules and its working.But this time I don't know why Im getting empty values.

Related

Updating data from controller to database in laravel

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 can't send the correct Id to my modify method

I have problem in my code when I try to modify a row from a table, I work with AngularJS as client and ASP.Net as the rest API, this is my code for the API modify:
[Route("api/Students/modifier/{id}")]
public async Task<HttpResponseMessage> PUT(int id, Student value)
{
try
{
_StudentService.Update(value);
await _unitOfWorkAsync.SaveChangesAsync();
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
This is my HTML code:
<table class="table table-responsive table-hover" ng-controller="etudmodifCtrl">
<thead>
</thead>
<tbody >
<tr ng-repeat="store in currentPageStores>
<td align="center">{{store.LastName}}</td>
<td align="center">{{store.FirstName}}</td>
<td align="center">{{store.Email}}</td>
<td align="center" ng-controller="etuddeleteCtrl">
<div id="myModal" class="modal fade" role="dialog" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">....</div>
<div class="modal-body">
<div class="form-group">
<label>LastName</label>
<div class="col-sm-10">
<input type="text" class="form-control" ng-model="nomet">
</div>
</div>
<div class="form-group">
<label>FirstName</label>
<div class="col-sm-10">
<input type="text" class="form-control" ng-model="prenomet">
</div>
</div>
<div class="form-group">
<label>Email</label>
<div class="col-sm-10">
<input type="text" class="form-control" ng-model="email">
</div>
</div>
</div>
<div class="modal-footer">
<button ng-click="modifetud(store.$id)">OK</button>
</div>
</div>
</div>
//this button opens the modal in which I will modify the data
<button ng-click="open(store.$id)" data-target="#myModal">Modify</button>
</td>
</tr></tbody></table>
The controller:
.controller("etudmodifCtrl", ["$scope", "$http", function ($scope, $http) {
//I get the data via these method and a correct Id of the selected row
$scope.open = function ($id) {$http(
{method: 'GET', url:'http://localhost:50001/api/Students/'+$id})
.success(......)
.error
}
$scope.modifetud = function ($id) {$http(
{method: 'PUT',url:'http://localhost:50001/api/Students/modifier/'+$id,data:'{"FirstName":"'+$scope.prenomet+'","LastName":"'+$scope.nomet+'","Email"'+$scope.email+'"}'}
)}
})
The problem is that the delete works fine,and for the etudmodifCtrl controller I get the correct Id selected from the table and I have send it to the modal correctly. My problem is when I click on the button "OK" of the modal, it always shows the id=1 and the old data (data before modification).
For example I chose the row with the id 12 then I click on the button "OK" in the modal, this is what I get when debugging:
Request details from browser

angularJS update table model on form submit

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

Website validation in AngularJs

I have a field that accepts a URL. How do I validate this URL in angularjs.
<div class="controls">
<input type="text" ng-model="controller.data.PropertyWebsite"/>
</div>
Any ideas and suggestions are appreciated !!!!
Add a html input[url] to a form and mark it as required, then use angular to check if the form is valid or not:
html:
<form name="form">
<tr>
<td><input type="url" name="url" required></td>
</tr>
<tr>
<td><button type="submit" ng-click="SubmitForm('form')">submit</button> </td>
</tr>
</form>
controller:
$scope.submitForm = function () {
if (this.form.$invalid)
//not valid
} else {
//valid
}
}
More information about url input:
https://docs.angularjs.org/api/ng/input/input%5Burl%5D
You can use ng-pattern to validate against a RegEx. https://docs.angularjs.org/api/ng/directive/input

Backbonejs: get clicked model from collection

define(['jquery', 'underscore', 'backbone', 'text!views/manageUsers.tpl', 'common'], function($, _, Backbone, tmpl_manageUsersView, ajax) {
/*
* Module list
*
* tmpl_page1View templates/tmpl_page1View.html
*/
var manageUsersView = Backbone.View.extend({
// Setting the view's template property using the Underscore template method
template: _.template(tmpl_manageUsersView),
// View constructor
initialize: function() {
self = this;
},
// View Event Handlers
events: {
},
// Renders the view's template to the UI
render: function() {
this.$el.html(this.template({data: this.templateData}));
user=Backbone.Model.extend({
defaults:{
name:"",
password:"",
isAdmin:false
},
});
users=Backbone.Collection.extend({
model:user,
url:"auth"
});
usersCollection=new users();
usersCollection.fetch({
error:function(response,xhr){
console.log(response);
},
success:function(response){
count=1;
_.each(data,function(d){
if(count%2==0)
$("#users>tbody").append("<tr class='odd'><td>"+count+"</td><td>"+d.username+"</td><td><a href='#' class='edit-iocn' id='edit_"+d.username+"' ></a><a class='ancrul delete-icon' id='delete_"+d.username+"'></a></td>");
else
$("#users>tbody").append("<tr class='even'><td>"+count+"</td><td>"+d.username+"</td><td><a href='#' class='edit-iocn' id='edit_"+d.username+"'></a><a class='ancrul delete-icon' id='delete_"+d.username+"'></a></td>");
count++;
});
/*--*/
var oTable = $('#users').dataTable({
"sDom": '<"bottom"<i>rtp<"clear">',
//"sDom":'<"top"ip>rt<"bottom"ip<"clear">',
"sPaginationType": "full_numbers",
"bLengthChange": true,
"bPaginate": true,
"bInfo": true,
//"bAutoWidth": true,
"iDisplayLength":5,
"oLanguage": {
"sInfo": "",
"sInfoEmpty": ""
},
});
}
});
});
return manageUsersView;
});
Above is my code for getting data from url.
Following manageUsers.tpl file.
<div class="content">
<p> </p>
<h3></h3>
<div class="admin-login-area ui-corner-all">
<p class="validateTips">All form fields are required.</p>
<form id="addUserForm">
<fieldset>
<label for="name" class="login-label">User Name</label>
<input type="text" name="u-name" id="u-name" class="text ui-widget-content ui-corner-all">
<label for="name" class="login-label">Password</label>
<input type="password" name="p-name" id="p-name" class="text ui-widget-content ui-corner-all">
<label for="email" class="login-label">Retype Password</label>
<input type="password" class="text ui-widget-content ui-corner-all" id="c-name" name="c-name">
<input type="checkbox" id="isAdmin" />
<label>Is Admin</label>
<label class="login-label"></label>
<br/>
<input type="button" name="submit" id="submit" value="Submit" class="submit-btn">
<input type="button" name="submit" id="reset" value="Reset" class="submit-btn">
<input type="button" name="submit" id="cancel" value="Cancel" class="submit-btn">
<label class="login-label"></label>
</fieldset>
</form>
<!-- end admin login --></div>
<div class="table" >
<table width="100%" cellspacing="0" cellpadding="0" border="0" id="users">
<thead>
<th>Sr No</th>
<th>users</th>
<th>Actions</th>
</thead>
<tfoot style="display: table-header-group;">
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
</div>
and on fetching data successfully i have filled table with collectios's data and on click of an item in table i want to retrive whole model.I have form and table in same tpl file
How to do that using backbonejs and underscore js?
First, add this event to your view :
events : {
'click .edit-iocn' : 'edit', // in your code you typed `iocn` instead of `icon`
'click .delete-icon' : 'delete'
}
Than change the ids to id='"+d.username+"' without the edit_ and delete_
And last the edit and delete methods :
edit: function(event) {
var username = event.currentTarget.id;
var user = usersCollection.where({name: username})[0];
...
}
delete: function(event) {
var username = event.currentTarget.id;
var user = usersCollection.where({name: username})[0];
...
}

Resources