How Displlay elements from API query , or put them in array - javascript

Hello i want to display results from https://developer.edamam.com/edamam-docs-recipe-api this api or to put them into array
vm.search = function(){
var req2 = {
method: "GET",
url:"https://api.edamam.com/search?q="+vm.searchText+"&app_id=myID&app_key=myKey"
}
$http(req2).then(
function(resp){
console.log(resp);
vm.recepti = resp.data.Search;
console.log(vm.recepti);
}, function(resp){
vm.message = 'error';
});
};
i dont quite understand this particular api, or how do i display all recepies (names, images and other parameters that it has) from query result that users inputs in field with vm.searchText text box thanks for help in advance
vm.recepti is an emtpy array ,
when i go to query link i get this now how do i access properties based on this?

Try to do something like this:
vm.recepti = resp.data.hits;

Related

How can I assign dictionary values to javascript variables (jQuery / AJAX API call returned in JSON)

I have a well running AJAX request that queries data from a third party API that returns the data in JSON. I now want to assign the values from the returned JSON data to javascript variables to make further manipulation to the data itself in my AJAX success function before updating the frontend.
In the below example I would like to assign the value of key name to my Javascript team variable.
What would be the best way to accomplish this?
This is the returned structure:
{
"api":{
"results":1,
"teams":[
{
"team_id":66,
"name":"Barcelona",
"code":null,
"logo":"Not available in Demo",
"country":"Spain",
"founded":1899,
"venue_name":"Camp Nou",
"venue_surface":"grass",
"venue_address":"Carrer d'Ar\u00edstides Maillol",
"venue_city":"Barcelona",
"venue_capacity":99787
}
],
This is my AJAX request:
$('ul.subbar li a').on('click', function(e) {
e.preventDefault();
var team_id = $(this).attr("id");
console.log(team_id);
$.ajax({
method: "GET",
dataType: "json",
url: "https://cors-anywhere.herokuapp.com/http://www.api-football.com/demo/api/v2/teams/team/" + team_id,
success: function(response) {
var team_data = response
console.log(team_data)
team = // how to assign team name from API callback to variable
console.log(team)
$("#selectedClub").html(response);
}
});
});
You can use dot notation to navigate through objects
team_data.api.teams[0].name //output: "barcelona"
In you example there is only one item inside teams array, so the above example should works fine, but let's suppose that in your response there is more than 1 team on teams then you could do something like this:
var teamList = [];
$.each(team_data.api.teams, function(index, team){
teamList.push(team.name);
})
and it will give an array with all team names from your ajax response
put JSON in js obj variable
var obj = JSON.parse('{ <key:value>,<key:value>...}');
Make sure the text is written in JSON format, or else you will get a syntax error.
Use the JavaScript object in your page:
Example
<p id="demo"></p>
<script>
document.getElementById("name").innerHTML = obj.name + ", " + obj.country;
</script>

PHP POST: Setting data variables dynamically from an array

Hi all I'm pretty new to PHP and AJAX and all that good stuff and I'm a little stumped on how to proceed from here in my code.
I have a form that is getting sent and I have an array (subcategories) which contains the form labels to retrieve the values of the fields. The fields and values are getting created dynamically based on a textfile that the user uploads so I don't have any way of knowing what they are.
var arrayLength = subcategories.length;
for (var i = 0; i < arrayLength; i++) {
var eachfield = subcategories[i];
//Do something
//#C: selector is working fine, cleaning input
var eachfield = $('#' + eachfield).val().trim();
//push the appropriate values with the fixed stuff to a new array
values.push(eachfield);
}
What I'm trying to do is now to set these variables to some name and send them through $data using AJAX and POST.
Something like the following if I was setting everything statically.
var data = {
dimitypedata: dimitype,
densitydata: density,
velocitydata: velocity,
temperaturedata: temperature,
submitbtnclicked: "submitted"
};
//using the data and sending it through a post with promise handling
$.ajax({
type: 'POST',
url: "controller.php",
data: data,
success: function(response) {
//alert("worked");
//console.log(response);
alert(response);
},
error: function() {
alert("There was an error submitting the information");
}
});
I'm not quite sure how to mix these two and it may be partially because of getting a confused and not yet being that great with POST and AJAX calls.
EDIT: It looks like my question was a bit unclear (sorry first post lol) I'm trying to dynamically push values that I take out of an HTML form field. The problem is that the form is generated depending on what the user chooses to upload to the site (so both the fields and the forms. My ultimate goal is to enable the user to edit the dynamically generated form based on a text file that they upload and be able to generate a new text file after editing it on the GUI after clicking on the submit button. I can do this if its static but I'm having trouble figuring out how to do the same if I don't know what the form will contain.
I'm trying to to my data object so I can use it in my AJAX call. Here's a little bit of the PHP code that I would use in the next step if the variables were static:
if(isset($_POST['submitbtnclicked']) && $_POST['submitbtnclicked'] == 'submitted') {
//new instance of model for use
$model = new model();
$dimitypedata = $_POST['dimitypedata'];
$densitydata = $_POST['densitydata'];
$velocitydata = $_POST['velocitydata'];
$temperaturedata = $_POST['temperaturedata'];
For an exact answer, we need to see what the "subcategories" array look like.
If I understood correctly, you would like to put the values in an object instead of an array (values). So the first part would look like:
var data = {};
var arrayLength = subcategories.length;
for (var i = 0; i < arrayLength; i++) {
//notice that now field name and field value go in separate variables
var fieldName = subcategories[i];
//#C: selector is working fine, cleaning input
var fieldValue = $('#'+eachfield).val().trim();
//push the appropriate values with the fixed stuff to a data object
data[fieldName] = fieldValue;
}
//and then you send your gathered data
//using the data and sending it through a post with promise handling
$.ajax({
type: 'POST',
url: "controller.php",
data: data,
success: function(response) {
//alert("worked");
//console.log(response);
alert(response);
},
error: function() {
alert("There was an error submitting the information");
}
});
If you want to generate your 'data' object using 'values' variable, you can do the next:
values = []; // here your values collected previously
var data = {};
for (var key in values){
data[key] = values[key];
}
//now you can use your data in AJAX

Javascript pass var

I'm having a little problem. I'm new in JS and I can't figure it out.
I'm trying to get a list of friends from Facebook. To do that I'm using the user posts and I want to show only the duplicates. My first answer is how to show all the friends from a loop and get only the duplicates (I want only one or two objects) and second is how to pass a var from a function to another function because I want to POST all the infos to a php file.
This is what I did:
function getInfo() {
FB.api(
'/me',
'GET',
{fields: 'first_name'},
function(response) {
friends();
var myname = response.first_name;
$.post(
"file.php",
{ myname:myname,friendsname:friendsname },
function(data) { $("body").append(data); }
);
}
With this function I'm getting my first name.
function friends() {
FB.api(
'/me/posts?fields=likes{id,name}',
{limit:50},
function(response) {
if (response.data) {
$.each(response.data,function(index, posts) {
var posturi = posts.likes;
$.each(posturi.data, function(useri, lista) {
var friendsname = lista.name;
});
});
}
}
);
}
And this is the list with my friends. If I check console.log(friendsname) it gives me all the friends with duplicates. But if I write an innerHTML in that $.each it returns me only 1 object. And how can I pass friendsname from friends() to getInfo() so I can post to that .php file?
That's because you're overwriting the value of innerHTML in every loop of $.each.
Try this:
var posturi = posts.likes;
var names = posturi.data.map(function(item) { return item.name; }).join(', ');
names will contain a comma separated list of names.

How can I hide or pass particular data in URL using router.navigate [duplicate]

I need to post some data to server in ajax call. I am binding data into json format and posting it to server:
var BookMarkData = JSON.stringify(postData);
self.app.router.navigate('#hotels/' + BookMarkData, true);
I want to show only 4 elements from postdata JSONArray in the url. But I need to pass entire data to server.
fetchResults: function(PostData) {
var self = this;
var postData = JSON.parse(hashedPostData);
.......
}
How can I pass entire information to fetch results by hiding some information in the url?
If you need to show only 4 elements from postdata I assume that it is an array. Use slice:
var bookMarkData = JSON.stringify(postData),
routeData = JSON.stringify(postData.slice(0, 4))
self.app.router.navigate('#hotels/' + bookMarkData, true);
bookMarkData still holds the the whole array.

Parse retrieve pointer from current user in javascript

In Parse I have the User table set up with a number of columns, most of which are Strings but one is a Pointer to another Parse Class. I want to use this pointer in a query
In Java I can access the pointer to use in my query as follows:
ParseUser currentUser = ParseUser.getCurrentUser();
ParseObject comParent = currentUser.getParseObject("ComParent");
In JavaScript I have tried using:
var currentUser = Parse.User.current();
var comParent = currentUser.get("ComParent");
But this returns undefined. What am I doing wrong?
According to the documentation:
"By default, when fetching an object, related Parse.Objects are not fetched. These objects' values cannot be retrieved until they have been fetched like so:"
var post = fetchedComment.get("parent");
post.fetch({
success: function(post) {
var title = post.get("title");
}
});
So you should write:
var currentUser = Parse.User.current();
var comParent = currentUser.get("ComParent");
comParent.fetch({
success: function(comParent) {
var name = comParent.get("Name");
alert(name); // this one will work
}
});
alert(comParent.get("Name")); // this one wont work, see below
Just remember that success is an asynchronous callback,as such comParent will not be available outside the success function as shown above, if you need to access comParent outside of success check out https://stackoverflow.com/a/27673839/1376624
Thanks. My issue was a combination of 2 things. Firstly, I was not correctly fetching the object as you rightly point out. Secondly, I was trying to fetch an object from a user which did not have an associated ComParent object (Doh!). Anyway, your solution put me onto the need to fetch the object but I don't think it is the currentUser that should have the fetch, it is comParent:
var currentUser = Parse.User.current();
var comParent = currentUser.get("ComParent");
comParent.fetch({
success: function(comParent) {
var name = comParent.get("Name");
alert(name);
}
});
Thanks again #DelightedD0D

Categories

Resources