PHP Simple HTML DOM Parser for JavaScript Code Within the Page - javascript

I'm using PHP Simple DOM Parser, the HTML part is working as expected, but some of the content of the web page is shown with JavaScript. The JavaScript is within the HTML page not a separate file and the information I need is clear, in plain text.
This is how the JavaScript code starts, the information needed is in the end (location):
<script id="state">
window.__INITIAL_STATE__ = {
"detail": {
"listingTopNavigation": {},
"isTracked": false,
"id": 30279925,
"isImported": false,
"isErotic": false,
"isMessengerEnabled": false,
"categories": [{
"name": "Musique - Instruments",
"id": 23,
"isErotic": false
}, {
"name": "Guitares & Accessoires",
"id": 697,
"isErotic": false
}, {
"name": "Electrique",
"id": 2354,
"isErotic": false
}],
"imageData": {
"baseUrl": "https:\u002F\u002Fcan01.anibis.ch\u002FElectrique-Line-6-DL-4-Delay-Modeler",
"images": ["\u002F?[size]\u002Fanibis\u002F925\u002F279\u002F030\u002FLSmd7oN9LU6lAP5EbJQXXg_1.jpg", "\u002F?[size]\u002Fanibis\u002F925\u002F279\u002F030\u002Fhn2lNMOudUmuZofpM7wrsg_1.jpg", "\u002F?[size]\u002Fanibis\u002F925\u002F279\u002F030\u002FJKBbte21vEaD7ZJqcMi_Qg_1.jpg"]
},
"title": "Line 6 DL 4 Delay Modeler",
"description": "\u003Cp\u003EVerkaufe mein Delay DL 6 in absolut neuwertigem Zustand wegen Nichtgebrauch. Das Delay habe ich im Dezember 2018 neu bei Musix gekauft und verfügt über eine tolle Auswahl an Delay Effekten, welche auf Fender Gibson Marshall oder Vox in Extraklasse daherkommen. Das Gerät ist optisch und technisch absolut neuwertig, kommt in Originalverpackung und mit dem passenden Netzadapter von Line 6. \u003C\u002Fp\u003E\n",
"price": 190,
"offerType": "Offer",
"formattedPrice": "CHF 190.–",
"formattedModified": "19.08.2019",
"details": [{
"name": "Remise",
"value": "Retrait et envoi "
}, {
"name": "Type d’annonce",
"value": "Offre"
}],
"location": {
"country": "Suisse",
"state": "Soleure",
"zipCity": "4625 Oberbuchsiten (SO)"
},
How can I get these values in PHP variables to use after.
$country = $html->find(...);
$state = $html->find(...);
$zip_city = $html->find(...);
Thanks.

if ($html) {
if ($html->find('script[id=state]', 0)) {
$script = $html->find('script[id=state]', 0);
$script = ltrim($script, '<script id="state">window.__INITIAL_STATE__=');
$script = rtrim($script, '</script>');
$obj = json_decode($script, true);
if (isset($obj['detail']['contact']['phone'])) {
$tel = $obj['detail']['contact']['phone'];
$tel = ltrim($tel, '+41 ');
if (isset($obj['detail']['location']['street']))
$address = trim($obj['detail']['location']['street']);
if (isset($obj['detail']['location']['zipCity']))
$npa_ville = trim($obj['detail']['location']['zipCity']);
$npa_ville = explode(' ', $npa_ville, 2);
$npa = preg_replace('/[^0-9]/', '', $npa_ville[0]);
$ville = $npa_ville[1];

Related

How clean the javascript object by replace() in javascript

I have a object in this format
{"paymethod_id":1,"business_id":76,"delivery_type":"1","driver_tip":0,"delivery_zone_id":6569,"delivery_datetime":null,"location":{"lat":18.7675049,"lng":-103.1445221},"deliveryOptionmodal":{"id":3,"value":"Sin contacto/Dejar orden en la puerta","$$hashKey":"object:272"},"delivery_cost_new":10,"products":{"name":"Product"},"customer_id":35,"customer":"{\"id\":35,\"name\":\"Hong Kong\",\"middle_name\":null,\"lastname\":\"\",\"second_lastname\":null,\"photo\":\"https://res.cloudinary.com/ordering2/image/upload/v1551225299/taomauvuhrrowqqp3ncp.png\",\"email\":\"hongkongpide#gmail.com\",\"cellphone\":\"4433413248\",\"address\":\"Coalcomán, Mich., México\",\"location\":\"{\\\"lat\\\":18.7675049,\\\"lng\\\":-103.1445221}\",\"internal_number\":null,\"address_notes\":null,\"zipcode\":null,\"map_data\":{\"library\":\"google\",\"place_id\":\"ChIJz6WGrUw-MIQR_jYIoFZ-RPM\"},\"tag\":\"home\"}","business_name":"Soporte Devy"}
Which is not easily readable is there any way i can clean this object and see like this
business_name: Sport Devy
name: hong kong
I just want to clean the object and convert it into representable form
You could write a function to transform it into the format you want. I am not sure if you specifically want it as a string or as a different object. I am outputting a string but you could modify this to return an object if that is what you need.
function formatDisplay(obj) {
const bname = obj.business_name;
const customer = JSON.parse(obj.customer || "{}");
const name = customer && customer.name;
/* If you need object:
return {
business_name: bname,
name: name
};
*/
return [
"business name: "+ bname,
"name: " + name,
].join("\n");
};
const data = {"paymethod_id":1,"business_id":76,"delivery_type":"1","driver_tip":0,"delivery_zone_id":6569,"delivery_datetime":null,"location":{"lat":18.7675049,"lng":-103.1445221},"deliveryOptionmodal":{"id":3,"value":"Sin contacto/Dejar orden en la puerta","$$hashKey":"object:272"},"delivery_cost_new":10,"products":{"name":"Product"},"customer_id":35,"customer":"{\"id\":35,\"name\":\"Hong Kong\",\"middle_name\":null,\"lastname\":\"\",\"second_lastname\":null,\"photo\":\"https://res.cloudinary.com/ordering2/image/upload/v1551225299/taomauvuhrrowqqp3ncp.png\",\"email\":\"hongkongpide#gmail.com\",\"cellphone\":\"4433413248\",\"address\":\"Coalcomán, Mich., México\",\"location\":\"{\\\"lat\\\":18.7675049,\\\"lng\\\":-103.1445221}\",\"internal_number\":null,\"address_notes\":null,\"zipcode\":null,\"map_data\":{\"library\":\"google\",\"place_id\":\"ChIJz6WGrUw-MIQR_jYIoFZ-RPM\"},\"tag\":\"home\"}","business_name":"Soporte Devy"};
console.log(formatDisplay(data));
const obj = {
"paymethod_id": 1,
"business_id": 76,
"delivery_type": "1",
"driver_tip": 0,
"delivery_zone_id": 6569,
"delivery_datetime": null,
"location": {
"lat": 18.7675049,
"lng": -103.1445221
},
"deliveryOptionmodal": {
"id": 3,
"value": "Sin contacto/Dejar orden en la puerta",
"$$hashKey": "object:272"
},
"delivery_cost_new": 10,
"products": {
"name": "Product"
},
"customer_id": 35,
"customer": "{\"id\":35,\"name\":\"Hong Kong\",\"middle_name\":null,\"lastname\":\"\",\"second_lastname\":null,\"photo\":\"https://res.cloudinary.com/ordering2/image/upload/v1551225299/taomauvuhrrowqqp3ncp.png\",\"email\":\"hongkongpide#gmail.com\",\"cellphone\":\"4433413248\",\"address\":\"Coalcomán, Mich., México\",\"location\":\"{\\\"lat\\\":18.7675049,\\\"lng\\\":-103.1445221}\",\"internal_number\":null,\"address_notes\":null,\"zipcode\":null,\"map_data\":{\"library\":\"google\",\"place_id\":\"ChIJz6WGrUw-MIQR_jYIoFZ-RPM\"},\"tag\":\"home\"}",
"business_name": "Soporte Devy"
}
business_name can be read directly from the object - obj.business_name. customer node needs to parsed into javascript object; for that you can use JSON.parse(obj.customer)

Javascript: Parse array of json objects within a string

I have an array of json object within a string:
[
{
"title": "Ham on Rye",
"alternativeTitles": [],
"secondaryYearSourceId": 0,
"sortTitle": "ham on rye",
"sizeOnDisk": 0,
"status": "released",
"overview": "A bizarre rite of passage at the local deli determines the fate of a generation of teenagers, leading some to escape their suburban town and dooming others to remain…",
"inCinemas": "2019-08-10T00:00:00Z",
"images": [
{
"coverType": "poster",
"url": "http://image.tmdb.org/t/p/original/px7iCT1SgsOOSAXaqHwP50o0jAI.jpg"
}
],
"downloaded": false,
"remotePoster": "http://image.tmdb.org/t/p/original/px7iCT1SgsOOSAXaqHwP50o0jAI.jpg",
"year": 2019,
"hasFile": false,
"profileId": 0,
"pathState": "dynamic",
"monitored": false,
"minimumAvailability": "tba",
"isAvailable": true,
"folderName": "",
"runtime": 0,
"tmdbId": 527176,
"titleSlug": "ham-on-rye-527176",
"genres": [],
"tags": [],
"added": "0001-01-01T00:00:00Z",
"ratings": {
"votes": 5,
"value": 6.9
},
"qualityProfileId": 0
}
]
When I try to parse my array of json objects, it always returns a string, so when I try to access it by:
let data = JSON.parse(JSON.stringify(jsonData));
console.log(data[0].title)
it returns a specific character like "[", as if it was a string.
Te problem is that you are stringifying something that is already a JSON string.
Change this:
let data = JSON.parse(JSON.stringify(jsonData));
to this:
let data = JSON.parse(jsonData);

How can i use the function ng-click in my case?

I have a div with pictures who change every 9 seconds, i want to keep it but i want to change the picture when user click on. I think the most easy is to use the ng-click function, but i don't know how
My code :
In the HTLM :
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12 session fondbleuSession">
<div>
<div ng-controller="eventCtrl">
<div ng-repeat="data in event" ng-if="data.id == actualSession">
<div class="sessionTxt">
<h1>{{data.title}} </h1>
<p>{{data.description}} </p>
</div>
<!-- ng-click here ? --> <a ng-href="{{data.url}}" class="sessionImg" ng-style="{'background-image':'url({{data.src}})'}" >
</a>
</div>
</slider>
</div>
</div>
</div>
And
In eventCtrl
app.controller('eventCtrl', function($scope, $interval) {
$scope.actualSession = 0;
var sessionLength = 0;
// INFORMATION GENERAL EVENT
// id = reference de l'image pour l'ordre de passage (+1 a chaque nouveau slide ajouté)
// title = titre de l'event
// description = resume rapide de l'event
// src = adresse de l'image
// url = lien de redirection vers article/sharepoint...
$scope.event = [
{
"id": 1,
"title": "Site Events",
"description": "",
"src": "images/index/event/Photo1.jpg",
"url": ""
},
{
"id": 2,
"title": "Site Events",
"description": "",
"src": "images/index/event/Photo2.jpg",
"url": ""
},
{
"id": 3,
"title": "Site Events",
"description": "",
"src": "images/index/event/Photo3.jpg",
"url": ""
},
{
"id": 4,
"title": "Site Events",
"description": "",
"src": "images/index/event/Photo4.jpg",
"url": ""
},
{
"id": 5,
"title": "Site Events",
"description": "",
"src": "images/index/event/Photo5.jpg",
"url": ""
}
];
sessionLength = _.size($scope.event);
$interval(function() {
$scope.actualSession = $scope.actualSession + 1;
if ($scope.actualSession == sessionLength) {
$scope.actualSession = 0;
}
}, 9000); //timer switch event (1000 = 1 seconde)
})
And i don't know if it's possible to have this two function : change the picture automatically after x seconds and change the picture when the user click.
Furthermore, i don't know who to go to the first picture when we come on the last picture
Thank you very much and have a nice day
Try wraping a div around the anchor tag and use ng-click there, hopefully it should work.
If you're looking to change the actionSession variable, it should be straightforward:
ng-click="ctrl.someFunc()"
Then in the controller:
someFunc() {
$scope.actualSession = $scope.actualSession === sessionLength - 1 ? 0 : $scope.actualSession++;
}

Get JSON array (API) where object is in object with Javascript

I am using the code below to build a table based on an API and am fine when there is in object in an array (e.g. lineStatuses[0].statusSeverityDescription), however when there is an object, in an object, in an array, it does not work and I get the result [object Object] returned.
Here is a sample of the JSON data from the URL (I am expecting Undefined to be returned for the first record):
[
{
"$type": "Tfl.Api.Presentation.Entities.Line, Tfl.Api.Presentation.Entities",
"id": "bakerloo",
"name": "Bakerloo",
"modeName": "tube",
"disruptions": [],
"created": "2016-06-03T12:36:54.19Z",
"modified": "2016-06-03T12:36:54.19Z",
"lineStatuses": [
{
"$type": "Tfl.Api.Presentation.Entities.LineStatus, Tfl.Api.Presentation.Entities",
"id": 0,
"statusSeverity": 10,
"statusSeverityDescription": "Good Service",
"created": "0001-01-01T00:00:00",
"validityPeriods": []
}
],
"routeSections": [],
"serviceTypes": [
{
"$type": "Tfl.Api.Presentation.Entities.LineServiceTypeInfo, Tfl.Api.Presentation.Entities",
"name": "Regular",
"uri": "/Line/Route?ids=Bakerloo&serviceTypes=Regular"
}
]
},
{
"$type": "Tfl.Api.Presentation.Entities.Line, Tfl.Api.Presentation.Entities",
"id": "central",
"name": "Central",
"modeName": "tube",
"disruptions": [],
"created": "2016-06-03T12:36:54.037Z",
"modified": "2016-06-03T12:36:54.037Z",
"lineStatuses": [
{
"$type": "Tfl.Api.Presentation.Entities.LineStatus, Tfl.Api.Presentation.Entities",
"id": 0,
"lineId": "central",
"statusSeverity": 5,
"statusSeverityDescription": "Part Closure",
"reason": "CENTRAL LINE: Saturday 11 and Sunday 12 June, no service between White City and Ealing Broadway / West Ruislip. This is to enable track replacement work at East Acton and Ruislip Gardens. Replacement buses operate.",
"created": "0001-01-01T00:00:00",
"validityPeriods": [
{
"$type": "Tfl.Api.Presentation.Entities.ValidityPeriod, Tfl.Api.Presentation.Entities",
"fromDate": "2016-06-11T03:30:00Z",
"toDate": "2016-06-13T01:29:00Z",
"isNow": false
}
],
"disruption": {
"$type": "Tfl.Api.Presentation.Entities.Disruption, Tfl.Api.Presentation.Entities",
"category": "PlannedWork",
"categoryDescription": "PlannedWork",
"description": "CENTRAL LINE: Saturday 11 and Sunday 12 June, no service between White City and Ealing Broadway / West Ruislip. This is to enable track replacement work at East Acton and Ruislip Gardens. Replacement buses operate.",
"additionalInfo": "Replacement buses operate as follows:Service A: White City - East Acton - North Acton - West Acton - Ealing Common (for District and Piccadilly Lines) - Ealing BroadwayService B: White City - North Acton - Northolt - South Ruislip - Ruislip Gardens - West RuislipService C: White City - North Acton - Park Royal (Piccadilly Line) - Hanger Lane - Perivale - Greenford - Northolt",
"created": "2016-05-12T11:04:00Z",
"affectedRoutes": [],
"affectedStops": [],
"isBlocking": true,
"closureText": "partClosure"
}
}
],
"routeSections": [],
"serviceTypes": [
{
"$type": "Tfl.Api.Presentation.Entities.LineServiceTypeInfo, Tfl.Api.Presentation.Entities",
"name": "Regular",
"uri": "/Line/Route?ids=Central&serviceTypes=Regular"
}
]
}
]
I am also trying to use setInterval to refresh the tube-disruption DIV with updated data from the API, which is not workng. Below is the code (with the URL returning some of the JSON data above). Any ideas what I am doing wrong?
var xmlhttp = new XMLHttpRequest();
var url = "https://api.tfl.gov.uk/line/mode/tube/status";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunctionDisruption(xmlhttp.responseText);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
setInterval(myFunctionDisruption, 600000);
function myFunctionDisruption(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].lineStatuses[0].disruption.description + <!-- DOES NOT WORK -->
"</td></tr>";
}
out += "</table>";
document.getElementById("tube-disruption").innerHTML = out;
}
The below code will generate a table for you. The generic tableMaker function takes an array of an object or an array of multiple objects provided in the first argument. All objects should have same keys (properties) since these keys are used to create the table header (if the second argument is set to true) and the values are used to create each row. It will return an HTML table text. You can see the tableMaker function working with a smaller size data at here. You can also practice it with some sample and simple data you may produce.
In your case you have multiple nested objects those, I guess, need to be converted into separate tables within the corresponding cells of the main table. For that purpose i have another function tabelizer which handles this job recursively by utilizing the tableMaker function. The result of tabelizer is a complete HTML text of your master table.
Lets see
var tableMaker = (o,h) => {var keys = o.length && Object.keys(o[0]),
rowMaker = (a,t) => a.reduce((p,c,i,a) => p + (i === a.length-1 ? "<" + t + ">" + c + "</" + t + "></tr>"
: "<" + t + ">" + c + "</" + t + ">"),"<tr>"),
rows = o.reduce((r,c) => r + rowMaker(keys.reduce((v,k) => v.concat(c[k]),[]),"td"),h ? rowMaker(keys,"th") : []);
return rows.length ? "<table>" + rows + "</table>" : "";
},
data = [
{
"$type": "Tfl.Api.Presentation.Entities.Line, Tfl.Api.Presentation.Entities",
"id": "bakerloo",
"name": "Bakerloo",
"modeName": "tube",
"disruptions": [],
"created": "2016-06-03T12:36:54.19Z",
"modified": "2016-06-03T12:36:54.19Z",
"lineStatuses": [
{
"$type": "Tfl.Api.Presentation.Entities.LineStatus, Tfl.Api.Presentation.Entities",
"id": 0,
"statusSeverity": 10,
"statusSeverityDescription": "Good Service",
"created": "0001-01-01T00:00:00",
"validityPeriods": []
}
],
"routeSections": [],
"serviceTypes": [
{
"$type": "Tfl.Api.Presentation.Entities.LineServiceTypeInfo, Tfl.Api.Presentation.Entities",
"name": "Regular",
"uri": "/Line/Route?ids=Bakerloo&serviceTypes=Regular"
}
]
},
{
"$type": "Tfl.Api.Presentation.Entities.Line, Tfl.Api.Presentation.Entities",
"id": "central",
"name": "Central",
"modeName": "tube",
"disruptions": [],
"created": "2016-06-03T12:36:54.037Z",
"modified": "2016-06-03T12:36:54.037Z",
"lineStatuses": [
{
"$type": "Tfl.Api.Presentation.Entities.LineStatus, Tfl.Api.Presentation.Entities",
"id": 0,
"lineId": "central",
"statusSeverity": 5,
"statusSeverityDescription": "Part Closure",
"reason": "CENTRAL LINE: Saturday 11 and Sunday 12 June, no service between White City and Ealing Broadway / West Ruislip. This is to enable track replacement work at East Acton and Ruislip Gardens. Replacement buses operate.",
"created": "0001-01-01T00:00:00",
"validityPeriods": [
{
"$type": "Tfl.Api.Presentation.Entities.ValidityPeriod, Tfl.Api.Presentation.Entities",
"fromDate": "2016-06-11T03:30:00Z",
"toDate": "2016-06-13T01:29:00Z",
"isNow": false
}
],
"disruption": {
"$type": "Tfl.Api.Presentation.Entities.Disruption, Tfl.Api.Presentation.Entities",
"category": "PlannedWork",
"categoryDescription": "PlannedWork",
"description": "CENTRAL LINE: Saturday 11 and Sunday 12 June, no service between White City and Ealing Broadway / West Ruislip. This is to enable track replacement work at East Acton and Ruislip Gardens. Replacement buses operate.",
"additionalInfo": "Replacement buses operate as follows:Service A: White City - East Acton - North Acton - West Acton - Ealing Common (for District and Piccadilly Lines) - Ealing BroadwayService B: White City - North Acton - Northolt - South Ruislip - Ruislip Gardens - West RuislipService C: White City - North Acton - Park Royal (Piccadilly Line) - Hanger Lane - Perivale - Greenford - Northolt",
"created": "2016-05-12T11:04:00Z",
"affectedRoutes": [],
"affectedStops": [],
"isBlocking": true,
"closureText": "partClosure"
}
}
],
"routeSections": [],
"serviceTypes": [
{
"$type": "Tfl.Api.Presentation.Entities.LineServiceTypeInfo, Tfl.Api.Presentation.Entities",
"name": "Regular",
"uri": "/Line/Route?ids=Central&serviceTypes=Regular"
}
]
}
],
tabelizer = (a) => a.length ? tableMaker(a.map(e => Object.keys(e).reduce((p,k) => (p[k] = Array.isArray(e[k]) ? tabelizer(e[k]) : e[k],p),{})),true)
: "",
tableHTML = tabelizer(data);
document.write(tableHTML);
I used arrow functions but they might not work at Safari or IE. You might need to convert them to the conventional function notation.
You can also try the code out at repl.it where you can see the HTML text displayed through console.log.

How to get "source" from JSON object

I'm trying to build a custom Facebook page feed into my website. When the posts on the Facebook page have only images it works great, but when they have videos we've got a problem. What I would like to happen is a mini version of the video to be place as it was an image itself. However I'm a newbie to the graph api, because of that I don't know how to grab the "source" element of the posts that have video on them.
Here is how the JSON objetc looks like:
{
"name": "Patrick Oliveira",
"picture": {
"data": {
"is_silhouette": false,
"url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xft1/v/t1.0-1/c13.0.50.50/p50x50/11694800_709940652467661_5760283552162746065_n.jpg?oh=8ce289debf38df76b1a8ad72e9e32950&oe=5641D882&__gda__=1447414822_01484acd6dcdb29c62a7278a140bb592"
}
},
"posts": {
"data": [
{
"full_picture": "https://fbcdn-sphotos-a-a.akamaihd.net/hphotos-ak-xft1/v/t1.0-9/p417x417/11873451_734632043331855_4522184841179328970_n.jpg?oh=67bd84af22a94bc59a2996ff8fa0a8d8&oe=563F7BE8&__gda__=1447502842_a29144ab596e29d3d92d2239d376adc9",
"message": "Lan\u00e7ado em fevereiro de 1990, o Photoshop completa 25 anos como o programa de edi\u00e7\u00e3o de imagens mais famoso do mundo. Parab\u00e9ns Adobe!",
"created_time": "2015-08-14T20:52:08+0000",
"id": "213578595437205_734632043331855"
},
{
"full_picture": "https://scontent.xx.fbcdn.net/hphotos-xft1/v/t1.0-9/q81/s720x720/11415380_700706213391105_871834721491614634_n.jpg?oh=8672f7ae4931323baaf012e5f57a6079&oe=567F5D35",
"message": "\"Agora eu sei de que \u00e9 feito aquele ch\u00e3o\".\n-- cliente",
"created_time": "2015-07-04T20:05:01+0000",
"id": "213578595437205_700706213391105"
},
{
"full_picture": "https://fbcdn-sphotos-f-a.akamaihd.net/hphotos-ak-xpt1/v/t1.0-9/s720x720/11406889_700700410058352_5592320885219405365_n.jpg?oh=acedee420f8e4944201c714e30f70627&oe=5679534C&__gda__=1451225194_477268223eedc2217b2ae1dcdd345399",
"message": "Levante que hoje \u00e9 Sexta!",
"created_time": "2015-07-03T09:27:01+0000",
"id": "213578595437205_700700410058352"
},
{
"full_picture": "https://fbexternal-a.akamaihd.net/safe_image.php?d=AQBxQzu6zRD6fM_d&w=720&h=720&url=http\u00253A\u00252F\u00252Fi.ytimg.com\u00252Fvi\u00252F2K9eMZyD5jc\u00252Fmaxresdefault.jpg&cfs=1",
"message": "Ferramenta poderosa pra quem trabalha com fotos de arquitetura, o Adaptive Wide Angle pode ser um poderoso aliado!\nhttps://www.youtube.com/watch?v=2K9eMZyD5jc",
"created_time": "2015-07-02T18:25:01+0000",
"source": "http://www.youtube.com/v/2K9eMZyD5jc?version=3&autohide=1&autoplay=1",
"id": "213578595437205_700700186725041"
},
{
"full_picture": "https://fbcdn-sphotos-b-a.akamaihd.net/hphotos-ak-xft1/v/t1.0-9/s720x720/541646_700699430058450_5858057325981612930_n.jpg?oh=24a5d3e03cf1f782262e0b72d04831b4&oe=567999FA&__gda__=1451117341_93c352ddfa2804fa4047d84ab94978d9",
"message": "Come\u00e7ando o m\u00eas de Julho com o p\u00e9...",
"created_time": "2015-07-01T10:23:00+0000",
"id": "213578595437205_700699430058450"
}
],
"paging": {
"previous": "https://graph.facebook.com/v2.4/213578595437205/posts?limit=5&fields=full_picture,message,created_time,source&since=1439585528&access_token=1641569939420394|NyfBDunYwpFoZrtAoCSfqTV2-uU&__paging_token=enc_AdDQS8eEeKGQ3tvUJJxS1kyUXRwabHz2C1GZA0QZCufpZCHklYUI76WLCrigOB3IT1yxUtsCvx60ZA2haPnZA2Xoc2BOvPOLkM9eZBrbbrV1A87hVgIgZDZD&__previous=1",
"next": "https://graph.facebook.com/v2.4/213578595437205/posts?limit=5&fields=full_picture,message,created_time,source&access_token=1641569939420394|NyfBDunYwpFoZrtAoCSfqTV2-uU&until=1435746180&__paging_token=enc_AdAVBcOniyc1nbopw3Gr3CkmZB1pUDYBmZBghDmQXLunZBbvcuO1xttx6vpnkZBskAawu1sdcfh6qZCrU3sZA5MzZAkRQMT2VALYxOkCJOQZCm38ebDd2wZDZD"
}
},
"id": "213578595437205"
}
The fourth post is a video post, so I thought maybe I could generate a smaller video feed if I could grab that video source there.
Here is what I've been trying to do:
$.getJSON("https://graph.facebook.com/"+$page_id+"/?fields=name,picture,posts{full_picture,message,created_time}&access_token="+$access_token, function(fb) {
fb.posts.data[3].source;
});
However, the only thing I get from that is "undefined". If I do fb.posts.data[3].message or fb.posts.data[3].created_time or any of the other options it works, just for source that it returns "undefined". What am I doing wrong?
I found out what was wrong, so stupid. The request URL was missing the source element. So with this it works:
$.getJSON("https://graph.facebook.com/"+$page_id+"/?fields=name,picture,posts{full_picture,message,created_time,source}&access_token="+$access_token, function(fb) {
fb.posts.data[3].source;
});
I'm sorry for the mistake, it was my bad.

Categories

Resources