I am trying to update data in the database using angular in Laravel 4 but the data is'nt get inserted, and a blank value is getting stored in to the database. Please find the bug and try to insert the passed value insteed of blank value.
JS File
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.updateFunction = function(updateId) {
$http.get("http://localhost/crud/public/registration_update_page/" + updateId).then(function successCallback(response) {
console.log('successCallback');
console.log(response);
alert("Row with id " + updateId + ", updated..!");
}, function errorCallback(response) {
console.log('errorCallback');
console.log(response);
});
};
});
.PHP File
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<h2>Registration</h2><br/>
<table border=1>
<tr><td>Name:</td><td><input type="text" ng-model="nam" name="nam"><br/></td></tr>
<tr><td>Email:</td><td><input type="email" ng-model="email" name="email"><br/></td></tr>
<tr><td>Password:</td><td><input type="password" ng-model="password" name="password"><br/></td></tr>
<tr><td>City:</td><td><input type="text" ng-model="city" name="city"><br/></td></tr>
<tr><td><button ng-click="insertFunc()" type="submit">Submit</button></td></tr>
</table>
</div>
</form>
<table style="width:100%" border=1>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
<th>City</th>
<th>Update</th>
<th>Delete</th>
</tr>
<tr ng-init='show = true' ng-repeat="x in query" ng-hide='!show'></div>
<!-- ng-hide will work when it is true in condition -->
<td>{{x.id}}</td>
<td><input type="text" value="{{x.name}}" name="edited_name"></td>
<td><input type="text" value="{{x.email}}" name="edited_email"></td>
<td><input type="text" value="{{x.password}}" name="edited_password"></td>
<td><input type="text" value="{{x.city}}" name="edited_city"></td><br/>
<td><input type="submit" ng-click="updateFunction(x.id);" value="Update"></td>
<td><button ng-click="deleteFunction(x.id);show = false">Delete</button></td>
<!-- !show==false means !false i.e., true -->
</tr><div>
</body>
</html>
Controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use DB;
use Session;
use Redirect;
class NewController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function registration_update_function(Request $request)
{
$updateId = $request->id;
$edited_name = $request->edited_name;
$edited_city = $request->edited_city;
$users1 = DB::table('angular_registration')->where('id', '=', $updateId)->update(['city' => $edited_city]);
}
}
Try with post method and following code and pass full x object / scope and x.id in this function updateFunction(x, x.id);
Angular Code
var req = {
method: 'POST',
url: 'http://localhost/crud/public/registration_update_page/',
data: { x: x, id = x.id }
}
$http(req).then(function(){
//Success
}, function(){
});
On server side PHP
print_r($_POST);
I solved this problem myself
This works for ANGULAR.JS with Laravel 4 to run insert,update,delete and select queries of the MySql DataBase.
VIEW
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<h2>Registration</h2><br/>
<table border=1>
<tr><td>Name:</td><td><input type="text" ng-model="nam" name="nam"><br/></td></tr>
<tr><td>Email:</td><td><input type="email" ng-model="email" name="email"><br/></td></tr>
<tr><td>Password:</td><td><input type="password" ng-model="password" name="password"><br/></td></tr>
<tr><td>City:</td><td><input type="text" ng-model="city" name="city"><br/></td></tr>
<tr><td><button ng-click="insertFunc()" type="submit">Submit</button></td></tr>
</table>
</div>
</form>
<table style="width:100%" border=1>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
<th>City</th>
<th>Update</th>
<th>Delete</th>
</tr>
<tr ng-init='show = true' ng-repeat="x in query" ng-hide='!show'></div>
<!-- ng-hide will work when it is true in condition -->
<td>{{x.id}}</td>
<td>{{x.name}}<input type="text" ng-model="edited_name"></td>
<td>{{x.email}}<input type="text" ng-model="edited_email"></td>
<td>{{x.password}}<input type="text" ng-model="edited_password"></td>
<td>{{x.city}}<input type="text" ng-model="edited_city"></td><br/>
<td><input type="submit" ng-click="updateFunction(x.id,edited_name,edited_email,edited_password,edited_city);" value="Update"></td>
<td><button ng-click="deleteFunction(x.id);show = false">Delete</button></td>
<!-- !show==false means !false i.e., true -->
</tr><div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http) {
$scope.deleteFunction = function(deleteId)
{
$http.get("http://localhost/crud/public/registration_delete_page/"+deleteId)
.then(function successCallback(response)
{
console.log('successCallback');
console.log(response);
alert("Row with id "+deleteId+", deleted..!");
},
function errorCallback(response)
{
console.log('errorCallback');
console.log(response);
});
};
$scope.updateFunction = function(updateId,edited_name,edited_email,edited_password,edited_city)
{
$http.get("http://localhost/crud/public/registration_update_page/"+updateId+"/"+edited_name+"/"+edited_email+"/"+edited_password+"/"+edited_city)
.then(function successCallback(response)
{
//$scope.edited_name = edited_name;
console.log('successCallback');
console.log(response);
alert("Row with id "+updateId+", updated..!");
},
function errorCallback(response)
{
console.log('errorCallback');
console.log(response);
});
};
$scope.insertFunc = function() {
$http({
method : 'POST',
url : 'http://localhost/crud/public/registration_data_page',
data : {nam:$scope.nam,email:$scope.email,password:$scope.password,city:$scope.city}
}).then(function successCallback(response) {
console.log('successCallback');
console.log(response);
}, function errorCallback(response) {
console.log('errorCallback');
console.log(response);
});
}
$http({method:'GET', url:'http://localhost/crud/public/registration_json_page'}).success(function(response){
$scope.query = response;
});
});
</script>
</body>
</html>
Controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use DB;
use Session;
use Redirect;
class NewController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function registration_data_function(Request $request)
{
echo $nam_value = $request->nam;
echo $email_value = $request->email;
echo $password_value = $request->password;
echo $city_value = $request->city;
$reg = DB::table('angular_registration')->insert(['name' => $nam_value, 'email' => $email_value, 'password'=>$password_value, 'city'=>$city_value]);
}
public function registration_json_function(Request $request)
{
$query = DB::select('select * from angular_registration');
return response($query);
}
public function registration_function(Request $request)
{
$query = DB::select('select * from angular_registration');
return view('registration');
}
public function registration_delete_function(Request $request)
{
$deleteId = $request->id;
return $users = DB::table('angular_registration')->where('id', '=', $deleteId)->delete();
}
public function registration_update_function(Request $request)
{
echo $updateId = $request->id;
echo $edited_name = $request->edited_name;
echo $edited_email = $request->edited_email;
echo $edited_password = $request->edited_password;
echo $edited_city = $request->edited_city;
$users1 = DB::table('angular_registration')->where('id', '=', $updateId)->update(['name' => $edited_name,'email' => $edited_email,'password' => $edited_password,'city' => $edited_city]);
}
}
ROUTE
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::auth();
Route::get('/registration', 'NewController#registration_function');
Route::post('/registration_data_page', 'NewController#registration_data_function');
Route::get('/registration_json_page', 'NewController#registration_json_function');
Route::get('registration_delete_page/{id}', 'NewController#registration_delete_function');
Route::get('registration_update_page/{id}/{edited_name}/{edited_email}/{edited_password}/{edited_city}', 'NewController#registration_update_function');
Related
I want to click on a link with id from database (on posts.html page) then view the full content of that post link in a display.html using AngularJS, MySQLi, and PHP. Please see the image below:
here is what I have managed to do so far:
Posts.html
<table class="table table-bordered" ng-controller="postController"
ng-init="show_data()">
<tr>
<th>Description</th>
</tr>
<tr ng-repeat="x in news">
<td>{{x.description}}</td>
</tr>
</table>
Here is my post controller: postController.js
"USE STRICT";
app.controller('postController', function ($scope, $http) {
$scope.show_data = function () {
$http.get("display.php")
.success(function (data) {
$scope.news = data;
});
}
});
And here is my display.php code:
<?php
require_once "config.php";
$output = array();
$query = "SELECT * FROM news";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$output[] = $row;
}
echo json_encode($output);
}
?>
My display.html is:
<div >
<div>{{id}}</div>
<div>{{title}}</div>
<div>{{article}}</div>
<div>{{tag}}</div>
<div>{{author}}</div>
</div>
How to display the results fetched from the database of the particular link on display.html?
This should do the job:
In your config:
app
.config(function ($routeProvider ...) {
$routeProvider
...
.when('/posts', {templateUrl: 'posts.html', controller: function($scope, $http) {
$scope.getPosts = function() {
$http.get('posts.php').then(function (response) {
$scope.posts = response.data;
});
};
}})
.when('/display/:id', {templateUrl: 'display.html', controller: function($scope, $routeParams, $http) {
$http.get('display.php', {id: $routeParams.id}).then(function (response) {
$scope.post = response.data;
});
}})
})
In posts.html:
<table class="table table-bordered" ng-controller="postController" ng-init="getPosts()">
<tr>
<th>Description</th>
</tr>
<tr ng-repeat="post in posts">
<td><a ng-href="display/{{post.id}}">{{post.description}}</a></td>
</tr>
</table>
In display.html:
<div ng-if="post">
...
<div>{{post.title}}</div>
...
</div>
In display.php:
$id = $_GET['id'];
// then retrieve post by this id and return as json item
I am self educating myself in angular js. For this i have created a project modelled after an actual project in my job
All get operation work fine but POST is giving me issue
My controller.js
var ngapp = angular.module('ngWebApp', ['angularUtils.directives.dirPagination']);
ngapp.controller('ngIndexController', function ($scope, ngDashboardService) {
$scope.exportData = function (selectedDataList) {
var getData = ngDashboardService.AddReportAudit(selectedDataList)
getData.then(function (result) {
alert(result.data);
}, function () {
alert('Error in getting records');
});
};
});
My service.js
angular.module('ngWebApp').service("ngDashboardService", function ($http) {
this.AddReportAudit = function (dataList) {
var response = $http({
method: "POST",
url: "/Home/AddReportAudit",
data: {
'dataList': JSON.stringify(dataList)
}
});
return response;
};
});
My code of JasonResult in HomeController
public JsonResult AddReportAudit(List<ADTOWebSMARTT_SSOData> dataList)
{
if (dataList != null)
{
using (HRMSystemEntities contextObj = new HRMSystemEntities())
{
var itemList = dataList.Where(x => x.IsChecked == true).ToList();
itemList.ForEach(a => a.DateChecked = DateTime.Now);
contextObj.SaveChanges();
return Json(new { success = true });
}
}
else
{
return Json(new { success = false });
}
}
The problem occurs here
public JsonResult AddReportAudit(List dataList)
For some reason the dataList on reaching AddReportAudit become empty i.e. list has zero element. dataList has 30 records in controller.js and service.js.
I am not sure why that is happening. is there a parsing that I am missing when json data comes from angular to c#
You are actually sending an Object, so the data that reaches your public JsonResult AddReportAudit(....isAnObject), but you are expecting it to be a list. Just change your controller code to the snippet below, it should work.
angular.module('ngWebApp').service("ngDashboardService",
function($http) {
this.AddReportAudit = function (dataList) {
var response = $http({
method: "POST",
url: "/Home/AddReportAudit",
data:JSON.stringify(dataList)
});
return response;
};
});
Solution for angular 1. Place your web service url and change the json data format as per your need. It works.
<!DOCTYPE html>
<html>
<head>
<title>Angular HTTP service</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<table>
<tr>
<th>S No</th>
<th>Source Name</th>
</tr>
<tr ng-repeat="res in result">
<td>{{$index + 1}}</td>
<td>{{res.source_name}}</td>
</tr>
</table>
<script type="text/javascript">
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http){
$http.get("http://127.0.0.1:4000/all_source").then(function(res){
//console.log(res.data.result);
//console.log(res);
$scope.result = res.data.result;
});
});
</script>
</body>
</html>
Actually I am trying to update the page automatic when the new data is inserted. means the displaying of new enered data on the view page. Can some one help ?
When I am inserting the data, I have to reload the page in order to view the new inserted data which is bulky and laborious. I want to rid of this work.
VIEW
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="//code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<div id="upd_cnt" class="container">
<table border=1>
<td>
<h2>Rectangle dimension</h2><br/>
<table border=1>
<tr><td>Length:</td><td><input type="text" ng-model="lngth"><br/></td></tr>
<tr><td>Breadth:</td><td><input type="text" ng-model="brdth"><br/></td></tr>
<tr><td><input ng-click="store.reload();insertFunc(lngth,brdth)" type="submit" value="Submit"></td></tr>
</table>
<svg width="400" height="200" version="1.1">
<rect fill="red" x="20" y="20" width="{{brdtha}}" height="{{lngtha}}" />
<rect fill="blue" x="50" y="50" width="200" height="75" />
</svg>
</td>
<td>
<table border=1>
<tr>
<th>ID</th>
<th>Length</th>
<th>Breadth</th>
<th>Draw Rectangle</th>
</tr>
<tr ng-repeat="x in select_rectangle">
<td>{{x.id}}</td>
<td>{{x.length}}</td>
<td>{{x.breadth}}</td>
<td><input ng-click='show = true' type="submit" value="Draw" ng-model="myVar"></td>
<td><svg width="400" height="200" version="1.1">
<rect fill="red" x="20" y="20" width="{{x.breadth}}" height="{{x.length}}" ng-init='show = false' ng-show='show'/></td>
</svg>
</tr>
</table>
</td>
</table>
</div>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http) {
//$scope.insertFunc = function(lngth, brdth) {
//$http.get("http://localhost/crud/public/insert_rectangle_dimension_page/"+lngth+"/"+brdth)
$scope.insertFunc = $timeout(function(lngth,brdth) {
$scope.lngtha = lngth;
$scope.brdtha = brdth;
$http({
method : 'POST',
url : 'http://localhost/crud/public/insert_rectangle_dimension_page',
data : {lngth:$scope.lngth, brdth:$scope.brdth}
})
.then(function successCallback(response)
{
console.log('successCallback');
console.log(response);
},
function errorCallback(response)
{
console.log('errorCallback');
console.log(response);
});
}
$http({method:'GET', url:'http://localhost/crud/public/rectangle_json_page'}).success(function(response){
$scope.select_rectangle = response;
});
});
</script>
</body>
</html>
Controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use DB;
use Session;
use Redirect;
class NewController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function rectangle_function(Request $request)
{
$select_rectangle = DB::select('select * from rectangle');
return view('rectangle');
}
public function rectangle_json_function(Request $request)
{
$select_rectangle = DB::select('select * from rectangle order by id desc');
return response($select_rectangle);
}
public function insert_rectangle_dimension_function(Request $request)
{
echo $rec_height = $request->lngth;
echo $rec_width = $request->brdth;
$rect = DB::table('rectangle')->insert(['length' => $rec_height, 'breadth' => $rec_width]);
}
}
ROUTE
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::auth();
Route::post('/insert_rectangle_dimension_page', 'NewController#insert_rectangle_dimension_function');
Route::get('/rectangle', 'NewController#rectangle_function');
Route::get('/rectangle_json_page', 'NewController#rectangle_json_function');
You should call a function that gets your data again, after an insert. Apoloies for any errors in the code, I'm not used to injecting scope in angular controllers.
For example:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http) {
//$scope.insertFunc = function(lngth, brdth) {
//$http.get("http://localhost/crud/public/insert_rectangle_dimension_page/"+lngth+"/"+brdth)
$scope.insertFunc = $timeout(function(lngth,brdth) {
$scope.lngtha = lngth;
$scope.brdtha = brdth;
$http({
method : 'POST',
url : 'http://localhost/crud/public/insert_rectangle_dimension_page',
data : {lngth:$scope.lngth, brdth:$scope.brdth}
})
.then(function successCallback(response)
{
console.log('successCallback');
console.log(response);
//Function call to re-load data
$scope.loadData();
},
function errorCallback(response)
{
console.log('errorCallback');
console.log(response);
});
}
$scope.loadData = function(){
$http({method:'GET', url:'http://localhost/crud/public/rectangle_json_page'}).success(function(response){
$scope.select_rectangle = response;
});
}//end scope.loadData
});
Here is my RestController Class
#RestController
#RequestMapping(value="/user")
public class Test {
#RequestMapping(value="/{userEmailId}",method=RequestMethod.GET)
public ModelAndView getUser(#PathVariable("userEmailId") String userEmailId){
//something goes here and get User class object
ModelAndView mav=new ModelAndView("showuser");
mav.addObject("user", user);//user is User class object
return mav;
}
}
I want to display this user object in showuser.jsp using Angular JS How can I do that?
Below is sample example assuming your user object have firstname and lastname:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
</head>
<div ng-app="myApp" ng-controller="userController">
<form action="demo_form.html">
First name: <input type="text" name="fname" ng-model="fname"><br>
Last name: <input type="text" name="lname" ng-model="lname"><br>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('userController', function($scope, $http) {
$http({
method : "GET",
url : "/user/xyz#a.com"
}).then(function mySucces(response) {
$scope.fname = response.fname;
$scope.lname = response.lname;
}, function myError(response) {
//handling error
});
});
</script>
I built a sample MVC application in which I tried to implement functionality to insert a record using angular js.
Here is the index cshtml page.
#{
ViewBag.Title = "Add User";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section adduser
{
#*Index.html*#
<div class="container-fluid" ng-app='MyData' ng-controller='DataController'>
<table class="table table-striped table-bordered table-responsive">
<tr>
<td>
<label class="text-primary">User Name:</label>
</td>
<td>
<input type="text" id="txtUserName" class="text-primary" required="required" ng-model="newUser" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" id="btnSubmit" class="btn btn-success" ng-click="AddUser()" />
</td>
</tr>
</table>
</div>
}
Here is the Model js code
var myData = angular.module('MyData', []);
Here is the controller JS code
myData.controller("DataController", function($scope) {
$scope.newUser = "";
$scope.addUser = function() {
$http.post("/Home/AddUser/", { newUser: $scope.newUser }).success(function (result) {
alert(result.success);
}).error(function(data) {
console.log(data);
});
};
});
Here is the post method inside controller which i am calling through angular js
[HttpPost]
public JsonResult AddUser(string name)
{
var db = new SchedulerEntities();
db.Users.Add(new User {Name = name});
db.SaveChanges();
return null;
}
I am adding an entry into DB from controller method but nothing is happening...
I think you need to declare $http in the function:
myData.controller("DataController", function($scope, $http) {
$scope.newUser = "";
$scope.addUser = function() {
$http.post("/Home/AddUser/", { newUser: $scope.newUser })
.success(function (result) {
alert(result.success);
}).error(function(data) {
console.log(data);
});
};
});