SelectBox not updating data while editing in angularjs using php - javascript

I am getting my data using json array via php now on edit operation when I got the data in select box on changing different values data is not updating .Any help would be appreciated.
$scope.rec = [];
$scope.update = function(rec){
var id = $scope.id;
$scope.upload = $upload.upload({
//url: 'api/manage_features/update/'+id, //upload.php script, node.js route, or servlet url
url: 'api/AdminArea/users/update/'+id,
method: 'POST',
headers: {'header-key': '83c238df1650bccb2d1aa4495723c63f07672ee8'},
withCredentials: true,
data:rec , //{data:rec},
//data: {name:$scope.name,price:$scope.price},
}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status, headers, config) {
toaster.pop('success', 'Edit', 'Record Updated successfully.');
setTimeout(function(){ $state.go('app.manage_users'); }, 3000);
$scope.$root.$broadcast("myDocEventReload", {});
})
}
<div class="form-group">
<label class="col-lg-2 control-label">Role:</label>
<div class="col-lg-5">
<div ng-show="addForm.$submitted || addForm.Name.$touched">
<div ng-show="addForm.Name.$error.required" style="color:red;">Field required!.</div>
</div>
<select class="form-control input-sm" ng-model="rec.roles" name="Role">
<option ng-repeat="roles in user " ng-selected="{{rec.roles==user.Role}}" value="{{roles.Role}}" >{{roles.Role}}</option>
</select>
</div>
</div>

Related

In ASP.NET Razor Page Jquery Ajax Function not Working

I have a two onchange function for a page called create delivery request. One is when the dropdownlist of receiver changes, then it should show the phone number & address of receiver selected. Another one is when the dropdownlist of delivery item changes, then it should set the max attribute for the quantity.
The url of both these are linked to the customized OnGet method in razor page.
However, usually the above Onget method is hit but the below one is not. And the above OnGet method can't get the dryfood with the passed ID as well, it is null inside. And the two jQuery ajax function doesn't work at all. I'm totally a beginner. Hope that there is someone who can help me. Thanks in advance.
In create.cshtml:
<div class="mb-3">
Receiver Name
<select id="receiver" asp-for="Delivery.ReceiverID" asp-items="Model.ReceiverList" class="form-control">
<option>--Select the Receiever--</option>
</select>
</div>
<div class="mb-3">
Receiver Phone
<span id="receiverphone" class="form-control">----</span>
</div>
<div class="mb-3">
Receiver Address
<div id="receiveradrs1" class="form-control">----</div>
<div id="receiveradrs2" class="form-control">----</div>
</div>
<div class="mb-3">
Delivery Item
<select id="deliveryitem" asp-for="DeliveryItem.DryFoodID" asp-items="Model.DeliveryItemList" class="form-control">
<option>--Select Delivery Item--</option>
</select>
</div>
<div class="mb-3">
Quantity
<input id="quantity" asp-for="DeliveryItem.Quantity" min="1" class="form-control" />
</div>
In create.csthml.cs, two customized OnGet method here:
public async Task<IActionResult> OnGetSetMaxQuantity(int id)
{
List<DryFoodDonation> dfdlist = await _db.DryFoodDonation.ToListAsync();
var dryfood = dfdlist.Where(d => d.Id == id).FirstOrDefault();
Debug.WriteLine(dryfood.DryFoodName + " " + dryfood.DryFoodRemainQuantity);
return new JsonResult(dryfood.DryFoodRemainQuantity);
}
public async Task<IActionResult> OnGetGetPhoneAdrs(int id)
{
List<User> receiverlist = await _db.User.Where(u => u.UserType.TypeID == 3).ToListAsync();
var selectreceiver = receiverlist.Where(d => d.UserID == id).FirstOrDefault();
Debug.WriteLine(selectreceiver.UserName + " " + selectreceiver.UserPhone);
return new JsonResult(selectreceiver);
}
The jQuery AJAX function in a JavaScript file:
$(document).ready(function () {
$("#receiver").change(function () {
alert('Yes receiver here changed.');
var item = $(this).val();
$.ajax({
type: 'GET',
url: 'Create/?handler=GetPhoneAdrs',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
'id': item
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$('#receiverphone').html(data.UserPhone);
$('#receiveradrs1').html(data.UserAdrs1);
$('#receiveradrs2').html(data.UserAdrs2);
}
});
});
$("#deliveryitem").change(function () {
alert('Yes item here changed.');
var item = $(this).val();
$.ajax({
type: 'GET',
url: 'Create/?handler=SetMaxQuantity',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
"id": item
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$("#quantity").attr({
"min": 1,
"max": data
});
}
});
});
});
Please help me with this. I can't solve this problem for a few weeks. Thank you!
// cshtml.cs
const sendMe = async function (someData) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/ControllerName/MethodNameInController',
data: { someData: someData },
success: function (response) {
if (response != null && response.statusCode == 200) {
..
} else {
..
}
}
});
}
//Controller
[HttpPost("MethodNameInController")]
public IActionResult MethodNameInController([FromForm] string someData) {
..
}

Django getlist getting null

Hello guys im currently learning on how to send data from HTML to Django backend using Ajax.
I have this HTML
<div class="form-row">
<input type="checkbox" name="car-checkbox[]" value="Audi" id="chck1">
<input type="checkbox" name="car-checkbox[]" value="BMW" id="chck2">
<input type="checkbox" name="car-checkbox[]" value="Lambo" id="chck2">
<input id="submit-car" type="button" value="Submit">
</div>
and then to send the data i use this code (Ajax)
$('#submit-car').click(function () {
const data = {user_id: user_id}
$.ajax({
type: 'POST',
url: '/submit-car/',
data: data,
beforeSend: function (request) {
request.setRequestHeader("X-CSRFToken", csrftoken);
},
success: function (data) {
$('#submit-form-field').prop('disabled', true);
location.reload();
alert("Submit OK!");
}
});
});
and then on the Django side i try to get the checked checkbox
def insert_car_to_db(self, request):
cars = request.POST.getlist('car-checkbox[]')
print(cars)
Weirdly enough when i try to get the checked data, i keep getting [] value,
where did i miss ? am i misunderstand something?
P.S
i followed this post
How to get array of values from checkbox form Django
$('#submit-car').click(function () {
const car_checkbox = [];
const user_id = "Some test UserId";
const csrftoken = "Provided CSRF TOKEN";
$("input[type=checkbox]:checked").each(function(){
car_checkbox.push($(this).val());
}); //STore the checkbox result in an array
const data = {"user_id": user_id, "car-checkbox": car_checkbox}
console.log(data);
$.ajax({
type: 'POST',
url: '/submit-car/',
data: data,
beforeSend: function (request) {
request.setRequestHeader("X-CSRFToken", csrftoken);
},
success: function (data) {
$('#submit-form-field').prop('disabled', true);
location.reload();
alert("Submit OK!");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-row">
<input type="checkbox" name="car-checkbox" value="Audi" id="chck1">
<input type="checkbox" name="car-checkbox" value="BMW" id="chck2">
<input type="checkbox" name="car-checkbox" value="Lambo" id="chck2">
<input id="submit-car" type="button" value="Submit">
</div>
So where you are sending the checkbox array value to backend /submit-car/ ?
what is user_id in your click evennt?
As you are using jquery so
$('#submit-car').click(function () {
const car_checkbox = [];
$("input[type=checkbox]:checked").each(function(){
car_checkbox.push($(this).val());
}); //STore the checkbox result in an array
const data = {"user_id": user_id, "car-checkbox": car_checkbox}
$.ajax({
type: 'POST',
url: '/submit-car/',
data: data,
beforeSend: function (request) {
request.setRequestHeader("X-CSRFToken", csrftoken);
},
success: function (data) {
$('#submit-form-field').prop('disabled', true);
location.reload();
alert("Submit OK!");
}
});
});

How to send empty string in routeparams in angular Js?

Hi I have a form in which I am sending a searched term and category id . It works fine as I am sending both things but if a user does not enter any thing only 'category id' goes, and in back end if searched term is empty all results are display to user.
But if I send an empty string in route params I redirect to myindex page. This is my app.js code.
when('/subcategory/:subcatId/:search', {
templateUrl: 'partials/subcategory.html',
controller: 'SubCategoriesController'
}).
My form
<form name="searchCategoryForm">
<div class="col-md-9 col-xs-10 col-sm-10">
<input class="form-control" placeholder="Find your item here...." ng-model="search" type="text" style="color:#09669c;">
</div>
<div class="col-md-2 col-xs-2 col-sm-2">
<a class="btn btn-primary" role="button" href='#/subcategory/{{cats[clicked_category].id}}/{{search}}'> Search</a>
</div>
</form>
My controller.js
$scope.search_term = $routeParams.search;
$scope.category_id = $routeParams.subcatId;
/* Search category form */
$scope.search_category = function () {
$http({
method: 'GET',
url: 'abc',
params: {"name": $scope.search_term, "category_id": $scope.category_id},
headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': $rootScope.keyword_auth_token}
})
.success(function (data) {
$scope.search_category_result = data.items;
console.log($scope.search_category_result);
})
.error(function (data) {
console.log(data);
});
};
/* Search category form ends here*/
if ($scope.search_term && $scope.category_id)
{
$scope.search_category();
}
I believe you should mark your search terms as optional by suffixing it with a question mark (?):
when('/subcategory/:subcatId/:search?', {
templateUrl: 'partials/subcategory.html',
controller: 'SubCategoriesController'
}).
See this answer for more info: Can angularjs routes have optional parameter values?

multiple cascading dropdown with Angular & MVC

Firstly apologies that post looks a bit long winded (it is just repeated code, so looks longer than it is). I'm trying to implement a multiple level cascading dropdown - It works fine for the initial and first level (COLUMN1 & COLUMN2) but not for COLUMN3.
Here is the controller:
public JsonResult GetCol1()
{
using (EntityName db = new EntityName())
{
var ret = db.TABLE_NAME.Select(x => new { x.COLUMN1 }).Distinct().ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}
[HttpPost]
public JsonResult GetCol2(string col1)
{
using (EntityName db = new EntityName())
{
var ret = db.TABLE_NAME.Where(x => x.COLUMN1 == col1).Select(x => new { x.COLUMN2 }).Distinct().ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}
[HttpPost]
public JsonResult GetCol3(string col1, string col2)
{
using (EntityName db = new EntityName())
{
var ret = db.TABLE_NAME.Where(x => x.COLUMN1 == col1).Where(x => x.COLUMN2 == col2).Select(x => new { x.COLUMN3 }).Distinct().ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}
Here is the JS:
app.controller('DropdownPopulation', function ($scope, $http) {
//$http service for Getting Column1
$http({
method: 'GET',
url: '/Data/GetCol1'
})
.success(function (data) {
$scope.Col1Data = data;
});
//$http service for getting Column2
$scope.GetCol2 = function () {
$http({
method: 'POST',
url: '/Data/GetCol2',
data: JSON.stringify({ COLUMN1: $scope.col1 })
}).
success(function (data) {
$scope.Col2Data = data;
});
};
//$http service for getting Column3
$scope.GetCol3 = function () {
$http({
method: 'POST',
url: '/Data/GetCol3',
data: JSON.stringify({ COLUMN1: $scope.col1, COLUMN2: $scope.col2 })
}).
success(function (data) {
$scope.Col3Data = data;
});
};
};
Finally here is the html / angular:
<!-- Column 1 -->
<div ng-controller="DropdownPopulation">
<div class="form-group">
<label class="control-label col-sm-2" for="Column1">Column1</label>
<div class="col-sm-10">
<select class="form-control" name="Column1"
data-ng-model="col1" id="Column1"
data-ng-options="c.COLUMN1 as c.COLUMN1 for c in Col1Data "
data-ng-change="GetCol2()">
<option value="" disabled selected>Select Col 1</option>
</select>
</div>
</div>
<!-- Column 2 -->
<div class="form-group">
<label class="control-label col-sm-2" for="Column2">Column2</label>
<div class="col-sm-10">
<select class="form-control" name="Column2"
data-ng-model="col2" id="Column2"
data-ng-options="c.COLUMN2 as c.COLUMN2 for c in Col2Data "
data-ng-change="GetCol3()"
data-ng-disabled="!Col1Data" >
<option value="" disabled selected>Select Col 2</option>
</select>
</div>
</div>
<!-- Column 3 -->
<div class="form-group">
<label class="control-label col-sm-2" for="Column3">Column3</label>
<div class="col-sm-10">
<select class="form-control" name="Column3"
data-ng-model="col3" id="Column3"
data-ng-options="c.COLUMN3 as c.COLUMN3 for c in Col3Data"
data-ng-disabled="!Col2Data" >
<option value="" disabled selected>Select Col 3</option>
</select>
</div>
</div>
</div>
Col3Data is actually returning empty when there is data in the database.
If you know why Col3Data is not returning back anything then your help would be most appreciated.
Many thanks
Shaheen
Okay i found out what the problem was. When doing the following:
data-ng-options="c.COLUMN1 as c.COLUMN1 for c in Col1Data
I was using 'values' for the first part rather than a 'key', so this was not returning data back.
changing to the following worked:
data-ng-options="c.COLUMN1_KEY as c.COLUMN1 for c in Col1Data
Viplock, thanks for your help as I found:
var dataToSend={ COLUMN1: $scope.col1, COLUMN2: $scope.col2 };
very helpful.
Regards,
Shaheen K
If there will be some issue with digest cycle not worked , you can try using $scope.$apply() like
Update For sending data
$scope.GetCol3 = function () {
var dataToSend={ COLUMN1: $scope.col1, COLUMN2: $scope.col2 };
$http({
method: 'POST',
url: '/Data/GetCol3',
data: dataToSend
}).
success(function (data) {
$scope.Col3Data = data;
$scope.$apply();
});
};

Getting issue in select drop down using Angular.js and PHP

I have one issue in my drop down list using Angular.js.Let me to explain the code first.
<div class="input-group bmargindiv1 col-md-12">
<span class="input-group-addon ndrftextwidth text-right" style="width:180px">Lecture Plan :</span>
<!--<input type="text" name="topic" class="form-control" ng-model="plan" id="plan" placeholder="Add Plan No" ng-keypress="clearField('plan');"/>-->
<select class="form-control" id="plan" ng-model="plan" ng-options="sec.name for sec in listPlanData track by sec.value " ng-change="clearField('plan');" > </select>
</div>
the following is my controller file code.
$scope.listPlanData=[{
name:'Select Lecture Plan',
value:'0'
}
];
$scope.plan=$scope.listPlanData[0];
$http({
method:'GET',
url:"php/userplan/getPlanName.php",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
angular.forEach(response.data, function(obj){
var Session={'name':obj.plan_name , 'value':obj.lp_id};
$scope.listPlanData.push(Session);
});
},function errorCallback(response) {
});
});
The following function is after user clicked on edit button.
$scope.getLecturePlan=function(plan_name){
//console.log('plan name',plan_name,$scope.plan);
$scope.listPlanData=null;
$scope.listPlanData=[{
name:'Select Lecture Plan',
value:'0'}];
$scope.plan=$scope.listPlanData[0];
$http({
method:'GET',
url:"php/userplan/getPlanName.php",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
// console.log('plan ',response);
angular.forEach(response.data, function(obj){
var Session={'name':obj.plan_name , 'value':obj.lp_id};
$scope.listPlanData.push(Session);
if(obj.plan_name==plan_name){
$scope.plan.value=obj.lp_id;
}
});
},function errorCallback(response) {
});
}
the parameter plan_name is taking the plan name from DB.
The following function is my update function.
if($scope.buttonName=="Update"){
console.log("aaaaaaa",$scope.plan.name);
if($scope.date==null){
alert('Please select date');
}else if($scope.plan.value==null || $scope.plan.value=='0' || $scope.plan.name=="Select Lecture Plan"){
alert('Please add Lecture plan');
}else if($scope.topic==null){
alert('Please add topic');
}else{
var dataString = "unit_plan_id="+temp_unit_id+"&plan_id="+id+"&date="+$scope.date+"&lession_plan="+$scope.plan.name+"&topic="+$scope.topic;
//alert("::"+dataString);
$.ajax({
type: "POST",url: "php/userplan/updatePlanData.php" ,data: dataString,cache: false,
success: function(html)
{
var dobj=jQuery.parseJSON(html);
//alert(dobj.result);
if(dobj.result == 0)
{
alert(dobj.error);
}
else
{
var updatedata={'unit_id':temp_unit_id};
$scope.viewPlanData=null;
$scope.viewPlanData=[];
$http({
method:'POST',
url:"php/userplan/readPlanData.php",
data:updatedata,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
console.log('res',response.data);
$scope.viewPlanData=response.data;
//document.getElementById("unit_list").style.display = "none";
//document.getElementById("plan_list").style.display = "block";
},function errorCallback(response) {
});
$scope.date = null;
$scope.plan = null;
$scope.topic = null;
$scope.clearPlanData();
alert("Plan updated successfully...");
}
}
});
In the above drop down list i am binding the dynamically from DB.Now i have one edit case in this case all selected data are set in this drop down for the further update.Suppose when user clicked on edit button and LP1 data set in this drop down.if user selected default namei.e-Select Lecture Plan and clicked for update it should display the error message but in this case it is taking the previous value i.e-LP1 always.Please help me to resolve this issue.
Try the following ng-options
sec.value as sec.name for sec in listPlanData

Categories

Resources