Sorry for the confusing title, basically I have a json file that looks like this that points to other locations:
{
"link": [
{
"href": "some-external-resource",
"title": "services-path"
}
]
}
My real problem is getting the href of the object to not load asynchronously into the Angular service. The following is my request to the above json file:
var servicesPath = $http({
url: 'resource-directory.json',
method: "GET"
}).success(function(data){
return $filter('filter')(data.link, {title: "services-path"})[0].href;
});
console.log(servicesPath);
I know what is being returned is what I want, but the console log returns the standard "then, catch, finally, success, error" object functions, meaning the data isn't there when I need it. How can I manipulate my request so the variable contains the information?
Since you have an async call, the value would be returned when the call is finished (successfully)
$http({
url: 'resource-directory.json',
method: "GET"
}).success(function(data){
console.log('response data', data);
var theHref = $filter('filter')(data.link, {title: "services-path"})[0].href;
console.log('theHref', theHref); // value shows here
}).error(function(errorResp){
console.log('error');
});
Related
Im trying to load the content of a JSON File into an variable.
Before, the variable looked something like this:
var Data = {
teams : [
["Team 1", "Team 2"],
["Team 3", "Team 4"]
],
results : [
[[1,2], [3,4]],
[[4,6], [2,1]]
]}
Now I have a JSON File looking something like this:
{"teams":[["Team 1","Team 2"],["Team 3","Team 4"],"results":[[[[1,2],[3,4]],[[4,6],[2,1]]]}
Now I want that the the content of the JSON File is stored in the Data Variable before. I tried it with Ajax which looks like this:
$.ajax({
type: "GET",
dataType : 'json',
async: true,
url: 'data.json',
success: function(data) {
console.log(data)
var Data = data
},
});
Console.log works perfect, but the Data is not saved in the variable and I'm getting the error: Uncaught ReferenceError: Data is not defined.
I also tried it with var Data = JSON.parse(data), but this doesn't seem to work either.
And now I'm stuck without any clue.
Thanks for help in advance.
I'm not sure what your code looks like after the ajax call, but I'm guessing the the code where you are using Data is after the ajax call. ajax is asynchrounous. That means that your code doesn't wait for it to finish before moving on. Any code that needs to wait until after it's done fetching the data, you can put in the .success function. Also, it's worth noting that success only gets called when the ajax request is successful. If you want to handle errors, you can use .error Something like this should work:
$.ajax({
type: "GET",
dataType : 'json',
async: true,
url: 'data.json',
success: function(data) {
console.log(data)
var Data = data;
// Anything that needs to use Data would go inside here
},
error: function(err) {
// handle errors
console.error(err);
}
});
// Any code here will not wait until `Data` is defined
// console.log(Data) // error
I've create a function in angular. And it is working fine and can get correct result but my problem is i want particular node from result. i have worked with JSON and Jquery, but i am new in angular.
This is my code.
$scope.booking= function(docid,addid){
//console.log(addid);
var a = $http({
method: 'POST',
url: "http://localhost:81/DoctorStayServiceAngular/model/getDoctorBookingDetail.php",
params:{"doctorid":docid,"addressid":addid,"day":weekday[d.getDay()]}
//params:{"doctorid":docid}
}).then(function mySucces(response) {
//$scope.count= response.data;
/*$scope.appo=[];
$scope.appo= i;
i++;*/
//
//console.clear();
return response.data;
});
console.log(a);
return a;
};
http://localhost:81/DoctorStayServiceAngular/model/getDoctorBookingDetail.php
return following json.
{
"status":"success",
"message":"",
"booking":{
"booking_detail":[{
"session":null,
"slot":null,
"day":"Friday"
}]
}
}
This how i can see in firebug
Expanded view
so i want to get value(which I've highlighted in image) from response(which is under $$state), what should i do?
in short how can i get bottom result?
{
"status":"success",
"message":"",
"booking":{
"booking_detail": [{
"session":null,
"slot":null,
"day":"Friday"
}]
}
}
$http service returns a promise(this is printed in your console logs), which will be resolved after that http call is complete.
Please go through this $q documentation on how deferred data works.
https://docs.angularjs.org/api/ng/service/$q
This should work,
$scope.booking= function(docid,addid){
$http({
method: 'POST',
url: "http://localhost:81/DoctorStayServiceAngular/model/getDoctorBookingDetail.php",
params:{"doctorid":docid,"addressid":addid,"day":weekday[d.getDay()]}
//params:{"doctorid":docid}
}).then(function mySucces(response) {
$scope.responseData = response.data;
});
};
After this you can bind the data in responseData to your view.
I have a byte array with some data in it. Now I want it to send the array in a RAW/Binary format to my embedded webserver:
var array = new Uint8Array(317);
... inserting data into array ...
$http.post('http://api/write_file', array)
.then(function(response) {
//Success
},function(response) {
//Fail..
});
Problem is that AngularJS by default sends the array as JSON - anyway to change this? I just want it to be transmitted raw!
EDIT:
I've tried to overwrite the transformRespons:
$http({
url: 'http://api/write_file',
method: 'POST',
transformResponse: function(value) {
return value; //Just return the value, without transform..
},
data: array
}).then(function(response) {
//Success
},function(response) {
//Fail
});
But no luck? it sends exactly the same JSON as before.
I've got the issue that my $http.post is not working correctly. Everytime I send the post it seems like it doesn't send the data at all.
This is my post:
$http({
method: 'POST',
url: "http://localhost:8080/app/api/v0/user/?access_token=" + UtilService.accessToken,
data: data
}).success(function(data){
console.debug(data);
}).error(function(data){
alert("error");
console.debug(data);
});
The data json:
var data = {
"country": $scope.country,
"firstname": $scope.firstname,
"lastname": $scope.lastname,
"username": $scope.username
}
I get the data from a form in my html.
What I tried so far is to add a header with
headers: {'Content-Type': 'application/json'}
or
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
I also tried JSON.Stringify(data) or angular.toJSson(data) before sending the data.
I even tried the suggestions from Make AngularJS $http service behave like jQuery.ajax()
But nothing seems to work. When I send the post via Postman everything works fine and I get the expected answer. When I send it via $http.post() I just get a empty data as a result and I end up in the error callback.
I am sure that the url I build is correct because of the Postman test. I feel like the issue comes from the data object I send. Even when I send a very simple json like:
{
"firstname": "asdf",
"lastname": "asdf"
}
I still recieve a empty data object.
I searched for hours now and I have no clue where this misbehaviour comes from. I'm very thankful for any advice!
EDIT: It seems like the issue comes from the fact that I'm trying to call the $http.post inside a promise.then(function(result){ /*where I call the $http.post()*/ }).
If I make the call outside the then() I get an appropriate answer. But I need to wait for the data until I can send my post. So what is wrong with the approach of sending a post inside a then()?
EDIT: The hash is the value I need to wait for
var deferred = $q.defer();
createPasswordHash(email, newPassword1,
function (hash) {
deferred.resolve(hash);
},
function (current, total) {
}
);
var promise = deferred.promise;
promise.then(function (result) {
var data = {
"country": $scope.country,
"firstname": $scope.firstname,
"lastname": $scope.lastname,
"username": $scope.username,
"hash": result
}
$http.post("http://localhost:8080/app/api/v0/user/?access_token=" + UtilService.accessToken, data).success(function (data) {
alert("success");
}).error(function (data) {
alert("error");
console.debug(data);
});
});
I had the same problem when i called the $http.post() inside the createPasswordHash method.
I'm using angular to save new data on the database, I take the data from my inputs, put it in a object and I convert it to a Json, I send it by POST, but my JSON gets cut off and I have no clue why is it happening.
var myJson = angular.toJson(myObject);
$http({
method: 'POST',
url: 'http://url/file.php',
data: {
'data': myJson
}
})
.success(function (data){
console.log(data);
})
My file.php has a var_dump($_POST) in it, and it shows that:
[
{
"uuid":"56456456456456456456465456"
},
{
"store_name":"",
"store_email":"",
"store_facebook":"",
"contact_name":"John Doe",
"contact_email":"email#email.com",
"contact_facebook":"http://localho
Angular's http post method sends whatever data it is passed to. You should check your generated json data after
var myJson = angular.toJson(myObject); using console.log(myJson);
and that itself must be cut off.