I am hitting a php file and the response returns a string. I can't find the documentation on how to deal with this.
From the google developer doc google developer doc, my fetch is simple
fetch('upvotes.php')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
And PHP
<?php
function test(){
return "This is a test";
}
echo test();
?>
This fails on the response.json() assumedly because I am returning just a string. If I log out just the response (attached screen shot) I get something I have no idea how to work with, and I cannot convert it. Where is my return value from the PHP here?
response.json causes the dreaded Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
How can the value from the PHP?
Your PHP isn't returning JSON, it's just returning a string so use .text() instead.
Related
I've created a simple word plugin and want to create a document based off another document.
I've stripped down the code
function WordLoadDocument(msg) {
Word.run(context => {
var myNewDoc = context.application.createDocument();
myNewDoc.properties.load();
/*
myNewDoc.properties.customProperties.add("fileId", file.id);
myNewDoc.properties.customProperties.add("fileName", file.name);
myNewDoc.properties.customProperties.add("attachId", attach.id);
myNewDoc.properties.customProperties.add("attachName", attach.name);*/
myNewDoc.open();
return context.sync()
}).catch(error => {
if (error instanceof OfficeExtension.Error) {
console.log(
"Error code and message: " + JSON.stringify(error.debugInfo)
);
console.log(error)
}
});
But I just get
Error code and message: {"code":"AccessDenied","message":"AccessDenied","errorLocation":"Application.createDocument","statement":"var createDocument = v.createDocument();"...
It doesn't seem to matter what I do I just always get the error - even before I add in the data..
The manifest has ReadWriteDocument which seems to be the 'max'
https://learn.microsoft.com/en-us/javascript/api/manifest/permissions?view=word-js-1.4
Is there something I'm missing.
I'm on Word desktop and sideloading the app via network - could this be a permissions on the machine / type issue?
So I've worked this one out - basically the issue is that I had the add-in in a dialog box (displayDialogAsync). Word doesn't like it and hence the error.
I have written sample echo message bot using facebook messenger api and wit.ai actions.
My message from facebook page is received and the proper action function defined using wit api's is also getting called. However
while returning the response, i am getting followin error as -
Oops! An error occurred while forwarding the response to : Error: (#100) Param message[text] must be a UTF-8 encoded string
at fetch.then.then.json (/app/index.js:106:13)
at process._tickCallback (internal/process/next_tick.js:103:7)
Here is the function which is used to return the response -
const fbMessage = (id, text) => {
const body = JSON.stringify({
recipient: { id },
message: { text },
});
const qs = 'access_token=' + encodeURIComponent(FB_PAGE_ACCESS_TOKEN);
return fetch('https://graph.facebook.com/v2.6/me/messages?' + qs, {
method: 'POST',
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body
})
.then(rsp => rsp.json())
.then(json => {
if (json.error && json.error.message) {
throw new Error(json.error.message);`enter code here`
}
return json;
});
};
I have copied this function from the messenger.js file from the documentation since i am just trying the POC.
I checked the values for text and id in this function and verified using console.log statements and those are coming properly.
Can some experts help me to solve this error?
Note - I tried encoding the text using text.toString("utf8"); but it returns the encoding string as [object object] and thats the
response i get from bot. so it doesnt work.
Get the latest code from node-wit, there is a change in facebook id usage,
According to Facebook:
On Tue May 17 format of user and page ids delivered via webhooks will
change from an int to a string to better support default json encoder
in js (that trims long ints). Please make sure your app works with
string ids returned from webhooks as well as with ints.
Still you are getting issue with the api try to add if(event.message && !event.message.is_echo) condition as shown in below code.
// Message handler
app.post('/webhook', (req, res) => {
const data = req.body;
if (data.object === 'page') {
data.entry.forEach(entry => {
entry.messaging.forEach(event => {
if (event.message && !event.message.is_echo) {
const sender = event.sender.id;
const sessionId = findOrCreateSession(sender);
const {text, attachments} = event.message;
if (attachments) {
fbMessage(sender, 'Sorry I can only process text messages for now.')
.catch(console.error);
} else if (text) {
wit.runActions(
sessionId, // the user's current session
text, // the user's message
sessions[sessionId].context // the user's current session state
).then((context) => {
console.log('Waiting for next user messages');
sessions[sessionId].context = context;
})
.catch((err) => {
console.error('Oops! Got an error from Wit: ', err.stack || err);
})
}
} else {
console.log('received event', JSON.stringify(event));
}
});
});
}
res.sendStatus(200);
});
Reference:
no matching user bug
no matching user fix
I have a JavaScript function to post image with Graph API.
function postOpenGraphFromUrl(imageUrl, pageUrl, callback) {
var options = {
'photo' : pageUrl,
'image[0][url]' : imageUrl,
'image[0][user_generated]' : true
};
FB.api('/me/hairchalk:create', 'post', options, function(response) {
if (callback && typeof callback == 'function') {
callback(response);
}
});
}
When I try to execute I have this error in response:
/**/ FB.__globalCallbacks.f4c69a98({"error":{"type":"Exception","message":"The user generated photo at https:\/\/hairchalk.ltst.su\/uploads\/look\/file\/7\/large_photo.jpg could not be uploaded because: cURL Error [#60, CURLE_SSL_CACERT]: Transfer failed.","code":1611180}});
As I can see from the error message there is kind of problem with curl, but on my side I don't use curl at all. How can I solve this problem?
Adding the chain certification fixed this for me. Here's some instructions: http://www.entrust.net/knowledge-base/technote.cfm?tn=8166
I am trying to couple the new version of Typeahead.js and using it with JSON that needs to be pulled from AJAX and not from a JSON file like they have in their examples. I just can't get it to work, I don't want to cache the JSON result or anything, I want to pull it live from Yahoo.
My HTML input is <input type="text" id="symbol" name="symbol" autofocus autocomplete="off" placeholder="Symbol" onkeyup="onSymbolChange(this.value)" />
My AJAX/PHP file has this to retrieve data (this part work, I tested it with Firebug)
header('Content-type:text/html; charset=UTF-8;');
$action = (isset($_GET['action'])) ? $_GET['action'] : null;
$symbol = (isset($_GET['symbol'])) ? $_GET['symbol'] : null;
switch($action) {
case 'autocjson':
getYahooSymbolAutoComplete($symbol);
break;
}
function getYahooSymbolAutoCompleteJson($symbolChar) {
$data = #file_get_contents("http://d.yimg.com/aq/autoc?callback=YAHOO.util.ScriptNodeDataSource.callbacks&query=$symbolChar");
// parse yahoo data into a list of symbols
$result = [];
$json = json_decode(substr($data, strlen('YAHOO.util.ScriptNodeDataSource.callbacks('), -1));
foreach ($json->ResultSet->Result as $stock) {
$result[] = '('.$stock->symbol.') '.$stock->name;
}
echo json_encode(['symbols' => $result]);
}
The JS file (this is where I'm struggling)
function onSymbolChange(symbolChar) {
$.ajax({
url: 'yahoo_autocomplete_ajax.php',
type: 'GET',
dataType: 'json',
data: {
action: 'autocjson',
symbol: symbolChar
},
success: function(response) {
$('#symbol').typeahead({
name: 'symbol',
remote: response.symbols
});
}
});
}
I don't think that I'm suppose to attach a typeahead inside an AJAX success response, but I don't see much examples with AJAX (except for a previous version of typeahead)... I see the JSON response with Firebug after typing a character but the input doesn't react so good. Any guidance would really be appreciated, I'm working on a proof of concept at this point... It's also worth to know that I'm using AJAX because I am in HTTPS and using a direct http to Yahoo API is giving all kind of problems with Chrome and new Firefox for insecure page.
UPDATE
To make it to work, thanks to Hieu Nguyen, I had to modify the AJAX JSON response from this echo json_encode(['symbols' => $result]); to instead this echo json_encode($result); and modify the JS file to use the code as suggested here:
$('#symbol').typeahead({
name: 'symbol',
remote: 'yahoo_autocomplete_ajax.php?action=autocjson&symbol=%QUERY'
});
I have to do it in reverse, i.e: hook the ajax call inside typeahead remote handler. You can try:
$('#symbol').typeahead({
name: 'symbol',
remote: '/yahoo_autocomplete_ajax.php?action=autocjson&symbol=%QUERY'
});
You don't have to create onSymbolChange() function since typeahead will take care of that already.
You can also filter and debug the response from backend by using:
$('#symbol').typeahead({
name: 'symbol',
remote: {
url: '/yahoo_autocomplete_ajax.php?action=autocjson&symbol=%QUERY',
filter: function(resp) {
var dataset = [];
console.log(resp); // debug the response here
// do some filtering if needed with the response
return dataset;
}
}
});
Hope it helps!
i've been figuring it out for ages, there's no problem debugging tool or in the terminal console, but it keeps popping "error occurred" in the following codes:
<script type="text/javascript">
function postCook()
{
$pageURL = window.location;
FB.api('/me/bgfapp:watch?movie=' + $pageURL,'post',
function(response) {
if (!response || response.error) {
alert('Error Occurred');
} else {
alert('Post was successful! Action ID: ' + response.id);
}
});
}
</script>
i tried to echo $pageURL and it returns the current URL successfully, so i can't figure out what's wrong with the above code
updated: 30-Jan-2012
the error says: Error Occurred[object Object][object Object]
You've probably already found a solution but hopefully this will help someone else.
The problem here is that you don't know the names of the child nodes within the response object. If you can't name the specific node then you're going to continually get that error message: "Error occured [Object object] message"
I have a simple workaround that will allow you to see the error message without knowing the names of the response object's child nodes. JSON.stringify will simply convert the entire object into a string, allowing you to view its contents. It won't be pretty but you'll definitely be able to see the error message in there.
Try this:
<script type="text/javascript">
function postCook()
{
$pageURL = window.location;
FB.api('/me/bgfapp:watch?movie=' + $pageURL,'post', function(response) {
if (!response || response.error) {
alert(JSON.stringify(response));
}
else {
alert('Post was successful! Action ID: ' + response.id);
}
});
}
An alternate solution would be to output the contents of the response object to the console rather than executing an alert, just replace line 7 in my code sample with this:
console.log(response);
From here, you can open the development console of your web browser and traverse the contents of the response object. Since the console is not always available (phonegap apps for example), the former solution is sometimes more suitable.
Based on your new error message it looks like you need to see what response.error says. Your logic says that either you got no response at all or you got a response.error. You should first figure out what case you are in and act accordingly.
response.responseText and response.error.responseText are undefined because they aren't returned to you.
$pageURL = '/me/bgfapp:watch?movie=' + window.location;
FB.api($pageURL,'post',
function(response) {
if (!response) {
alert('Error Occurred I got no response with ' + $pageURL);
}
else if (response.error) {
alert('Error Occurred '+ response.error);
} else {
alert('Post was successful! Action ID: ' + response.id);
}
});
My suggestion is try simple and work your way up. Debug all variables that you are checking. If you aren't getting a response it could be that your API endpoint call doesn't exist. If you are getting an error then your call is wrong or maybe not authenticated.