How get data with jQuery.parseJSON - javascript

In page 1 I have this array:
$pole = array("countLike" => "countLike", "Message" => "Some message");
echo json_encode($pole);
And I want get this data on page 2, but this code doesn't work.
function Like(id)
{
$.post("page1.php", { action: "Like", "id": id }, function(data) {
var obj = jQuery.parseJSON(data);
$(".countLike#"+id).html(obj.countLike);
$(".Message#"+id).html(obj.Message);
});
}
Can you help me please with this code.
Thanks.

Pass json as expected output from the post request.
function Like(id)
{
$.post("page1.php", { action: "Like", "id": id }, function(data) {
//data is already a json parsed string
$(".countLike#"+id).html(data.countLike);
$(".Message#"+id).html(data.Message);
}, "json"); // <<<<< This is what you missed
}

Code should work making the request but there is an issue with your element selectors.
".countLike#"+id
".Message#"+id
The "#" is not space separated from the class name. Issue now becomes are you looking for elements with ID "#"+id? I suspect you are so you really don't need the class prefixing the ID at all and simply use
$('#' + id)
An Id selector is far faster for jQuery to search than class since there can only be one in the page.

Related

Why I can't access json properties with dot (.) operator while passing a var through $.getjson()

I have a $getJSON() that i want to pass a var through how ever i always get undefined in console log.
I have done this before i just cant seem to figure out why this isnt working.
Any help would be appreciated.
here is my example
{
"harry": {
"example": "test",
"example1": "test",
}
"james": {
"example": "test",
"example1": "test",
}
"ben": {
"example": "test",
"example1": "test",
}
}
var usersidno = $("#hiddenid").html();
$.getJSON(
"http://localhost/example/file.json",
function(json) {
console.log(json.usersidno);
});
<div id="hiddenid">harry</div>
When you want to access an object's (JSON) property dynamically (using a variable or expression), you should use square bracket notation.
[your expression or variable inside square brackets]. i.e, json[useridno]
var usersidno = $("#hiddenid").html();
$.getJSON(
"http://localhost/example/file.json",
function(json) {
console.log(json[usersidno]); // try to use square brackets
});
This is a working example of ,your issue I have used an api ,that gives back a json ,You can use [] annotatiton to access object properties.
$(document).ready(function(){
var user = $("#hiddenid").html()
console.log(typeof user)
$.getJSON(
"https://jsonplaceholder.typicode.com/todos/1",
function(json) {
let js=JSON.parse(JSON.stringify(json))
console.log(js[user]);
console.log(js.user);//undefined
console.log(js)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="hiddenid">userId</div>
Explanation:
var userid = 'userId';
console.log(x.userid); // it looks for x.userid, which throws undefined,if it does'nt exists
console.log(x[userid]); // looks for x['userId'] which it will find
Have a look at mdn docs

NightmareJs + Jquery return empty JSON response

Im trying to deal with testing tools likewise nightmare, phantom etc. And seems to be stuck with some basic DOM manipulation. Im using jquery here for later use of $().parent() methods. Ive already tryed all posiible selector that come in collection with no use. It only returns some pieces of data. Where it actually fully exists on a page.
....
nightmare
.goto(link)
.inject('js', 'jquery-2.2.4.min.js')
.wait()
.evaluate( () => {
$('.sport--head:not(.folding--open)').click()
})
.wait(4000)
.evaluate( () => {
let events = [];
$('.view-wrapper .events--list > li').each( (i, elem) => {
let event = {
'name' : $(elem).text()
}
events.push(event);
});
let data = JSON.stringify(events, null, '\t');
return data;
})
.end()
....
It returns empty fields where they are actually not:
[{ "name": "" }, { "name": "" }, { "name": "" }, { "name": "contents" } ]
Why could this happen? Any ideas?
You do not know the pages loads completely within 4 seconds.
Either there are some Ajax data and while you are scraping it appears only at that moment. Or, the selector is actually wrong.
Instead of a specific number, use .wait to wait for a target selector,
.wait(4000)
.wait('.view-wrapper .events--list > li')
Also make sure the code actually returns the data by putting it on console.log of your actual browser.

How to read from JSON in protractor test?

I would like to read groups_id_ss for specific id.
How to do that in this json?
I successfully read response.docs , but then can't reach id and groups_id_ss.
{
"responseHeader":{
"status":0,
"QTime":0,
"params":{
"q":"object_type_s:USER",
"indent":"true",
"wt":"json"
}
},
"response":{
"numFound":13,
"start":0,
"docs":[
{
"id":"sanja",
"groups_id_ss":[
"COORDINATION AO",
"ACM_INVESTIGATOR_DEV"
]
},
{
"id":"sanjaseconduser",
"groups_id_ss":[
"ACM_SUPERVISOR_DEV",
"CHAIRMAN",
"ACM_ADMINISTRATOR_DEV",
"CPC INITIATOR",
"COORDINATION AO",
"ACM_INVESTIGATOR_DEV"
]
}
]
}
}
As stated you could read response.docs from json. Let's say
var docs = response.docs;
As docs is an array you can use forEach to loop thruogh each element
docs.forEach(function(doc) {
if(doc.id === "desired_Id") {
var groupIdSS = doc.groups_id_ss;
}
});
This way you can read groups_id_ss for desired id.
Hope it helps.
Since you are using the values in separate file, you can use like this.
I am assuming the file is stored as .json
For example, your json values are in response.json
You can write code like this in your spec file:
var responseData = require('../../response.json');
describe('some function description', function(){
var groupID = responseData.response.docs[0].groupid_ss[0];
var groupID = responseData.response.docs[0].groupid_ss[0]
});
Since that is json array, we have to give the index of the array in that.
Hope this would work for you.

Knockout load another AJAX url to combine to model

I have some complex question.
My first JSON url has this properties, ID, Name and Parameter. Then when I call the JSON, I want to go to retrieve another JSON URL based on the ID to get the child ID.
Then I want to output as Child ID, Parent Name and Parent Parameter.
Here is the jsFiddle http://jsfiddle.net/c3L7gr4w/1/
And here is the model url 1
[
{
"ParemeterValues": "Actual,2011,SYS.LoadCompanies,y,y",
"ID": "1771cdf7-7a73-49e4-8538-0d0cad965226",
"Name": "EXEC.Data.PLandBS.FromFMISMultipleCompanies",
},
{
"ParemeterValues": "Actual,2012",
"ID": "19439ce4-240c-4f2a-98ee-47cb1708b339",
"Name": "Data.BS.BringForwardOpeningBalances",
}
]
and the model url2
{
"ID": "1771cdf7-7a73-49e4-8538-0d0cad965226",
"Name": "EXEC.Data.PLandBS.FromFMISMultipleCompanies",
"TM1.ChoreProcessesProcess":
[
{
"Name": "EXEC.Data.PLandBS.FromFMISMultipleCompanies",
"ID": "dd1acc0b-51ff-4844-b6c4-c67640b326c4",
}
]
}
I think you need to adjust your dataMappingOptions.key so that KO can return a different key when you load your child model in on top of your original.
I have a working fiddle here, I think - http://jsfiddle.net/sifriday/c3L7gr4w/4/
dataMappingOptions now looks like:
var dataMappingOptions = {
key: function(data) {
var ChildID = "";
if (data["TM1.ChoreProcessesProcess"] != undefined)
ChildID = data["TM1.ChoreProcessesProcess"][0].ID
return data.ID + ChildID;
},
create: function(options) {
return new Person(options.data);
}
};
The problem with this is that when you load your updatedData KO will now use the mapping to destroy your original people and create new ones. However, updatedData is missing the ParemeterValue, so you need to merge this in from your original JSON. This will be OK even when you are using Ajax, because you can save the original JSON in a variable somewhere:
loadUpdatedData: function() {
// You need to merge in paremeterValues from your orig JSON
updatedData[0].ParemeterValues = data[0].ParemeterValues;
// Now good to go...
ko.mapping.fromJS(updatedData, dataMappingOptions, viewModel.people);
}
(I've also done it so that ChildID is appended as an extra property, but you should be able to see from this how to make it replace the original ID in both the People view-model and in the dataMappingOptions.key)

Using JSON to get value

I want to select one specific property of a jason object.
This is the structure of the JSON:
{
"resultsPage:" {
"results": { "event": [
{
"id":11129128,
"type":"Concert",
"uri":"http://www.songkick.com/concerts/11129128-wild-flag-at-fillmore?utm_source=PARTNER_ID&utm_medium=partner",
"displayName":"Wild Flag at The Fillmore (April 18, 2012)",
"start":{"time":"20:00:00",
"date":"2012-04-18",
"datetime":"2012-04-18T20:00:00-0800"},
"performance":[{"artist":{"uri":"http://www.songkick.com/artists/29835-wild-flag?utm_source=PARTNER_ID&utm_medium=partner",
"displayName":"Wild Flag","id":29835,"identifier":[]},
"displayName":"Wild Flag",
"billingIndex":1,
"id":21579303,
"billing":"headline"}],
"location":{"city":"San Francisco, CA, US","lng":-122.4332937,"lat":37.7842398},
"venue":{"id":6239,
"displayName":"The Fillmore",
"uri":"http://www.songkick.com/venues/6239-fillmore?utm_source=PARTNER_ID&utm_medium=partner",
"lng":-122.4332937, "lat":37.7842398,
"metroArea":{"uri":"http://www.songkick.com/metro_areas/26330-us-sf-bay-area?utm_source=PARTNER_ID&utm_medium=partner",
"displayName":"SF Bay Area","country":{"displayName":"US"},"id":26330,"state":{"displayName":"CA"}}},
"status":"ok",
"popularity":0.012763
}, ....
]},
"totalEntries":24,
"perPage":50,
"page":1,
"status":"ok"
}
}
This is what I'm doing to get the JSON:
url: "http://api.songkick.com/api/3.0/artists/480448/calendar.json?apikey=APIKEY&jsoncallback=?",
dataType: "jsonp", // <== JSON-P request
success: function (data) {
$.each(data["resultsPage"]["results"]["event"], function (i, entry) {
$("#events").append('<li>' + entry.displayName + '</li>');
});
I'm new with JSON so my question is: How do I get the latitude and longitude of a location by entering an artist name out this JSON object? Any Idea?
You would use entry.location.lng and entry.location.lat inside your $.each() function.
each property, if not an array, can be accessed with dot notation, which most people find easier to read and understand. meaning, your $.each() could also be defined like this :
$.each(data.resultsPage.results.event, function (i, entry) {
Hope that helps...
If you have to match a given property value, then you're going to have to crawl and check for it.
for ( loop events )
if ( select Name = thing you want )
do my stuff

Categories

Resources