My service code look like belowed :-
data.service('SmartLearnerService', function ($http) {
//Get Single Records
this.get = function (id) {
return $http.get("/api/Category/");
}
});
Here is my controller code for App.js:-
$scope.questionlist = SmartLearnerService.get();
$scope.questionlist.then(function (pl) {
var res = pl.data;
$scope.que = res.QuestionLabel;
},
function (errorPl) {
console.log('failure loading Employee', errorPl);
});
console.log($scope.questionlist);
Here is Controller code for web api controller :-
public class CategoryController : ApiController
{
CommonDb db = new CommonDb();
public JsonResult Get()
{
var Result = db.GetQuestionById().ToList();
string message = "No Data Found";
if (Result.Count() != 0)
{
return new System.Web.Mvc.JsonResult()
{
Data = Result,
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
};
}
else
{
return new System.Web.Mvc.JsonResult()
{
Data = message,
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
};
}
}
}
}
And here is div tag where i want to bind questions from json result using ng-repeat directive.
<div class="question" align="center">{{Questions.QuestionLabel}}</div>
i am facing problem while binding json array in controller's $scope.questionlist and i am successfully getting json result from web api controller.
Ok, if I had to guess (and that's exactly what I'm doing), you want something like this in your controller...
SmartLearnerService.get().success(function(questions) {
$scope.questionList = questions;
});
or, if you're not a fan of the add-on success / error callbacks
SmartLearnerService.get().then(function(response) {
$scope.questionList = response.data;
});
and in your template
<div ng-repeat="question in questionList">
<div class="question" align="center">{{question.QuestionLabel}}</div>
<!-- and so on -->
</div>
This is totally assuming your C# controller returns JSON that looks something like...
[{
"QuestionID": "1",
"QuestionLabel": "Why are mirrors often slightly curved (convex) ?",
"Image": "zibra-crossing.jpg",
"Correct": "two",
"Explaination": "Question one explaination is goes here"
}, {
...
}]
Can you try this?
SmartLearnerService
.get()
.success(function (data, status) {
if (status === 200) {
//your code to process data is here
}else{alert(status)}
})
.error(function (data, status) {
//TODO: Use nice alert.
alert('Server request failed with status ' + status + ' while getting area in the ' + $item.Name);
});
You will get the status code that you are receiving and then you can change the code accordingly.
The approach that I took in my case was to serialize using JsonConvert from NewtonSoft and then return the string of Json object instead of Json object itself to improve the speed.
Related
Im new in angular, tried to search many posts but none helped me to receive data in controller method after angular js post. Does anyone know why parameters of model object are empty even though angularjs post sends the data?
this is the request payload which I found in chrome debugger, so I think all goes to bakend correctly..
{Name: "MyName"}
Name: "MyName"
FrontEnd:
<div id="divMain" ng-app="testCtrl">
<div id="divTblForm" class="border" ng-controller="ButtonsController">
<input id="btnTest" class="inptSubmit right roundBorder" type="button" value="Test" ng-click="test()" />
</div>
</div>
here's the javascript (i tried to stringify, without stringify, property names in objToSearch quoted, not-quoted and so on..)
function getAngularApp() {
return angular.module('testCtrl', []);
}
app.controller('ButtonsController', function ($scope, $http) {
$scope.test = function () {
var objToSearch = {
Name: 'MyName'
}
$http.post("TestAngular/Test", JSON.stringify(objToSearch),
{
headers: {
"Content-Type": "application/json"
}
}
).success(function (response) {
alert(response)
})
.error(function (error) {
alert(error);
});
}
});
Backend:
I tried with and without FromBody attribute and none of them brought success..
[RoutePrefix("TestAngular")]
public class TestAngularController : Controller
{
[System.Web.Http.Route("Test")]
[System.Web.Http.HttpPost]
public List<Test> Test([System.Web.Http.FromBody]Test test)
{
//breakpoint here, parameter 'test' values always empty or null..
return null;
}
}
here's the model class
public class Test
{
public string Name { get; set; }
}
Can anyone help please? I spent already more than 4 hours of searching similar topics and trying. it becomes really exhauasting. :(
I modified the AngularJS code to post data using $http.post, which work as expected.
On AngularJS client
<script>
function getAngularApp() {
return angular.module('testCtrl', []);
}
var app = getAngularApp();
app.controller('ButtonsController', function ($scope, $http) {
$scope.test = function () {
var objToSearch = {
Name: 'MyName'
}
$http.post("/TestAngular/Test", JSON.stringify(objToSearch),
{
headers: {
"Content-Type": "application/json"
}
}
).then(function successCallback(response) {
//code logic here
console.log("success");
}, function errorCallback(response) {
console.log("error");
});
}
});
</script>
Test Result
To troubleshoot the issue, you can use postman etc tools to make request(s) with same testing data and check if your controller action can receive the data you sent. And if possible, you can create new project to implement same functionality then check if that new one can work well.
newbie here.
I am trying to understand how I need to structure asynchronous calls within my controller to fit my specific use case:
Consider the following code snippet from an Angular Module in "service.js" within my project:
function getSearchObjects(projectName, title) {
var payload = JSON.stringify({
"title": title
});
var request = $http({
method: 'post',
url: URL + '/search/' + projectName,
data: payload
});
return request.then(handleSuccess, handleError);
};
function runQuery(projectName, fromDate, toDate, sort, direction, columns) {
var from = Date.parse(fromDate);
var to = Date.parse(toDate);
var payload = JSON.stringify({
"fromDate": from,
"toDate": to,
"sort": sort,
"direction": direction,
"columns": columns
});
console.log(payload);
var request = $http({
method: 'post',
url: URL + '/query/' + projectName,
data: payload
});
return request.then(handleSuccess, handleError);
}
function handleSuccess(response) {
return response.data;
};
function handleError(response) {
if (!angular.isObject( response.data ) || !response.data.error) {
return( $q.reject( "An unknown error occurred." ) );
}
return $q.reject( response.data.error );
};
});
Within my controller, I am trying to troubleshoot the following function:
$scope.submit = function() {
var objectProperties = exportsStorageService.getSearchObjects($scope.selected.project.name, $scope.selected.search)
.then(function(result) {
exportsStorageService.runQuery($scope.selected.project.name, $scope.selected.start_date, $scope.selected.end_date, objectProperties.sort, objectProperties.direction, objectProperties.columns)
},
function(error) {
console.log(error);
});
};
getSearchObjects matches a title ($scope.selected.search) selected in my UI and grabs the following more detailed object from an API call:
{ title: 'Duplication Example',
sort: '#_traac-timestamp',
direction: 'desc',
columns: [ '#_traac-remote_ip', 'c-platform-m-distinct-id_s', '_type' ] }
I am trying to grab the properties returned from getSearchObjects and pass them along with a few user selected values from my UI to runQuery, which then returns data from a database to the user, but when I check the values passed to runQuery using the above logic in my controller, I get the following values. All of the objectProperties values I am attempting to pass to runQuery are undefined:
project_name: "Example Project"
start_date: 1499770800000
end_date: 1499943600000
sort: undefined
direction: undefined
columns: undefined
I have been trying to debug this, but I am too new to using Angular and asynchronous calls to really understand what I am doing wrong. My best guess currently is that I am calling runQuery before the values retrieved from getSearchObjects are attached to objectProperties. Either that or I am incorrectly referencing the properties within the objectProperties variable.
Could someone help me troubleshoot this issue, and better understand what I am doing wrong?
Thank you in advance for your help!
When you do this:
var objectProperties = some async function...
You are assigning the promise of the async function to the variable, not the result of it.
The result is coming in the .then, like you declared:
.then(function(result) { ... }
So, instead of objectProperties.sort, objectProperties.direction, objectProperties.columns, try using result.sort, result.direction, result.columns :)
If you are new to Promises, take a look at this simple, but great tutorial.
EDIT
Based on your comment, you are receiving, inside the response.data, the following object:
{"objectMatch": {
"title": "doc-event",
"sort": "#_traac-timestamp",
"direction": "desc",
"columns": [
"m-doc-name_s",
"m-user_s",
"m-full-action-type_s",
"m-event-action-descriptor_s"
]}
}
So you have: response > data > objectMatch > properties you want.
The response.data you are extracting on your handleSuccess function:
function handleSuccess(response) {
return response.data;
};
So here, your result is response.data, containing the property objectMatch.
$scope.submit = function() {
var objectProperties = exportsStorageService.getSearchObjects($scope.selected.project.name, $scope.selected.search)
.then(function(result) {
...
},
...
If all of that is correct, you should be able to access the values you want using result.objectMatch.<sort, direction or columns>, like:
exportsStorageService.runQuery($scope.selected.project.name, $scope.selected.start_date, $scope.selected.end_date,
result.objectMatch.sort, result.objectMatch.direction, result.objectMatch.columns)
I have this http request
GET /deals/couchbaseDocument/_search
{
"query" : {
"match" : {
"amenities" : "Maids "
}
}
}
when i put it in curl, it gives me results, i want to build a web app to call that request.
what i did is removing the newlines and put the whole text in .getjson()
as this:
var query = $("#query").val();
query = query.replace(/(\r\n|\n|\r)/gm,"");
$.getJSON(query, function (results) {
alert("success");
alert(results);
})
.success(function () { alert(" second success"); })
.error(function () {
alert("error");
alert(query);
});
i kept getting the error alert, i wonder if what i did is actually what should it be done to send that request
I read this
I found that .getJson could be like this:
$.getJSON('httpURL',
{ parameter1: "parameter value", parameter2: "parameter value" })
i wonder if i should pass my json request as a parameter
in case of the whole picture** i am working on sense elasticsearch plugin
According to the documentation of jQuery's getJson, you can pass a javascript object (jQuery.getJSON() | jQuery API Documentation) so you can do something like this
var queryData = {
"query" : {
"match" : {
"amenities" : "Maids "
}
}
};
$.getJSON('httpURL', queryData)
From client-side javascript I want to call a share-webscript which returns JSON data.
The response from getTicket.json.ftl looks like:
{
"ticket" : "TICKET_faf851d4a993b62c98908268af07876f09fa86c9"
}
So how can I call this share-webscript from my client-side javascript and extract the value of "ticket" ?
see answer below
Answer:
Alfresco.util.Ajax.jsonGet(
{
url: Alfresco.constants.PROXY_URI + "/auth/getTicket.json",
successCallback:
{
fn: function(response)
{
try {
var json = JSON.parse(response.serverResponse.responseText);
var ticket = json["ticket"];
if (ticket.substring(0, 6) == "TICKET") {
clipboardData.setData("Text", ticket + "&" + file.nodeRef);
location.href = Alfresco.constants.URL_RESCONTEXT + "components/javawebstart/AEF_JNLP.jnlp";
} else {
// handle unknown format
}
} catch (e) {
// handle error
}
},
scope: this
},
failureCallback:
{
fn: function(response)
{
// handle failure case
},
scope: this
}
});
This calles the share tier webscript. So you also need a share tier webscript which calls a repository web script which returns the actual ticket ...
I have two Ajax Get Request:
$.get('/tutorials/rate', {id: {{$tutorial->id}}}, function (data) {
$ratingCount = data;
});
$.get('/tutorials/rateAverage', {id: {{$tutorial->id}}}, function (data) {
$averageRating = data;
});
in my Controller:
public function get_rate() {
$postId = Input::get('id');
$ratings = rating::where('tutorial_id', '=', $postId)->get();
return count($ratings);
}
public function get_rateAverage(){
$postId = Input::get('id');
}
in my routes:
Route::controller('tutorials', 'TutorialController');
First Request is workin like a charm, second one gives me a 500 Error...
On your second get request, try
$.get('/tutorials/rate-average', {id: {{$tutorial->id}}}, function (data) {
$averageRating = data;
});
Your function names should be getRate() and getRateAverage()
This is what Laravel expects as far as naming conventions. Please see http://laravel.com/docs/controllers#resource-controllers