Inserting data into database by WEB API in angular JS - json

I am new into angular JS and web api world. Recently facing difficulty in sending data into database through web api and angular. I am able to load json data from webapi.Any help will be highly appreciated.
My html:
<div class="container-fluid" ng-controller="SubmitDataCtrl">
<div class="container text-center" style="margin-bottom:5px">
<div id="divTables">
<table id="tbl_SMDetails" class="display responsive nowrap aleft" cellspacing="0" width="100%">
<thead>
<tr>
<th class="all">Name</th>
<th class="all">CTSID</th>
<th class="all">FDID</th>
<th class="all">Name of the Project</th>
<th class="all">Effort Hour</th>
<th class="all">Month</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="showData in loadData">
<td>{{showData.EmpName}}</td>
<td>{{showData.EmpCognizantID}}</td>
<td>{{showData.FDID}}</td>
<td><input id="Text1" type="text" />{{showData.projectName}}</td>
<td><input id="Text1" type="text" />{{showData.effortHour}}</td>
<!--<td>{{date | date:'MM-dd-yyyy}}</td>-->
<td>{{showData.date}}</td>
</tr>
</tbody>
</table>
</div>
</div>
<div>
<a ng-href='#SubmitData' class="btn btn-default" ng-click='go()'>Submit</a><span></span>
<a ng-href='#SubmitData' class="btn btn-default" ng-click=''>Reset</a>
</div>
</div>
My service page looks like:
var request = $http({
method: method_args,
url: myConfig.ServiceURL + url,
data: JSON.stringify(input_data),
Accept: 'application/json',
headers: {'Content-Type':'application/json'},
xhrFields: {
withCredentials: true
}
});
}
and my controller is
App.controller("SubmitDataCtrl", function($scope, ajaxService) {
//login user
ajaxService.MakeServiceCall("employee/GetTeamMember? superVisiorCogniID=256826", "GET", "")
.then(function effortData(data)
{
// alert(data);
$scope.date = new Date();
$scope.loadData = data;
showData = $scope.loadData;
for (var i = 0; i < showData.length; i++)
{
//alert(showData[i].EmpName + showData[i].EmpCognizantID + showData[i].FDID);
}});
$scope.go = function()
{
//alert('clicked');
ajaxService.MakeServiceCall("effort/SaveTeamEfforts?hourLoadDate=08/20/2015&hourLoadByCogniID=256826&forMonth=July", "POST", Employee).then(function save() {
var Employee =
{
"EmpCogniID": showData[i].EmpCognizantID,
"FDTimeCardHour": showData[i].effortHour,
"HourLoadDate": 08/11/2015,
"HourLoad`enter code here`By": "256826",`enter code here`
"ForMonth": "july"
}
}).success(function (Employee)
{
$scope.showData[i] = Employee;
});
alert(Employee); }});

It's hard to answer without knowing what the API POST call should do.
Can you confirm that the POST you are making to effort/saveTeamEfforts works by executing it using a REST tester in the browser?
if that is working, you should add an .error function to your API call and see what error is returned as dan has sugested above
L

Related

Retrieving Mongodb data in front end by using Ajax Get Method

I have inserted a data in mongodb and used nodejs for writting API, need to retrieve those data in front-end using jquery. I have inserted 3 rows of data in mongodb.I have used below code to get data and it is working fine, but it is hardcoded. I want it to happen manually using jquery. Please help to solve this.
$.ajax({
dataType:"json",
url: "/purchaser/purchasersList",
type:"GET",
global:false,
async:false,
success: function(response){
console.log("response is:",response);
document.getElementById("userName").innerHTML = (response[0].userName);
document.getElementById("email_id").innerHTML=(response[0].email_id);
document.getElementById("address").innerHTML=(response[0].address);
document.getElementById("phoneNumber").innerHTML=(response[0].phoneNumber);
//2nd row data
document.getElementById("userName1").innerHTML = (response[1].userName);
document.getElementById("email_id1").innerHTML=(response[1].email_id);
document.getElementById("address1").innerHTML=(response[1].address);
document.getElementById("phoneNumber1").innerHTML=(response[1].phoneNumber);
//3rd row data
document.getElementById("userName2").innerHTML = (response[2].userName);
document.getElementById("email_id2").innerHTML = (response[2].email_id);
document.getElementById("address2").innerHTML = (response[2].address);
document.getElementById("phoneNumber2").innerHTML =(response[2].phoneNumber);
},
error: function (jqXHR, textStatus, errorThrown) { // error callback
console.log("Error Response jqXHR is:" + jqXHR);e
<table class = table2>
<tr>
<th style="text-align:center">SL.No</th>
<th style="text-align:center">Purchaser Name</th>
<th style="text-align:center">Email</th>
<th style="text-align:center">Address</th>
<th style="text-align:center">Phone No</th>
</tr>
<tr>
<td height="50">1</td>
<td height="50" id="userName"></td>
<td height="50" id="email_id"></td>
<td height="50" id="address"></td>
<td height="50" id="phoneNumber"></td>
<td height="50">Active</td>
</tr>
<tr>
..
</tr>
If you can change the id to class then I surges you try something like this:
$.each(response,function(i) {
var tr = $('.table2 tr').eq((i+1));
$(tr).find(".userName").text(response[i].userName)
$(tr).find(".email_id").text(response[i].email_id)
$(tr).find(".address").text(response[i].address)
$(tr).find(".phoneNumber").text(response[i].phoneNumber)
})
Note I can't test it since I dont have your response.
Full code
$.ajax({
dataType: "json",
url: "/purchaser/purchasersList",
type: "GET",
global: false,
async: false,
success: function(response) {
$.each(response,function(i) {
var tr = $('.table2 tr').eq((i+1));
$(tr).find(".userName").text(response[i].userName)
$(tr).find(".email_id").text(response[i].email_id)
$(tr).find(".address").text(response[i].address)
$(tr).find(".phoneNumber").text(response[i].phoneNumber)
})
},
error: function(jqXHR, textStatus, errorThrown) { // error callback
console.log("Error Response jqXHR is:" + jqXHR);
e
<table class=table2>
<tr>
<th style="text-align:center">SL.No</th>
<th style="text-align:center">Purchaser Name</th>
<th style="text-align:center">Email</th>
<th style="text-align:center">Address</th>
<th style="text-align:center">Phone No</th>
</tr>
<tr>
<td height="50">1</td>
<td height="50" class="userName"></td>
<td height="50" class="email_id"></td>
<td height="50" class="address"></td>
<td height="50" class="phoneNumber"></td>
<td height="50">Active</td>
</tr>
<tr>
..
</tr>

ng repeat nested loop

I am facing an issue while displaying the nested data inside the ng-repeat. I get data for the first 4 fields but those which are more nested like the label and onwards field data do not show up. the last 5 fields appear to be empty and does not fetch the data. Will be glad if anyone could help troubleshoot the issue.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<!-- <p>Today's welcome message is:</p> -->
<table border="2">
<tr>
<th>deliveryRecipient</th>
<th>Pick Up Locality</th>
<th>Delivery Locality</th>
<th>Created On</th>
<th>Name</th>
<th>category</th>
<th>Item Price</th>
<th>Weight</th>
<th>Qty</th>
<th>Action</th>
</tr>
<tr ng-repeat="x in myWelcome">
<td>{{x.deliveryRecipient}}</td>
<td>{{x.pickupLocality}}</td>
<td>{{x.deliveryLocality}}</td>
<td>{{x.createdOn}}</td>
<td>{{x.label}}</td>
<td>{{x.category}}</td>
<td>{{x.actualPriceLabel}}</td>
<td>{{x.weight}}</td>
<td>{{x.quantity}}</td>
<td><button onclick="showgraphqldata()" type="button" class="view">View</button></td>
</tr>
<td ng-repeat="y in x.items">
<td>
<tr ng-repeat="z in y">
<td>{{z.label}}</td>
<td>{{z.category}}</td>
<td>{{z.actualPriceLabel}}</td>
<td>{{z.weight}}</td>
<td>{{z.quantity}}</td>
</tr>
<input type="hidden" value="{{x.uid}}" />
</table>
</div>
<!-- <p>The $http service requests a page on the server, and the response is set as the value of the "myWelcome"
variable.</p> -->
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
$http({
method: "GET",
url: "https://api-stg.martcart.pk/api/v1/merchants/incomingOrders?archived=false&isIncomingOrders=true&isPurchaseOrders=true&loadItems=true&pageNumber=1&recordsPerPage=100&statusIn=NEW,VIEWED",
headers: {
datatype: 'JSON',
, 'Content-Type': 'application/json'
}
}).then(function mySuccess(response) {
$scope.myWelcome = response.data;
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
});
</script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).on('click', '.view', function () {
var uid = $(this).parent().prev().val();
</script>
</body>
</html>
attached images are the responses if json data
enter image description here
enter image description here

Importing a HTML table into a google doc using google app script

I'm importing data from JIRA into a Google Doc. One of the fields would be the description, which is basically HTML text.
Is there any way to "add" this HTML text on a Google Doc? Or do I really have to parse it manually and create paragraphs, tables, etc.?
The HTML could look as follows:
<p>Hello There</p>
<table class='confluenceTable'>
<tbody>
<tr>
<th class='confluenceTh'> Name </th>
<th class='confluenceTh'> Hours </th>
<th class='confluenceTh'> Cost </th>
</tr>
<tr>
<td class='confluenceTd'> Some Person</td>
<td class='confluenceTd'> 1 </td>
<td class='confluenceTd'> CHF 1</td>
</tr>
</tbody>
</table>
I was able to create a new Doc with styled html content from the change mentioned in my comment in this post:
var blob = Utilities.newBlob(content, {mimeType:"text/html"});
var newfile = Drive.Files.insert(resource, blob, {"convert":"true"});
Thanks for your hint - based on this I found the following post: https://ctrlq.org/code/20102-convert-office-files-to-google-docs (plus http://scraping.pro/automaticly-converting-files-google-app-script/ which tells how to enable Drive API).
The following function works pretty well for me:
function convertHtmlToDocs(html) {
var uploadFile = JSON.parse(UrlFetchApp.fetch(
"https://www.googleapis.com/upload/drive/v2/files? uploadType=media&convert=true",
{
method: "POST",
contentType: "text/html",
payload: Utilities.newBlob("").setDataFromString(html, "UTF-8").getBytes(),
headers: {
"Authorization" : "Bearer " + ScriptApp.getOAuthToken()
},
muteHttpExceptions: true
}
).getContentText());
var doc = DocumentApp.openById(uploadFile.id);
var body = doc.getBody().copy();
DriveApp.removeFile(DriveApp.getFileById(doc.getId()));
return body;
}

How to convert json string to ko.observableArray([]), array of objects?

I have a ViewModel works with knockout framework and ajax. I can save new items to the database with ajax.Save but I have problem when I want to retrieve the saved data. Here are the codes.
Codes in ViewModel:
self.Categories = ko.observableArray([]);
self.Message = ko.observable("");
elf.GetCategories = function () {
$.ajax({
url: "/Admin/Categories",
cache: false,
type: "GET",
datatype: "json",
contenttype: "application/json;utf8"
}).done(function (data) {
self.Categories(ko.mapping.fromJS(data));
}).error(function (err) {
self.Message("Error! " + err.status);
});
}
console.log(JSON.stringify(data)); returns:
{"categories":[{"Id":1,"Name":"Learning","UrlSlug":"0-learning","Description":"learning"},
{"Id":2,"Name":"Topics","UrlSlug":"0-topics","Description":"posts"},
{"Id":3,"Name":"Shares","UrlSlug":"category-shares","Description":"shares"},
{"Id":4,"Name":"Projects","UrlSlug":"category-projects","Description":"project"}]}
Codes in controller is:
[HttpGet]
public ContentResult Categories()
{
var categories = _weblogServices.Categories();
return Content(JsonConvert.SerializeObject(new {categories}), "application/json;utf8");
}
and the problem is the self.Categories = ko.observableArray([]); is always empty without any data. I also tried these items too, but nothing changed:
ko.mapping.fromJS(data, self.Categories);
self.Categories(ko.mapping.fromJS(data));
self.Categories(ko.mapping.fromJSON(data));
ko.mapping.fromJS(data, {}, self.Categories);
I have a simple table in view :
<table id="tblCategory" class="table table-striped table-bordered
table-responsive table-condensed table-hover">
<thead>
<tr>
<th class="text-center">Name</th>
<th class="text-center">Url Slug</th>
<th class="text-center">Description</th>
</tr>
</thead>
<tbody data-bind="foreach: Categories">
<tr>
<td><span data-bind="text: Name"></span></td>
<td><span data-bind="text: UrlSlug"></span></td>
<td><span data-bind="text: Description"></span></td>
<td><button type="button" class="btn glyphicon glyphicon-pencil"
title="Edit" data-bind="click:$data.GetSelected"></button></td>
<td><button type="button" class="btn glyphicon glyphicon-trash"
title="Delete" data-bind="click:$data.DeleteSelectedCategory">/button></td>
</tr>
</tbody>
</table>
So, the question is how can I convert JSON data to observableArray([])?
UPdate: Chrome debugger says: data and Categories are not available.
You don't need to use mapping at all.
In your ajax call .done, you simply have to do this:
self.categories(data.categories);
As an observable array, categories expect an array as parameter. And according to the result of console.log(JSON.stringify(data)) being: {"categories":[{...}, {...}, ...], the array is on the categories property of the received data.
You don't need to use mapping because you simply need to show the objects inside the array, and you don't want to edit their properties. So they can be left as regular JavaScript objects, without observable properties.

Retrieving values from a table cell <td> to a controller

I'm trying to get a specific value from a table cell and pass is to a controller. But it doesn't seem to be working. I show you some of my codes:
This is in the controller:
def searchUser = {
String abc = request.getParameter("harrow")
println(abc)
}
This is in the html page:
<form>
<div style="height: 250px; overflow: scroll; width: 100%;">
<table id="normal">
<g:each in = "${result}">
<tr id="btn">
<td width=10% >${it.ID}</td>
<td width=25% id="harrow">${it.username}</td>
</tr>
</g:each>
</table>
</div>
<input type ="submit" name ="abc" id="opener">
</form>
EDIT
AJAX:
$("#edittable").on('click', function() {
$.ajax({
url: URL,
data: $(this).serialize(),
type: "POST",
success: function(html){
//do something with the `html` returned from the server here
$("#edit1").html(html).dialog("open")
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;//suppress natural form selection
});
I can get the value to pass to the controller, but right now it only retrieves the first row of values rather than the other. Is there something wrong with my AJAX codes? Thank you guys so much.
So to show details of the row, one of the approaches can be:
CONTROLLER METHODS
def rows = [
[id:1, name:'name1'],
[id:2, name:'name2'],
[id:3, name:'name3']
]
def show(){
[results:rows]
}
def showLine(Long id){
render rows.find {it.id == id }
}
VIEW
<html>
<head>
<g:javascript library="jquery" />
<r:layoutResources />
</head>
<body>
<table>
<thead>
<tr>
<th>Action</th>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<g:each in="${results}" status="i" var="r">
<tr>
<td><g:remoteLink value="Details" id="${r.id}" action="showLine" update="lineDetails">Details</g:remoteLink></td>
<td>${r.id}</td>
<td>${r.name}</td>
</tr>
</g:each>
</tbody>
</table>
<div id="lineDetails">
</div>
</body>
</html>
Basically you call showLine method using AJAX and passing row object id. Then you search for the object and render it back. Rendered data is put into div under the table. It's up to you if you use onclick, button or link in the table. It's also up to you how to show details on results page - use jquery dialog, or something else. Hope it helps