wordpress JSON API Uncaught SyntaxError: Unexpected token <script - json

I am using the wordpress JSON API to make an android app with angularJS. I am using the following code, and everything works fine.
$http.jsonp(WORDPRESS_API_URL + 'get_post/' +
'?post_id='+ postId +
'&callback=JSON_CALLBACK')
.success(function(data) {
deferred.resolve(data);
})
.error(function(data) {
deferred.reject(data);
});
But in some pages of my wp site I use the jplayer module, which places this code at the <head>
<script>
var MP3jPLAYLISTS = [];
var MP3jPLAYERS = [];
</script>
This <script> tag comes along with the JSON return like this
<script>
var MP3jPLAYLISTS = [];
var MP3jPLAYERS = [];
</script>
angular.callbacks._2({"status":"ok","post": ....
which gives the Unexpected token
Any help is much appreciated!

You must build JSON API which will provide only JSON.
You have words JSON API in your question. API, answers of your API, must be JSON-valid. That means, that responses can only have headers and JSON data:
{"data": {"items": [1, 2, 3]}}
This is correct JSON.
In your case, response contains some HTML tags. It is not valid json, so your JSON request fails.

I found a solution, not so elegant but it works. I am writting it here just in case someone has the same problem.
The problem arises by the jplayer module. So in main.php file of this module you can make the following change:
function defineJSvars ()
{
if ( ! $this->JSvars ) {
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$pos = strpos($actual_link, "api/get_");
if ($pos == ""){
echo "\n<script>";
echo "\nvar MP3jPLAYLISTS = [];";
echo "\nvar MP3jPLAYERS = [];";
echo "\n</script>\n";
}
$this->JSvars = true;
}
}

Related

Pass a random JSON pair into an aframe component

Edit 3: The code is now working across numerous objects (thanks to Noam) and he has also helped in getting the random function working alongside it. I'll update the code in the question once its implemented.
Edit 2: I've taken #Noam Almosnino's answer and am now trying to apply it to an Array with numerous objects (unsuccessfully). Here's the Remix link. Please help!
Edit: I've taken some feedback and found this page which talks about using a JSON.parse function. I've edited the code to reflect the new changes but I still can't figure out exactly whats missing.
Original: I thought this previous answer would help in my attempt to parse a json file and return a random string and its related pair (e.g Title-Platform), but I couldn't get it to work. My goal is to render the output as a text item in my scene. I've really enjoyed working with A-frame but am having a hard time finding documentation that can help me in this regard. I tried using the following modified script to get text from the Json file...
AFRAME.registerComponent('super', { // Not working
schema: {
Games: {type: 'array'},
jsonData: {
parse: JSON.parse,
stringify: JSON.stringify}
},
init: function () {
var el = this.el;
el.setAttribute('super', 'jsonData', {src:"https://cdn.glitch.com/b031cbf1-dd2b-4a85-84d5-09fd0cb747ab%2Ftrivia.json?1514896425219"});
var hugeArray = ["Title", "Platform",...];
const el.setAttribute('super', {Games: hugeArray});
el.setAttribute('position', {x:-2, y:2, z:-3});
}
});
The triggers are also set up in my html to render the text. My code is being worked on through glitch.com, any help will be much appreciated!
To load the json, I think you need to use an XMLHttpRequest (as Diego pointed out in the comments), when that's loaded, you can set the text through setAttribute.
Here's a basic example on glitch:
https://glitch.com/edit/#!/a-frame-json-to-text
On init it does the request, then when done, it set's the loaded json text onto the entity.
AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var jsonText = JSON.parse( event.target.response )
textEntity.setAttribute("value", jsonText.text)
} );
request.send( null );
}
});
Updated version: https://glitch.com/edit/#!/peppermint-direction
AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var games = JSON.parse( event.target.response ).games;
// Get a random game from the list
var randomGame = games[Math.floor(Math.random()*games.length)];
// Get the next game if it's available
var nextGame = null
if (games.indexOf(randomGame) < games.length - 1) {
nextGame = games[games.indexOf(randomGame) + 1]
}
// Build the string for the games
var gameInfo = randomGame.Title + '\n' + randomGame.Developer + '\n\n'
if (nextGame != null) {
gameInfo += nextGame.Title + '\n' + nextGame.Developer + '\n'
}
textEntity.setAttribute("value", gameInfo);
var sceneEl = document.querySelector('a-scene');
sceneEl.querySelector('a-box').setAttribute('material', {src:"https://cdn.glitch.com/4e63fbc2-a1b0-4e38-b37a-9870b5594af8%2FResident%20Evil.jpg?1514826910998"});
});
request.send( null );
}
});

how to display json data in my listview in intel xdk

i am developing hybrid application by using intel xdk and jquerymobile framework for UI. i am trying to get json data from url and display it into listview. i already got json data from url but i don't know how to display those data in listview
This is my json data
{
"nl_wu":[
{
"id":"42",
"year":"2015",
"month":"jan",
"title":"newsletter",
"file":"http://school.com/sample.pdf"
},
{
"id":"39",
"year":"2015",
"month":"jan",
"title":"imagetest",
"file":"http://school.com/sampleimage.jpg"
}
]
}
This is json retrieving function
function showsmsmessage(){
var i;
var out ="";
var json;
var arr ;
var xhr = new XMLHttpRequest();
xhr.open("GET", "URL", false);
xhr.onload = function(){
if(xhr.status == 200)
{
var json_string = xhr.responseText;
json = eval ("(" + json_string + ")");
var s = JSON.stringify(json);
arr = $.parseJSON(s);
for(i=0;i<arr.nl_wu.length;i++)
{
out = arr.nl_wu[i];
alert(out.title);
}
}
else if(xhr.status == 404)
{
intel.xdk.notification.alert("Web Service Doesn't Exist", "Error");
}
else
{
intel.xdk.notification.alert("Unknown error occured while connecting to server", "Error");
}
}
xhr.send();
}
this is my html code for displaying json data in listview
<body>
<div data-role="listview" id="result">
<ul data-role="listview" data-autodividers="false">
<li>Adele</li>
</ul>
</div>
</body>
i want to display title from json in my listview (dynamically). i am getting title from json and just display it in alert message but i need to display in my listview. In my html code i just create one listview with static item.
My Question:-
1) how to display json data(title) in my listview
2) if i click the data item, particular pdf file or image file should download by using file path from json and display it in our app (i have file path in my json)
could you please tell me how to display json data(title) in my listview dynamically
add this instead of alert(out.title);
$("#result ul").append('<li>'+out.title+'</li>');
Its very easy to implement. Suppose list is the object which you are getting from the server. Now we just need to process the object for each array item.
use this code..
var html = '' ;
$.each(list.nl_wu, function(index, item){
html = "<li>" ;
html += "<a href='"+item.file+"'>"+item.title+"</a>" ;
html += "</li>" ;
}) ;
$("#result ul").html(html) ;
P.S. : There may be some comma mistake or something like that but i hope you got the logic behind this.

json each parser ajax

I receive json information as:
{"entInfos":[{"conent":"entreprise","conadd":"45 rue de Paris","conadd2":"75010 \/ Paris| France"}]}
I need to extract each item for entInfos conent = entreprise, conadd = 45 ... etc ...
I tried, but isn't working.
Below is what I tried. Do, you have sample or idea ?
var json = JSON.parse(response);
$.each(json, function(i, item) {
alert(item.conadd);
alert(i.conadd);
});
you probably forgot about entInfos object:
var json = JSON.parse(response);
json.entInfos.forEach(function(info) {
alert(info.conadd);
alert(info.conadd2);
alert(info.conent);
});
And instead of jQuery's $.each method, I've just plain JavaScript's (ES5) forEach method.
Does this help?
Auto response :
var json = JSON.parse(response);
$(json.entInfos).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" ===== "+ v);
});
});

JSON.stringify gives me wrong json array

I have this code:
var sidebars = {};
var counter = 0;
// Loop through all already crated sidebars
$('.custom_dynamic_sidebars li').each(function(event) {
sidebars[counter] = $(this).text();
counter++;
});
var sidebars_string = JSON.stringify(sidebars);
but it gives me this string:
{\"0\":\"aa\",\"1\":\"bb\"}
Here is javascript which sends array to the server:
$.ajax({
url:"/welit_2/wp-admin/admin-ajax.php",
type:'POST',
data:'action=dynamic_sidebars&sidebars='+sidebars_string+'',
success:function(results) {
console.log(results);
}
});
does anyone know what am I doing wrong?
thx for your time
So I found a solution If you run stripslashes() on the JSON string before you output it, it works fine

Binding JSON string to ListView in Metro apps?

I have a metro application(HTML5 & WinJS) in which am trying to display service data . Actually here am retrieving JSON data from my service but am unable to bind this data into listview . Anyone give me some working example.
Thank you.
You can use the WinJS.xhr() for this. You can read more about it on this link https://msdn.microsoft.com/pt-br/library/windows/apps/br229787.aspx and here is an example:
var path = "data/file.json";
function getData(path) {
WinJS.xhr({ url: path }).then(
function (response) {
var json = JSON.parse(response.responseText);
// Since this is an asynchronous function, you can't
// return the data, so you can:
// 1) retrieve the data to a namespace once the app loads.
var list = new WinJS.Binding.List(json);
Somenomespace.data = list;
// 2) or do all the binding inside the function.
var listView = document.getElementById("listViewID");
listView.winControl.itemDataSource = list.dataSource;
});
}
If you use the built in JSON.parse(jsonString) function you can loop through the content using a normal for loop as it then is a normal object and add it as usuall. Just remember to process or render the data.
Her is an example from code i had in a search page using listview:
var response = JSON.parse(data) ;
var originalResults = new WinJS.Binding.List();
for (x in response) {
originalResults.push(response[x]);
}
this.populateFilterBar(element, originalResults);
this.applyFilter(this.filters[0], originalResults);