Integrating PHP into JavaScript to fetch JSON - javascript

I installed PHP5 and Apache2 on an Linux vServer (8 Gb Ram ; 8 vCores) and I was scripting but I can't get rid of an error in my code. I'm trying to fetch JSON with integrated PHP but it doesn't work. Here is part of the source code:
function GameDetails(servername, serverurl, mapname, maxplayers, steamid, gamemode) {
var data = '<?php header("access-control-allow-origin: http://api.steampowered.com");$jsonData = file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=*REMOVEDREMOVEDREMOVED&steamids=76561197960435530');echo $jsonData;?>';
document.getElementById('server_name').innerHTML = jsonObj.response.players[0].personaname;
});
}
And here is the version after PHP Processing:
function GameDetails(servername, serverurl, mapname, maxplayers, steamid, gamemode) {
var data = '{
"response": {
"players": [
{
"steamid": "76561197960435530",
"communityvisibilitystate": 3,
"profilestate": 1,
"personaname": "Robin",
"lastlogoff": 1405647102,
"profileurl": "http://steamcommunity.com/id/robinwalker/",
"avatar": "http://media.steampowered.com/steamcommunity/public/images/avatars/f1/f1dd60a188883caf82d0cbfccfe6aba0af1732d4.jpg",
"avatarmedium": "http://media.steampowered.com/steamcommunity/public/images/avatars/f1/f1dd60a188883caf82d0cbfccfe6aba0af1732d4_medium.jpg",
"avatarfull": "http://media.steampowered.com/steamcommunity/public/images/avatars/f1/f1dd60a188883caf82d0cbfccfe6aba0af1732d4_full.jpg",
"personastate": 0,
"realname": "Robin Walker",
"primaryclanid": "103582791429521412",
"timecreated": 1063407589,
"personastateflags": 0,
"loccountrycode": "US",
"locstatecode": "WA",
"loccityid": 3961
}]
}
}';
alert data;
document.getElementById('server_name').innerHTML = data.response.players[0].personaname;
});
}
I know its a loading screen for a Garrys Mod Server. The Debug Console from Firefox says:
SyntaxError: unterminated string literal.
But it's just normal JSON. JSON examples from web works without errors.

var data = '{
There's your unterminated string literal.
You can't have a literal new line in the middle of a string literal in JS.
Later, you are trying to access data as an object, not a string, anyway. Get rid of the quotes around it.

Related

Suitescript RESTlet data get Error Empty JSON string

I have issue using POST Function, I want to transform Transfer Order to Item Receipt, But when I tried to execute the script, it failed with error "org.mozilla.javascript.EcmaError: SyntaxError: Empty JSON string (INVOCATION_WRAPPER$sys#24".
Anyone can help me about my issue ?
Here is my Suitescript Code :
function postData (receiptItem) {
doValidation([receiptItem.recordtype], ['recordtype'], 'POST');
if (receiptItem.recordtype == 'transferorder') {
var recordId = [];
var recStr = [];
var objRecord = record.transform({
fromType: record.Type.TRANSFER_ORDER,
fromId: 131, // transfer Order internalid
toType: record.Type.ITEM_RECEIPT,
defaultValues: {
customform: '433'}
});
var itemReceiptId = objRecord.save({
enableSourcing: false,
ignoreMandatoryField: false
});
recordId.push(itemReceiptId)
log.debug({
"title": "[success] recordId: ",
"details": recordId
});
var recLoad = record.load({
type: receiptItem.recordtype,
id: recordId.getValue('internalid')
});
recStr.push({
use_form: recLoad.getText('customform'),
tran_id: recLoad.getValue('tranid'),
tran_date: recLoad.getValue('trandate'),
tran_from: recLoad.getValue('transferlocation'),
tran_to: recLoad.getValue('location'),
tran_ord_id: recLoad.getvalue('createdfrom'),
tran_memo: recLoad.getValue('memo')
});
log.debug({
"title": "recStr",
"details": recStr
});
return recStr;
}
}
return {
post: postData
};
});
It's a syntax error, very likely some misplaced bracket.
Make sure you are posting valid JSON and that the content type is set on your request
You must send data as JSON. if empty or no data then send {} at least in POST as ContentType is Application/JSON. ECMA Standard. The error message clearly states that "Empty JSON string".
Then try this in Postman tool.

What is wrong with my JSON output for a Slack Message payload?

I have set up what I think should be a working JSON output to send a message in slack but Slack keeps rejecting it.
I have tried multiple different message layout formats using the guides on slack's api site, but so far the only method that has successfully sent is a fully flat JSON with no block formatting.
function submitValuesToSlack(e) {
var name = e.values[1];
var caseNumber = e.values[2];
var problemDescription = e.values[3];
var question = e.values[4];
var completedChecklist = e.values[5];
var payload = [{
"channel": postChannel,
"username": postUser,
"icon_emoji": postIcon,
"link_names": 1,
"blocks": [
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": "*Name:*\n " + name
}
]
}]
}];
console.log(JSON.stringify(payload, null, "\t"));
var options = {
'method': 'post',
'payload': JSON.stringify(payload)
};
console.log(options)
var response = UrlFetchApp.fetch(slackIncomingWebhookUrl, options);
}
When I run this, I get the following output:
[
{
"channel":"#tech-support",
"username":"Form Response",
"icon_emoji":":mailbox_with_mail:",
"link_names":1,
"blocks":[
{
"type":"section",
"fields":[
{
"type":"mrkdwn",
"text":"*Name:*\n test"
}
]
}
]
}
]
Which I believe is correct, however slack api just rejects it with an HTTP 400 error "no text"
am I misunderstanding something about block formatting?
EDIT:
To Clarify, formatting works if I use this for my JSON instead of the more complex format:
{
"channel":"#tech-support",
"username":"Form Response",
"icon_emoji":":mailbox_with_mail:",
"link_names":1,
"text":"*Name:*\n test"
}
The reason you are getting the error no_text is because you do not have a valid message text property in your payload. You either need to have a text property as top line parameter (classic style - your example at the bottom) or a text block within a section block.
If you want to put to use blocks only (as you are asking) the section block is called text, not fields. fields is another type of section bock that has a different meaning.
So the correct syntax is:
[
{
"channel":"#tech-support",
"username":"Form Response",
"icon_emoji":":mailbox_with_mail:",
"link_names":1,
"blocks":[
{
"type":"section",
"text":[
{
"type":"mrkdwn",
"text":"*Name:*\n test"
}
]
}
]
}
]
Also see here for the official documentation on it.
Blocks are very powerful, but can be complicated at times. I would recommend to use the message builder to try out your messages and check out the examples in the docu.

getting signature error for _POST_ORDER_FULFILLMENT_DATA_

I'm trying to post fulfillment data on SubmitFeed using javascript in sapui5 and i have done the steps as,
1) I have created json object for fulfillment data and converted it into XML again XML converted into MD5.
JSON code:-
{
"AmazonEnvelope": {
"-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"-xsi:noNamespaceSchemaLocation": "amznenvelope.xsd",
"Header": {
"DocumentVersion": "1.01",
"MerchantIdentifier": "Example"
},
"MessageType": "OrderFulfillment",
"Message": {
"MessageID": "1",
"OperationType": "Update",
"OrderFulfillment": {
"AmazonOrderID": "102-8289425-201934",
"FulfillmentDate": "2017-06-20T00:36:33-08:00",
"FulfillmentData": {
"CarrierName": "UPS",
"ShippingMethod": "Second Day",
"ShipperTrackingNumber": "1234567890"
},
"Item": {
"AmazonOrderItemCode": "1234567",
"MerchantFulfillmentItemID": "1234567",
"Quantity": "2"
}
}
}
}
};
2) Created signature as per the api documents.
3) Post the data on Feed/2009-01-01.
but i'm getting the error as:-
"<?xml version="1.0"?>
<ErrorResponse xmlns="https://mws.amazonservices.com/">
<Error>
<Type>Sender</Type>
<Code>InvalidAddress</Code>
<Message>Resource /$metadata is not found on this server. API Version is missing</Message>
</Error>
<RequestID>c00cb653-f53c-445f-9f24-82587144805d</RequestID>
</ErrorResponse>
"
Please help me to resolve this.
Thank you
The error you are getting is InvalidAddress, not a signature check error. It seems whatever you are doing in step 3 (Post the data on Feed/2009-01-01) does not work as expected. The MWS servers see a request for /$metadata instead of API name and version. Your question does not include the piece of code that does that.

Error when parsing array with OpenLayers and Protocol.HTTP()

I'm trying to send a JSON file to my Node.js app via Protocol.HTTP. The file is correctly sent, but I can't access to an array. Here is the relevant code :
Client side
(...)
var vectorProtocol = new OpenLayers.Protocol.HTTP({
url: '/getcoords',
format: vectorFormat,
readWithPOST: true,
params: {
"code_company": "8501",
"data_company": [
{
"origin": "2013P00109",
"type": "LJ",
"naf": "5610A",
},
{
"origin": "2013P00110",
"type": "FJ",
"naf": "5481"
}
]
}
});
(...)
Server side, I try to build an array with only the "origin" field of my array "data_company":
function getCoords(params, callback) {
var arrOrigin = params.data_company.map(function(d) {
return d.origin;
});
(...)
}
And I get this error :
TypeError: Object [object Object] has no method "map"
It seems that my "data_company" is not recognized as an array but as an object. I tried to JSON.parse(params) before but I get another error :
SyntaxError: Unexpected token o
Anyway, I'm stuck. Do you have any clue to help me to solve this ?
Thanks

Jquery Autocomplete with json fails

I am using the auto complete plugin by Devbridge and I have it all installed here is my code:
$(document).ready(function(){
$('#request_task').autocomplete({
serviceUrl: '<%= ajax_path %>',
minChars:1,
width: 300,
delimiter: /(,|;)\s*/,
deferRequestBy: 0, //miliseconds
params: { artists: 'Yes' },
});
});
This request hits my rails action and returns this json. there is only one object returned but most of the time there will be more then 1...this was just a test case:
[
{
"user": {
"salt": "somthing",
"name": "john",
"encrypted_password": "92dadsfa6b001ffe71c3c1d8e9fb76c42d1c8afeffa739de9063d94206c",
"created_at": "2010-09-10T14:10:54Z",
"updated_at": "2010-09-10T14:10:54Z",
"admin": null,
"id": 1,
"remember_token": "c945522b3eb0a25e36bb39155fc05b3eec301ac5e2196956f2e6f86b4b22c987",
"email": "test#gmail.com"
}
}
]
I can clearly see the request in firebug but I am not getting anything for the autocomplete and it errors out...Am i missing anything...My error is
a.suggestions is undefined
I think you need to read a little further down the developers page as your response is in the wrong format:
Web page that provides data for Ajax
Autocomplete, in our case
autocomplete.ashx will receive GET
request with querystring ?query=Li,
and it must return JSON data in the
following format:
{
query:'Li',
suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
data:['LR','LY','LI','LT']
}
Notes:
query - original query value
suggestions - comma separated array of suggested values data
(optional) - data array, that contains values for callback function when data is selected.
Sincere advice , dont construct JSON Strings. Please go for an API.
If you are using java, check this out http://www.json.org/java/
and make sure to set content-type in response as application/json
YOUR JSON is in a wrong format
Check their correct format
{
query:'Li',
suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
data:['LR','LY','LI','LT']
}

Categories

Resources