I'm trying to keep the context in Watson Conversation, but it isn't working.. I already tried this answer, but it didn't worked. I'm trying to integrate the bot to the html.
I tried this in the conversation configuration:
var payload = {
workspace_id: workspace,
context: {}};
if (req.body) {
if (req.body.input) {
payload.input = req.body.input;
}
if(req.body.context) {
payload.context = req.body.context;
}}
And this in the code to html/javascript:
var payload = {};
var context = {};
function callWatson(){
alert("watson");
$.ajax({
type: 'POST',
dataType: 'JSON',
contentType: "application/json",
url: '/api/message',
data: JSON.stringify(payload)
}).done(function (json) {
if (json.output.text[0]) {
context = payload.context;
$'<div class="message">+ json.output.text[0]+</div>').appendTo($('.container'));
function insertMessage() {
msg = $('.message-input').val();
$'<div class="message">+ msg+</div>').appendTo($('.container'));
I'm a beginner in coding and I tried coping the conversation-simple js, but I wanted something more simple and direct.. Thanks in advance!
For send message like Watson, with repository conversation-simple, you can simple add in your front-end:
var latestResponse = Api.getResponsePayload();
var context = latestResponse.context;
Api.setResponsePayload('{"output": {"text": ["Hi $name!"]},"context" : ' + JSON.stringify(context) +'}');
You can see the Javascript code use Api and getResponsePayload() and setResponsePayload function inside api.js (path public/js/api.js) to send a message like Watson. But, in your index you have to add the file for use like this line.
You can see inside my setResponsePayload I use the output and text to send the message, like payload show if Watson sends a message.
No need to waste time to maintain context just delete conversation_start dialog(first dialog node) in ibm watson conversation after that give input then you will get exact output
You could try using this as a starting point: https://github.com/snrubnomis/burgerbot
It's intended to be as simple as possible. The "sendMessage" function (in burgerbot.js) makes the call and then stores the returned context for use on subsequent calls.
Related
I am trying to send data to a google app script, to create and insert data into a sheet. What I would like to happen is that the person using the page, will be the one asked to authorize the app (only allowed within the organization). So when authorized, the javascript on the page will send data via jsonp to an app script, which will process and generate a sheet, and then save it to the users drive, and show them the link (or open it up in a new tab).
But when I try this I am running into issues. Here is javascript in my app (not in googles html, my own app).
var foo = function(data) {
console.log('foo')
console.log(data)
}
var url = "https://script.google.com/a/macros/viedu.org/s/AKfycbzF6g9dAC5DI7Qtl0VD3QeYGsDbo43XxuVtoEYSHEA5_4yibYFN/exec"
console.log(url)
var data = {
"foo": "bar"
}
$.ajax({
"url": url,
// The name of the callback parameter
jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "json",
jsonpCallback: foo,
"data": data
})
.done(function(response) {
console.log('success')
console.log(response)
})
.fail(function(response) {
console.log('fail')
console.log(response)
})
and my app script:
function doGet(e) {
var cb = e.parameter.callback;
var data = JSON.stringify({"data":"bar"});
var outputStr = cb + "(" + data + ")";
return ContentService
.createTextOutput(outputStr)
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
and my response in chrome console:
fail
script.html:39 Object {readyState: 0, responseJSON: undefined, status: 0, statusText: "error"}
the response from the app script seems to be coming back as undefined. but im not sure why. If I try almost anything else in the jquery, I get errors stating it is trying to parse html/text and is invalid javascript. But I don't see what has to change in the app script as it looks fairly straight forward.
Replace this:
return ContentService.createTextOutput(outputStr).setMimeType(ContentService.MimeType.JAVASCRIPT);
with this:
var params = JSON.stringify(getr);
return ContentService.createTextOutput(params);
I'm writing a user interface in javascript, it will take data from the HTML and pass it through an API using javascript. I am trying to take the data and pass it to a function without writing a bunch of if statements. However some actions have the actions are the same names in other controllers. So I have a nested namespace, now I can't get to the nested function. Hopefully someone can help.
Everything before this works fine.
var apiHandler = {
user: {
login: function(){
console.log("test");
}
}
};
function callAPI(apiObject){
//console.log(apiObject);
var apiData = JSON.stringify(apiObject);
$.ajax({
type: "POST",
url: 'https://dev.tragicstudios.com/clients/trego/api/index.php',
data: {'enc_request':apiData},
dataType: 'json',
success: function(data){
var apiFunction = apiObject.controller+"."+apiObject.action;
console.log(apiFunction);
apiHandler["user.login"]();
return data;
}
});
}
Just use the controller and action part as separate keys, instead of combining them:
apiHandler[apiObject.controller][apiObject.action]();
For this specific example, instead of:
apiHandler["user.login"]();
Try
apiHandler["user"]["login"]();
I am struggling with this issue for 2 days...
I have a JavaScript array (20,000K rows and 41 columns). It was originally received in javaScript through an ajax call as shown below,
var dataArray = [];
var dataRequest = {};
dataRequest.SearchCondition = 'some value';
$.ajax({
type: "POST",
url: "api/GetData/ProcessRequest",
dataType: 'json',
cache: false,
async: true,
crossDomain: false,
data: dataRequest ,
success: function (response) {
dataArray = response;
},
error: function (xhr, textStatus, errorThrown) {
dataArray = null;
}
});
In the application, the user will verify the data and send it back to Web API method.
I am trying to send the same data back (dataArray) to web api method but, it fails. Please see the code below,
Option 1: (failed - the request did not hit web api method)
var dataArrayJsonStr = JSON.stringify(dataArray);
$.ajax({
type: "POST",
url: "api/SendData/ProcessRequest",
dataType: 'json',
data: {'dataValue':dataArrayJsonStr },
success: function (response) {
alert('success');
},
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown)
}
});
In IE 8, I am getting 'out of memory' exception popup. (most of our application users still have IE 8)
In Chrome, it crashes.
Option 2 tried: (don't know how to read the value)
I tried to send the same value to web api through XmllHttpRequest
var dataArrayJsonStr = JSON.stringify(dataArr);
var xmlRequest;
if (window.XMLHttpRequest) {
xmlRequest = new XMLHttpRequest();
}
xmlRequest.open("POST", "api/SendData/ProcessRequest", false);
xmlRequest.setRequestHeader('Content-Type', 'application/text');
xmlRequest.send("dataValue=" + dataArrayJsonStr);
Using Chrome, I am able to post the data successfully to Web API, I am seeing the content-length as '128180309'. But, I don't see the values. How do i get the values in Web API?
Please suggest me how to send large data back to web api from javascript.
Thanks,
Vim
I think you create overhead, maybe I wrong, you can edit me.
Did you really need send back all datas back or you just need send modified data?
Because in real life hard to imagine that user will review 20.000 of rows.
Good example is ExtJS stores, you can see example here
Key thing of stores that they send back to the server only modified or deleted data, it save browser, network and server resources.
Try to add more memory for API or more time excecution, also you can try return data in more small parts. Defining the number of parts to send.
Did you try to send the data by chunks?
I mean, you need to split it in small pieces and perform multiple number of requests.
For example, it can be like:
--HELLO SERVER. STARTING TRANSMITION FOR DATA SET #177151--
PIECE 1/13
PIECE 2/13
...
PIECE 13/13
--BUE SERVER--
So, it will take some time, but you can send any amounts of data without memory problems. If you're struggling with it for 2 days, I think you got some time to code it :)
UPD1: Client code example.
Here's an example of client code. This is a simple chunking algorithm.
Have to say I didn't test it, because it would take a lot of time to represent your situation.
So, you should read it and get the point.
You have a simple function, that takes you whole data set and callbacks for each response (to update your progress bar, e.g.), for successful finish and for error.
Hope, it will help you to make some problems.
Also, I can help you to build architecture on the server-side, but I need to know what technologies do you use.
function sendData(data, onEach, onFinish, onError) {
var CHUNK_SIZE = 1000;
var isFailed = false;
var chunkNum = 0;
var chunk, chunkStart, chunkEnd;
while(data.length + CHUNK_SIZE > chunkNum * CHUNK_SIZE) {
if(isFailed) {
return;
}
chunkStart = chunkNum * CHUNK_SIZE;
chunkEnd = chunkStart + CHUNK_SIZE + 1;
chunk = {
num: chunkNum,
data: data.slice(chunkStart, chunkEnd)
};
ajaxCall(chunk);
chunkNum++;
}
function ajaxCall(data) {
$.ajax({
type: "POST",
url: "api/GetData/ProcessRequest",
dataType: 'json',
async: true,
data: dataRequest ,
success: function (response) {
onEach(data, response);
},
error: function (xhr, textStatus, errorThrown) {
isFailed = true;
onError(arguments);
}
});
}
}
I have a function below (searchTerm) which is supposed to fetch data from two URL's simultaneously and display the result after both the calls are completed.
This is working fine when I call with only one parameter in .when (say $.ajax(options1)),
but as I need the output from both in parallel, I am calling both URL's and recording responses data1 and data2 in .then function, but now it is not getting called after the ajax calls are completed.
Can anyone tell if I am correct in this approach? If so, then why is the callback not getting executed?
var searchTerm = function() {
var $a = $(this);
var term = $("#searchbox").val();
var options1 = {
url: "someurl1",
contentType: "application/json",
data: JSON.stringify({
searchString: term
}),
type: "post",
dataType: "html"
};
var options2 = {
url: "someurl2",
contentType: "application/json",
data: JSON.stringify({
searchString: term
}),
type: "post",
dataType: "html"
};
$.when($.ajax(options1), $.ajax(options2)).then(function(data1, data2) {
alert("callbacks finished");
});
Info1:
It seems any ajax call I specify as first argument is failing with 500 server error. I tried swapping options1 and options2, and now the call with options2 fails.
Info2:
The url that I have mentioned as part of options1 and options2 point to action methods in the same controller and they both return awaitable Task of (ActionResult) object. Can this be the problem here? Are the calls somehow blocking/interrupting each other over async requests?
Info 3:
Trying to provide more details to work with. The definition of the action methods are like this -
public async Task<ActionResult> someurl1(.....){
...
...
return await View(...);
}
Finally, I found the answer after debugging through all the subsequent calls. I was calling a common function from both action methods which uses a global variable to make external URL calls. Simply used the below locking mechanism to make my critical section thread-safe.
public static object Lock = new object();
lock (Lock) // added for thread safety purpose
{
response_task = CallExtern(...)
}
Try adding the option
async: false
to the ajax objects.
Here's what I am doing,
Get request to my web server, response is in json. Using jquery templates to render that callback data in my app. Pretty straightforward, works like a charm.
Here is the problem: I want to store some of this data locally so that my app doesn't have to fetch it from the server every time (3g is slow and every transaction hurts my UX...). So here is what I've attempted:
$.ajax({
url: app_domain + '/pages/home.json',
type: 'get',
datatype: 'json',
data: { mobile: "1" },
async: true,
cache: false,
success: function(data) {
//store locally
localStorage.setItem('foo', data);
//grab from local store
var bar = localStorage.getItem('foo');
// populate template with data
$.tmpl("cityTemplate", bar).appendTo('#all');
...
This fails. (I realize the code is silly, just for easy debugging until I get it to work)
If I do a simple
alert(foo);
after grabbing the locally stored data i see something like
[object, Object],[object, Object],[object, Object],...,[object, Object]
if i do
alert(foo[0])
i get
'['
if i do
alert(foo[0].name);
i get
'undefined'
So, my best guess is this is caused by the data format getting changed from json to string when stored via localStorage. Would you agree? And, if so, what can I do to get it back into json format?
Thanks a ton!
You need to use JSON like so:
localStorage.setItem('foo', JSON.stringify(data));
And then parse it:
JSON.parse(localStorage.getItem('foo'))
App.local = (function () {
var self = {};
self.get = function (key) {
var b = localStorage.getItem(key);
return b ? JSON.parse(b) : null;
}
self.set = function (key, value) {
var b = JSON.stringify(value);
localStorage.setItem(key, b);
}
return self;
})();
Now you have a nice interface to local storage,
var local = App.local;
local.set('foo', 'bar');
var bar = local.get('foo');
console.log(bar);