Grab data from JSON using JSON data as var - javascript

I trying to grab the url of an attached photo using json. Im using the value of the data from the json "HousePhoto1". I then want to use that value to grab the value from the post_media data. This is what im using at the moment, but my javascript doesn't load correctly when I try this, but if i take to .guid away, my page loads but without any json data. I have also added a photo of my json.
$.getJSON( "https://example.co.uk/wp-json/wp/v2/posts?&per_page=1&page=1", function( data ) {
$.each( data, function( key, val ) {
var photo = val.post_media[val.HousePhoto1].guid;
});
});
<img src="'+photo+'"/>
Image of my json

You were almost there. However, it looks like you are receiving an array back from your JSON response. Using a simplified dataset as my example, you can probably do something like this:
var data = [
{
HousePhoto1: "7073",
post_media: {
7073: {
guid: "https://somecoolphoto.com"
}
}
},
{
HousePhoto1: "7085",
post_media: {
7085: {
guid: "https://anothercoolphoto.com"
}
}
},
];
$.each(data, function(index, value) {
var housePhotoId = value.HousePhoto1;
var photo = value.post_media[housePhotoId].guid;
});
Also, if you are attempting to set multiple images, you cannot do it the way you currently are. You should dynamically insert the image into the DOM inside each iteration of the each loop via JavaScript.

Related

OData get URI of individual Entity

I'm developing in SAPUI5 and I'm retrieving an EntitySet via an OData read function. My code looks like this:
oDataModel.read("/Products", {
success: function(oData) {
oData.results.forEach(function(element, index, array) {
*// Here I want to get the Request URI for this specific element*
});
}
});
In the forEach function I want to retrieve the URI for the specific Entity from the EntitySet.
So for example I want to retrieve the URI like this:
"/Products(ID='1')"
"/Products(ID='2')"
Is this possible?
You could simply get the URL by creating it with the Entity Key values.
oDataModel.read("/Products", {
success: function(oData) {
oData.results.forEach(function(element, index, array) {
var sEntity = "/Products(ID='"+element.ID+"')";
});
}
});

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

pass collection of objects through http post in angular js

I have pass a collection of objects through http post in angular js.
The code is as follows:
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data.ContentId, { Selected: true }); // I could able to get all the selected objects here, No problem with it
var jsonData = angular.toJson(contents); //It is not able to convert to Json if there are more than 5 records
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent?jsonData=' + jsonData, {});
promise.success(function () {
window.location.reload();
});
[ReferrerFilterAttribute]
[HttpPost]
[System.Web.Http.ActionName("CmsPublishApprovedContent")]
public void CmsPublishApprovedContent(string jsonData)
{
var contents = JsonConvert.DeserializeObject<List<ContentNodeInWorkFlow>>(jsonData);
foreach (var content in contents)
{
_contentService.PublishContent(content.ContentId, userId);
}
}
}
The above code works fine if there are 5 records or less. If there are more records, I could able to get all the selected record
objects in the variable 'contents'. But the problem is occuring when converting to Json for all those objects. I
have about 500 records to pass through. How can do I it?
There is no specific reason to convert to JSON data. I just need to extract the ids of all the selected items. I have modified the above code as below:
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data, { Selected: true });
var abc = [];
angular.forEach(contents, function(content)
{
abc.push(content.ContentId); // got all the ids in the array now
});
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent' ,{contents : abc});
promise.success(function () {
window.location.reload();
});
}
I have just took an array and pushed all the content ids into it. I could able to see all the ids in the array now. I tried to pass the array as above.
How to retrieve those array in the code behind.
[ReferrerFilterAttribute]
[HttpPost]
[System.Web.Http.ActionName("CmsPublishApprovedContent")]
public void CmsPublishApprovedContent(int[] abc)
{}
I do not see any values obtained under int[] abc. What will be the datatype for the parameter in the method call above.
You need second argument of $http.post method. You have to send such data by POST requests, not in query of url. You can put some data into body of the post request.
You need this:
var postBodyWithHugeAmountOFData = {data: [1,2,3,4,5...500]};
$http.post(url, postBodyWithHugeAmountOFData).success(function () {});
Also, you must be ready to handle this request in your backend.
is there any specific reason u want to pass this data as a JSON?.
if u r using Web API in that case u can pass the object as it is but only make sure that collection in web API method contains all the property in javascript collection
Thank you for all your posts. It's working fine without converting to Json. The code is as below.
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data, { Selected: true });
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent' ,contents);
promise.success(function () {
window.location.reload();
});
}
and the signature would be
public void CmsPublishApprovedContent(List<ContentNodeInWorkFlow> abc)
{
}

Passing variable to Flask from Javascript and then loading template

In my Flask app--I'm pretty new to Flask--, I'm getting the values for client's latitude and longitude with Javascript and then passing a formatted string to a flask view. The view is supposed to pass the string to an online API and obtain a JSON object. It then converts it to a dictionary and displays certain values on a new page. I'm having trouble with loading the page from the view after I pass it the variables from the Javasctipt function. I know that it returns a result (I tried using Javascript's alertto display the resulting html), but return rendered_template() doesn't load the new page for some reason. I wonder if that's even possible to achieve. Thanks.
Javascript:
function getLocation(){
if("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(transferFile);
}
}
function transferFile(position){
var start = 'lat=';
var result = start.concat(position.coords.latitude, '&lon=', position.coords.longitude, '&format=json');
$.get(
url="phony",
data= result,
success=function(data) {
;
}
);
}
And here's the Flask part:
#app.route('/phony')
def phony():
query = request.query_string
url = <link to API> + query
location_dict = requests.get(url).json()
return render_template("phony.html", location_data = location_dict)
Your current call to $.get doesn't do anything with the result in the success callback
success: function(data) {
;
}
data contains the output from render_template('phone.html', location_data=location_dict). You need to add it to the page.
success: function(data) {
$('#some-selector').html(data);
}
That will replace the contents of an element matching #some-selector with the output. If the output contains a new HTML document (i.e., it's wrapped in an html tag), you'll want to replace the entire DOM. You can do that with something like
success: function(data) {
$('html').replaceWith(data);
}

Read a json file and save the data (as json) in list

I am new to JavaScript and I'm trying to read data from a file and save it in list so that I can retrieve it later. Something like:
sample.json
{
"circles": [
{"x":14,"y":2,"z":4,"r":50},
{"x":14,"y":2,"z":4,"r":50}
]
}
What I am looking for is:
var circle_list = []
circle_lst = some_function_which_reads_json_from_file('sample.json')
//Now circle list contains
circle_list = [
{"x":14,"y":2,"z":4,"r":50},
{"x":14,"y":2,"z":4,"r":50}
]
Later I can just do something like:
for (var i = 0; i <circle_list.lenght;i++){
//do osmething
}
I was looking into
$.getJSON("sample.json" , function(data){
//
});
But then I came to know this call is asynchronous... But I need to maintain execution order.
Don't maintain execution order. This will lock up the browser during the fetching. Use this only as an absolute last resort:
var circle_list;
$.ajax({'dataType': 'json', url: 'sample.json', 'async': false})
.done(function(json) {
circle_list = json;
});
Instead, you can do at least a couple of other things:
Work with callback. It doesn't have to all be in one spot thanks to deferreds.
Load the JSON along with the rest of the page and fetch it from the DOM.

Categories

Resources