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.
Related
I am referencing this code to build a twitch viewer app, which I'm having difficulties in understanding:
$(document).ready(function() {
let usernames = ["user1", "user2", "user3", "user4"];
usernames.forEach(function(user) {
let http = "https://api.twitch.tv/kraken/streams/" + user;
function getAjax(getdata) {
$.ajax({
url: http,
headers: {
'Client-ID': 'myclientid'
},
success: function(data) {
getdata(data)
}
});
}
});
})
What does 'headers' do exactly? I looked it up on twitch and couldn't find a detailed description. It doesn't look like it gives/adds anything to my http request. Twitch says the header "securely identify my application." but wasn't sure what that mean. I thought if it works similar to an API key it should be included in the request.
What does the 'getdata' function in this code do? does it simply store the data i receive from the ajax request?
1) Headers are included in the request. You should be able to see them in the developer tools; this is what it looks like in Firefox
2) getdata is a callback function that is passed into getAjax by consumers, which can then act on the data as necessary, for example...
getAjax(function(data) {
// do something with data
})
Note also, you're redeclaring the function in each iteration of the loop, but not actually calling it anywhere. You probably want something more like this...
$(document).ready(function() {
let usernames = ["user1", "user2", "user3", "user4"];
function getAjax(url, getdata) {
$.ajax({
url: url,
headers: {
'Client-ID': 'myclientid'
},
success: function(data) {
getdata(data)
}
});
}
usernames.forEach(function(user) {
let http = "https://api.twitch.tv/kraken/streams/" + user;
getAjax(http, function(data) {
// do something with data
})
});
})
I've been playing around with the Google+ API and trying to get the profile image url of a Google+ user with this url:
https://www.googleapis.com/plus/v1/people/{user_id}?key={API_KEY}
No OAuth is needed and you can also give it a try here (no API key needed):
https://developers.google.com/apis-explorer/#p/plus/v1/plus.people.get?userId=116725099929439898086&_h=1&
At first I used the Fetch API to fetch the data since I also want to use a service worker to do that:
fetch('https://www.googleapis.com/plus/v1/people/116725099929439898086?key=MY_API_KEY')
.then(function(response){
console.log(response);
});
But it only gives me this response:
{
body: ReadableStream
bodyUsed: false
headers: Headers
ok: true
status: 200
statusText: ""
type: "cors"
url: "https://www.googleapis.com/plus/v1/people/115681458968227650592?key=MY_API_KEY"
}
However, if I use jQuery's getJSON method instead:
$.getJSON( "https://www.googleapis.com/plus/v1/people/115681458968227650592?key=MY_API_KEY", function( data ) {
console.log(data);
});
It works like a charm and I can get what I need:
{
"kind": "plus#person",
"etag": "\"FT7X6cYw9BSnPtIywEFNNGVVdio/DgskSQn7XXHCvjcdFBFkiqEbsfo\"",
"gender": "male",
"urls": [ ... ],
"objectType": "person",
"id": "116725099929439898086",
"displayName": "Kevin Lai",
...
}
Can someone explain why they will to such different behaviors? And also, how can I fix the problem while still using the Fetch API so I can still do this asynchronous task in a service worker?
Change the fetch() call to use response.json() (see MDN docs) to extract the JSON from the response body.
fetch('https://www.googleapis.com/plus/v1/people/116725099929439898086?key=MY_API_KEY')
.then(function (response){
return response.json();
})
.then(function (json){
console.log(json);
});
Relevant function
function subscribe(to_send, url) {
$.ajax({
url: url,
data: to_send,
dataType: 'jsonp',
success: function(data) { console.log('Response', data) },
error: function (data) { console.log('FUUUUU: ' + data) }
})
}
Variables passed in
to_send = http://evaline.us14.list-manage.com/subscribe/post-json?u=76ee17f86cd92d4984c0046f8&id=15deb1bbee&c=?
and to_send = JSON.stringify(data), where data is the following:
data = {
"email_address": inputs[1].value,
"email_type": "html",
"status": "subscribed",
"status_if_new": "subscribed",
"merge_fields": {
"FNAME": inputs[0].value
},
"interests": {
"9b4ccc9f43": isInvestor,
"82636e7cd9": isEmployee,
"c8b187e22d": isBusiness,
"798cc04c42": isUser,
"d750ac8858": isOther,
}
}
Where inputs[i] evaluate properly to strings, and isSomeRole evaluates to a boolean. I confirmed with a console.log that they do actually properly evaluate, into something like this:
"{\"email_address\":\"a#a.io\",\"email_type\":\"html\",\"status\":\"subscribed\",\"status_if_new\":\"subscribed\",\"merge_fields\":{\"FNAME\":\"a\"},\"interests\":{\"9b4ccc9f43\":false,\"82636e7cd9\":false,\"c8b187e22d\":false,\"798cc04c42\":true,\"d750ac8858\":false}}"
...which is the properly stringifyed data.
On execution of subscribe()
When I execute subscribe(), it appears to properly submit, running the success: function(data) bit, with the response being the following:
Response – {result: "error", msg: "Blank email address"}
This is the exact same response I get if I execute subscribe('', url) - seems like data isn't being attached/sent at all...
To conclude...
I'm really confused. Should I not be stringifying data? Should I be doing something else with that payload? Am I missing something in my ajax statement?
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');
});
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.