Get Vimeo video duration with manual api call - javascript

I simply want to get the duration of a vimeo video. I don't want to use froogaloop.
The API states: "You interact with the player by sending a serialized JSON object with postMessage() to the . The following format should be used: { "method": "methodName", "value": "value" } Omit the value key if the method requires no value.""
I tried this bit of code:
*$wrapper.find('#parpap')[0].contentWindow.postMessage(JSON.stringify('method', 'getDuration'));*
Firefox tells me: NS_ERROR_XPC_NOT_ENOUGH_ARGS: Not enough arguments [nsIDOMWindow.postMessage]
Chrome tells me: Failed to execute 'postMessage' on 'Window': Invalid target origin '' in a call to 'postMessage'.
Safari tells me: [Error] SyntaxError: DOM Exception 12: An invalid or illegal string was specified. fixVideoSize
Anyone got any advice? Thanks. :)

The reason of the errors is that JSON.stringify converts a single value to a json string (either string, number, object or array), you are instead passing to it two strings. What you should do is compose an object like this:
$wrapper.find('#parpap')[0].contentWindow.postMessage(
JSON.stringify(
{
'method': 'getDuration'
}
));
Know more about JSON.stringify on Mozilla Developer Network

Related

AWS Lambda: How do I get property inside event.body, it keep return undefined

I was trying to get event.body.data, but it keep return me undefined, i tried JSON.parse(event), JSON.parse(event.body), JSON.parse(event.body.data), JSON.stringify, almost tried out things that i can do with JSON and non of them seems to work. When i tried JSON.parse(event), will give syntax error. So i suspect it already in JSON object format and when i console.log it, it didn't have the " " quote. If it is already in JSON format, why can't I access the property in it. I also tried wrap it inside if(event.body.data) and it doesn't work as well. Anyone know how to get property inside event.body?
Based on your screenshot it looks like the body data is a JSON string. That means you have to parse it first before you can use it. Something like this:
exports.handler = function(event, context, callback) {
const body = JSON.parse(event.body)
console.log('data: ', body.data)
}
Then apply the suggestions from #Marcin and fix your JSON data because it's missing quotes.
Your even.body is invalid json string, which explain why JSON.parse fails. Thus, you should check who/what is making the request and modify the code of the client side to invoke your API with a valid json string.
It should be:
'{"action": "message, "data": "black clolor"}'
not
"{action: 'message, data: 'black clolor'}"
Thanks #Marcin for the feedback, it was indeed caused by invalid json string sent from frontend.
Changing it to the code below solved the issue.
{"action": "message", "data": "black clolor"}

Ajax Error : Uncaught SyntaxError: Unexpected token '<' [duplicate]

I am running an AJAX call in my MooTools script, this works fine in Firefox but in Chrome I am getting a Uncaught SyntaxError: Unexpected token : error, I cannot determine why. Commenting out code to determine where the bad code is yields nothing, I am thinking it may be a problem with the JSON being returned. Checking in the console I see the JSON returned is this:
{"votes":47,"totalvotes":90}
I don't see any problems with it, why would this error occur?
vote.each(function(e){
e.set('send', {
onRequest : function(){
spinner.show();
},
onComplete : function(){
spinner.hide();
},
onSuccess : function(resp){
var j = JSON.decode(resp);
if (!j) return false;
var restaurant = e.getParent('.restaurant');
restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
$$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
buildRestaurantGraphs();
}
});
e.addEvent('submit', function(e){
e.stop();
this.send();
});
});
Seeing red errors
Uncaught SyntaxError: Unexpected token <
in your Chrome developer's console tab is an indication of HTML in the response body.
What you're actually seeing is your browser's reaction to the unexpected top line <!DOCTYPE html> from the server.
Just an FYI for people who might have the same problem -- I just had to make my server send back the JSON as application/json and the default jQuery handler worked fine.
This has just happened to me, and the reason was none of the reasons above. I was using the jQuery command getJSON and adding callback=? to use JSONP (as I needed to go cross-domain), and returning the JSON code {"foo":"bar"} and getting the error.
This is because I should have included the callback data, something like jQuery17209314005577471107_1335958194322({"foo":"bar"})
Here is the PHP code I used to achieve this, which degrades if JSON (without a callback) is used:
$ret['foo'] = "bar";
finish();
function finish() {
header("content-type:application/json");
if ($_GET['callback']) {
print $_GET['callback']."(";
}
print json_encode($GLOBALS['ret']);
if ($_GET['callback']) {
print ")";
}
exit;
}
Hopefully that will help someone in the future.
I have just solved the problem. There was something causing problems with a standard Request call, so this is the code I used instead:
vote.each(function(element){
element.addEvent('submit', function(e){
e.stop();
new Request.JSON({
url : e.target.action,
onRequest : function(){
spinner.show();
},
onComplete : function(){
spinner.hide();
},
onSuccess : function(resp){
var j = resp;
if (!j) return false;
var restaurant = element.getParent('.restaurant');
restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
$$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
buildRestaurantGraphs();
}
}).send(this);
});
});
If anyone knows why the standard Request object was giving me problems I would love to know.
I thought I'd add my issue and resolution to the list.
I was getting: Uncaught SyntaxError: Unexpected token < and the error was pointing to this line in my ajax success statement:
var total = $.parseJSON(response);
I later found that in addition to the json results, there was HTML being sent with the response because I had an error in my PHP. When you get an error in PHP you can set it to warn you with huge orange tables and those tables were what was throwing off the JSON.
I found that out by just doing a console.log(response) in order to see what was actually being sent. If it's an issue with the JSON data, just try to see if you can do a console.log or some other statement that will allow you to see what is sent and what is received.
When you request your JSON file, server returns JavaScript Content-Type header (text/javascript) instead of JSON (application/json).
According to MooTools docs:
Responses with javascript content-type will be evaluated automatically.
In result MooTools tries to evaluate your JSON as JavaScript, and when you try to evaluate such JSON:
{"votes":47,"totalvotes":90}
as JavaScript, parser treats { and } as a block scope instead of object notation. It is the same as evaluating following "code":
"votes":47,"totalvotes":90
As you can see, : is totally unexpected there.
The solution is to set correct Content-Type header for the JSON file. If you save it with .json extension, your server should do it by itself.
It sounds like your response is being evaluated somehow. This gives the same error in Chrome:
var resp = '{"votes":47,"totalvotes":90}';
eval(resp);
This is due to the braces '{...}' being interpreted by javascript as a code block and not an object literal as one might expect.
I would look at the JSON.decode() function and see if there is an eval in there.
Similar issue here:
Eval() = Unexpected token : error
This happened to me today as well. I was using EF and returning an Entity in response to an AJAX call. The virtual properties on my entity was causing a cyclical dependency error that was not being detected on the server. By adding the [ScriptIgnore] attribute on the virtual properties, the problem was fixed.
Instead of using the ScriptIgnore attribute, it would probably be better to just return a DTO.
If nothing makes sense, this error can also be caused by PHP Error that is embedded inside html/javascript, such as the one below
<br />
<b>Deprecated</b>: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in <b>C:\Projects\rwp\demo\en\super\ge.php</b> on line <b>54</b><br />
var zNodes =[{ id:1, pId:0, name:"ACE", url: "/ace1.php", target:"_self", open:true}
Not the <br /> etc in the code that are inserted into html by PHP is causing the error. To fix this kind of error (suppress warning), used this code in the start
error_reporting(E_ERROR | E_PARSE);
To view, right click on page, "view source" and then examine complete html to spot this error.
"Uncaught SyntaxError: Unexpected token" error appearance when your data return wrong json format, in some case, you don't know you got wrong json format.
please check it with alert(); function
onSuccess : function(resp){
alert(resp);
}
your message received should be: {"firstName":"John", "lastName":"Doe"}
and then you can use code below
onSuccess : function(resp){
var j = JSON.decode(resp); // but in my case i'm using: JSON.parse(resp);
}
with out error "Uncaught SyntaxError: Unexpected token"
but if you get wrong json format
ex:
...{"firstName":"John", "lastName":"Doe"}
or
Undefined variable: errCapt in .... on line<b>65</b><br/>{"firstName":"John", "lastName":"Doe"}
so that you got wrong json format, please fix it before you JSON.decode or JSON.parse
This happened to because I have a rule setup in my express server to route any 404 back to /# plus whatever the original request was. Allowing the angular router/js to handle the request. If there's no js route to handle that path, a request to /#/whatever is made to the server, which is just a request for /, the entire webpage.
So for example if I wanted to make a request for /correct/somejsfile.js but I miss typed it to /wrong/somejsfile.js the request is made to the server. That location/file does not exist, so the server responds with a 302 location: /#/wrong/somejsfile.js. The browser happily follows the redirect and the entire webpage is returned. The browser parses the page as js and you get
Uncaught SyntaxError: Unexpected token <
So to help find the offending path/request look for 302 requests.
Hope that helps someone.
I had the same problem and it turned out that the Json returned from the server
wasn't valid Json-P. If you don't use the call as a crossdomain call use regular Json.
My mistake was forgetting single/double quotation around url in javascript:
so wrong code was:
window.location = https://google.com;
and correct code:
window.location = "https://google.com";
In my case putting / at the beginning of the src of scripts or href of stylesheets solved the issue.
I got this error because I was missing the type attribute in script tag.
Initially I was using but when I added the type attribute inside the script tag then my issue is resolved
I got a "SyntaxError: Unexpected token I" when I used jQuery.getJSON() to try to de-serialize a floating point value of Infinity, encoded as INF, which is illegal in JSON.
In my case i ran into the same error, while running spring mvc application due to wrong mapping in my mvc controller
#RequestMapping(name="/private/updatestatus")
i changed the above mapping to
#RequestMapping("/private/updatestatus")
or
#RequestMapping(value="/private/updatestatus",method = RequestMethod.GET)
For me the light bulb went on when I viewed the source to the page inside the Chrome browser. I had an extra bracket in an if statement. You'll immediately see the red circle with a cross in it on the failing line. It's a rather unhelpful error message, because the the Uncaught Syntax Error: Unexpected token makes no reference to a line number when it first appears in the console of Chrome.
I did Wrong in this
`var fs = require('fs');
var fs.writeFileSync(file, configJSON);`
Already I intialized the fs variable.But again i put var in the second line.This one also gives that kind of error...
For those experiencing this in AngularJs 1.4.6 or similar, my problem was with angular not finding my template because the file at the templateUrl (path) I provided couldn't be found. I just had to provide a reachable path and the problem went away.
In my case it was a mistaken url (not existing), so maybe your 'send' in second line should be other...
This error might also mean a missing colon or : in your code.
Facing JS issues repetitively I am working on a Ckeditor apply on my xblock package. please suggest to me if anyone helping me out. Using OpenEdx, Javascript, xblock
xblock.js:158 SyntaxError: Unexpected token '=>'
at eval (<anonymous>)
at Function.globalEval (jquery.js:343)
at domManip (jquery.js:5291)
at jQuery.fn.init.append (jquery.js:5431)
at child.loadResource (xblock.js:236)
at applyResource (xblock.js:199)
at Object.<anonymous> (xblock.js:202)
at fire (jquery.js:3187)
at Object.add [as done] (jquery.js:3246)
at applyResource (xblock.js:201) "SyntaxError: Unexpected token '=>'\n at eval (<anonymous>)\n at Function.globalEval (http://localhost:18010/static/studio/common/js/vendor/jquery.js:343:5)\n at domManip (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5291:15)\n at jQuery.fn.init.append (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5431:10)\n at child.loadResource (http://localhost:18010/static/studio/bundles/commons.js:5091:27)\n at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5054:36)\n at Object.<anonymous> (http://localhost:18010/static/studio/bundles/commons.js:5057:25)\n at fire (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3187:31)\n at Object.add [as done] (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3246:7)\n at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5056:29)"
Late to the party but my solution was to specify the dataType as json. Alternatively make sure you do not set jsonp: true.
Try this to ignore this issue:
Cypress.on('uncaught:exception', (err, runnable) => {
return false;
});
Uncaught SyntaxError: Unexpected token }
Chrome gaved me the error for this sample code:
<div class="file-square" onclick="window.location = " ?dir=zzz">
<div class="square-icon"></div>
<div class="square-text">zzz</div>
</div>
and solved it fixing the onclick to be like
... onclick="window.location = '?dir=zzz'" ...
But the error has nothing to do with the problem..

Hyperledger-Composer: not able to access javaScript split()-function from within transaction processor function

In my hyperledger composer app I added some programmatic access control to a transaction processor function (in file logic.js).
One of the lines of code I added throws an error:
Here is the line of code:
for (consultantRef of transaction.newConsultants) {
//the following line of code does NOT work:
let consultantId = consultantRef.split('#')[1];
In the console I get the following error message:
"transaction returned with failure: TypeError: consultantRef.split is not a function"
For clarification:
transaction.newConsultants is an array of the following type:
["resource:org.comp.app.Consultant#id1", "resource:org.comp.app.Consultant#id2",
"resource:org.comp.app.Consultant#id3"]
I want to get the id of the respective consultants (e.g. "id1").
According to the docs (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split), the split function DOES exist.
But it doesn't work.
How can I get the ids of the consultants?
UPDATE:
When I look at the attributes of the transaction in the console, I see the following for the attribute "newConsultants":
newConsultants: Array (1)
0 "resource:org.comp.app.Consultant#john.doe#gmail.com_1535655902439"
Array Prototype
For clarification:
transaction is an object, namely the following (copied from the angular front-end):
this.transaction = {
$class: 'org.comp.app.AddToConsultantsOfProject',
'project': 'resource:org.comp.app.project#' + this.projectId,
'newConsultants': this.selectedConsultants,
'timestamp': new Date().getTime()
};
its because its a Resource. You would likely convert it to a String (then split would be available on the string object - but you would still need to remove trailing characters (of the resource converted)).
There is a better way -try something like:
trxn.newConsultants.forEach((consultantRef) => {
console.log("identifier is " + consultantRef.getIdentifier());
});
getIdentifier() is described in the Composer API docs.

Soap API error - incorrect type?

I am currently trying to consume an API that is working fine in my browser - my code is as follows:
function getHistory() {
var wsdl = SoapService.wsdl("http://zulutrade.com/WebServices/Performance.asmx?WSDL");
var performanceService = wsdl.getService("PerformanceWebService");
var param = Xml.element("GetProviderTrades", [
Xml.attribute("xmlns", "ZuluTrade.WebServices"),
Xml.element("length",["100"]),
Xml.element("sortBy",["dc"]),
Xml.element("sortAscending",[false]),
Xml.element("providerId",["24508"]),
Xml.element("currencyIds",["[]"]),
Xml.element("fromDateStr",["1984-04-24"]),
Xml.element("toDateStr",["2011-09-10"]),
Xml.element("validTrades",[true]),
Xml.element("lotSize",["2"])
]);
//var envelope = performanceService.getSoapEnvelope("GetProviderTrades", param)
//Logger.log(envelope);
var result = performanceService.GetProviderTrades(param);
Logger.log(result);
}
This appears to be connecting to the service, but is generating the error:
Request failed for http://zulutrade.com/WebServices/Performance.asmx returned code 500. Server response: soap:ClientServer was unable to read request. ---> There is an error in XML document (1, 640). ---> Instance validation error: '2' is not a valid value for LotSize. (line 26)
In order to set each of the parameters, I have copied exactly the payload from the developer tools of Chrome when accessing the page (go to http://www.zulutrade.com/TradeHistoryIndividual.aspx?pid=24508 and change the number of visible trades while viewing the XHR requests to see the payload). As I have set the lotSize to 2, as per the payload in the browser request, I would have expected this to work, but it clearly does not.
Looking at the schema at http://zulutrade.com/WebServices/Performance.asmx?WSDL, I can see the following for lotSize:
<s:element minOccurs="1" maxOccurs="1" name="lotSize" type="tns:LotSize"/>
This looks like it has type tns:LotSize - is this why I am getting the error? If so, how can I pass something of this type in my request?
Thanks!
afaik from WSDL you can see that
<s:simpleType name="LotSize">
<s:restriction base="s:string">
<s:enumeration value="Micro"/>
<s:enumeration value="Mini"/>
<s:enumeration value="Standard"/>
</s:restriction>
</s:simpleType>
So lotSize can be
Xml.element("lotSize","Mini") // 2nd value, instead of ["2"]

Changing the sequence

I am trying to upload a file into my amazon account using the dojo.io.send.However, it's failing to do so .
This is error which i get to see when i run through the firebug.
<Error>
<Code>InvalidArgument</Code>
<Message>Bucket POST must contain a field named 'key'. If it is specified,
please check the order of the fields.</Message>
<ArgumentValue></ArgumentValue>
<ArgumentName>key</ArgumentName>
I figured out the reason and apparently the "Key" field is below to the
"File" field because of that it is ignoring below ones and throwing up the
error .
In order to rectify this issue, i need to have dojo.io.send() to send the
param's list in the following way:-
key uploads/${filename}
AWSAccessKeyId
policy
signature
Content-Type plain/text
file
I tried my luck by playing with the below code but it always put the file
field on the top.
I would appreciate if anybody can help me out in changing the sequence.
Code Snippet:-
var jsonpArgs =
{
url: "https://s3.amazonaws.com/<Bucketname>",
form : dojo.byId("Myform"),
//MyForm has an attribute
//as file which takes the file name from the user to upload.
handleAs: "json",
content:
{
"key":"*******",
"AWSAccessKeyId":"****",
"policy" :"***********",
"signature":"*******",
"Content-Type":"plain/text"
},
error: function(error)
{
},
};
dojo.io.iframe.send(jsonpArgs);
},
Appreciated,
The cause is that Dojo just iterate all the properties in the JSON object and generate the POST request body from it. Since the order of iteration is undetermined, you can not guarantee that the key property always is the first one.
The solution is to generate the POST body yourself. You can get the POST body string using:
"key=" + encodeURIComponent(key) + "&" + dojo.objectToQuery({AWSAccessKeyId : "", policy :""})
By doing this, the key is always the first one in the post body.
When sending the request, do not use content property, use rawBody instead. If you're using older version of Dojo, maybe you can use dojo.rawXhrPost and using postData property in the request.

Categories