Instantly share code, notes, and snippets.

Embed
What would you like to do?
<html>
<head>
<title>API Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var accessToken = "<your agent's client access token>";
var baseUrl = "https://api.api.ai/v1/";
$(document).ready(function() {
$("#input").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
send();
}
});
$("#rec").click(function(event) {
switchRecognition();
});
});
var recognition;
function startRecognition() {
recognition = new webkitSpeechRecognition();
recognition.onstart = function(event) {
updateRec();
};
recognition.onresult = function(event) {
var text = "";
for (var i = event.resultIndex; i < event.results.length; ++i) {
text += event.results[i][0].transcript;
}
setInput(text);
stopRecognition();
};
recognition.onend = function() {
stopRecognition();
};
recognition.lang = "en-US";
recognition.start();
}
function stopRecognition() {
if (recognition) {
recognition.stop();
recognition = null;
}
updateRec();
}
function switchRecognition() {
if (recognition) {
stopRecognition();
} else {
startRecognition();
}
}
function setInput(text) {
$("#input").val(text);
send();
}
function updateRec() {
$("#rec").text(recognition ? "Stop" : "Speak");
}
function send() {
var text = $("#input").val();
$.ajax({
type: "POST",
url: baseUrl + "query?v=20150910",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }),
success: function(data) {
setResponse(JSON.stringify(data, undefined, 2));
},
error: function() {
setResponse("Internal Server Error");
}
});
setResponse("Loading...");
}
function setResponse(val) {
$("#response").text(val);
}
</script>
<style type="text/css">
body { width: 500px; margin: 0 auto; text-align: center; margin-top: 20px; }
div { position: absolute; }
input { width: 400px; }
button { width: 50px; }
textarea { width: 100%; }
</style>
</head>
<body>
<div>
<input id="input" type="text"> <button id="rec">Speak</button>
<br>Response<br> <textarea id="response" cols="40" rows="20"></textarea>
</div>
</body>
</html>
@jib123456

This comment has been minimized.

Show comment
Hide comment
@jib123456

jib123456 Dec 8, 2016

This isn't working for me. It says Internal Server Error.

jib123456 commented Dec 8, 2016

This isn't working for me. It says Internal Server Error.

@BipulRaman

This comment has been minimized.

Show comment
Hide comment
@BipulRaman

BipulRaman Dec 8, 2016

It is not working. It says Internal Server Error.
If we see Browser Network log, Each POST request to API returning two responses.
One with code 204 (empty response) and another is 200 (JSON response)
screen

BipulRaman commented Dec 8, 2016

It is not working. It says Internal Server Error.
If we see Browser Network log, Each POST request to API returning two responses.
One with code 204 (empty response) and another is 200 (JSON response)
screen

@Gugic

This comment has been minimized.

Show comment
Hide comment
@Gugic

Gugic Dec 8, 2016

@BipulRaman, @jib123456 - can you check it now? Just copy to my local machine and execute with my access token.

Owner

Gugic commented Dec 8, 2016

@BipulRaman, @jib123456 - can you check it now? Just copy to my local machine and execute with my access token.

@dubyajaysmith

This comment has been minimized.

Show comment
Hide comment
@dubyajaysmith

dubyajaysmith Dec 9, 2016

Worked well here. Thanks Gugic.
ai2

dubyajaysmith commented Dec 9, 2016

Worked well here. Thanks Gugic.
ai2

@SinanGabel

This comment has been minimized.

Show comment
Hide comment
@SinanGabel

SinanGabel Dec 14, 2016

Hi!

To add speech response add the following piece of code to function setResponse(), and let synth be a global var.

Also do not JSON.stringify() in function send():success, do this in function setResponse() so that val for the below is an Object.

Also test your sound, e.g. ensure sound is not muted on computer.

Works in Chrome:

            if (val.result) {
                var say=""; 
                say = val.result.fulfillment.speech;
                
                synth = window.speechSynthesis;
                var utterThis = new SpeechSynthesisUtterance(say);
                //utterThis.lang = "en-US";
                synth.speak(utterThis);
            }

SinanGabel commented Dec 14, 2016

Hi!

To add speech response add the following piece of code to function setResponse(), and let synth be a global var.

Also do not JSON.stringify() in function send():success, do this in function setResponse() so that val for the below is an Object.

Also test your sound, e.g. ensure sound is not muted on computer.

Works in Chrome:

            if (val.result) {
                var say=""; 
                say = val.result.fulfillment.speech;
                
                synth = window.speechSynthesis;
                var utterThis = new SpeechSynthesisUtterance(say);
                //utterThis.lang = "en-US";
                synth.speak(utterThis);
            }
@A-Guidry

This comment has been minimized.

Show comment
Hide comment
@A-Guidry

A-Guidry Jan 1, 2017

I am getting a 401 error and the "internal server message" I have tried everything I can think of to allow it connect.
screen shot 2017-01-01 at 1 38 15 pm

A-Guidry commented Jan 1, 2017

I am getting a 401 error and the "internal server message" I have tried everything I can think of to allow it connect.
screen shot 2017-01-01 at 1 38 15 pm

@ankitch01

This comment has been minimized.

Show comment
Hide comment
@ankitch01

ankitch01 Jan 9, 2017

Copy the client access token and paste it in your html code .. check attached screenshot for reference.

image

ankitch01 commented Jan 9, 2017

Copy the client access token and paste it in your html code .. check attached screenshot for reference.

image

@mepower2

This comment has been minimized.

Show comment
Hide comment
@mepower2

mepower2 Mar 8, 2017

Could someone please explain the updateRec function and how it works?

mepower2 commented Mar 8, 2017

Could someone please explain the updateRec function and how it works?

@razuahammad14

This comment has been minimized.

Show comment
Hide comment
@razuahammad14

razuahammad14 Mar 11, 2017

I have also getting JSON Respond. How I can use only reply from that format
{
"id": "0ed65683-64b3-41eb-990b-4d1f2b6606e7",
"timestamp": "2017-03-11T20:24:21.693Z",
"result": {
"source": "domains",
"resolvedQuery": "Hi",
"action": "smalltalk.greetings",
"parameters": {
"simplified": "hello"
},
"metadata": {},
"fulfillment": {
"speech": "Howdy."
},
"score": 1
},
"status": {
"code": 200,
"errorType": "success"
},
"sessionId": "somerandomthing"
}

razuahammad14 commented Mar 11, 2017

I have also getting JSON Respond. How I can use only reply from that format
{
"id": "0ed65683-64b3-41eb-990b-4d1f2b6606e7",
"timestamp": "2017-03-11T20:24:21.693Z",
"result": {
"source": "domains",
"resolvedQuery": "Hi",
"action": "smalltalk.greetings",
"parameters": {
"simplified": "hello"
},
"metadata": {},
"fulfillment": {
"speech": "Howdy."
},
"score": 1
},
"status": {
"code": 200,
"errorType": "success"
},
"sessionId": "somerandomthing"
}

@SABTECH

This comment has been minimized.

Show comment
Hide comment
@SABTECH

SABTECH Mar 26, 2017

i have copied my client access token to the HTML code but still, it doesn't run

SABTECH commented Mar 26, 2017

i have copied my client access token to the HTML code but still, it doesn't run

@betagoro

This comment has been minimized.

Show comment
Hide comment
@betagoro

betagoro Apr 27, 2017

Remove this symbol < from client token, and tadaaaaaaaa....
Put only number at this way ===>> "99999999999999"

betagoro commented Apr 27, 2017

Remove this symbol < from client token, and tadaaaaaaaa....
Put only number at this way ===>> "99999999999999"

@supprix

This comment has been minimized.

Show comment
Hide comment
@supprix

supprix Apr 28, 2017

How it running in mobile application iOS or android?

supprix commented Apr 28, 2017

How it running in mobile application iOS or android?

@sanchezbroz

This comment has been minimized.

Show comment
Hide comment
@sanchezbroz

sanchezbroz May 24, 2017

It works like a charm!
Just find accessToken in the example code and put the Client Access token.

image

sanchezbroz commented May 24, 2017

It works like a charm!
Just find accessToken in the example code and put the Client Access token.

image

@panconjugo

This comment has been minimized.

Show comment
Hide comment
@panconjugo

panconjugo May 31, 2017

isn't there a version 2 already? I tried updating this part

var baseUrl TO = "https://api.api.ai/v2/";

But doesn't seem to work

panconjugo commented May 31, 2017

isn't there a version 2 already? I tried updating this part

var baseUrl TO = "https://api.api.ai/v2/";

But doesn't seem to work

@viplav76

This comment has been minimized.

Show comment
Hide comment
@viplav76

viplav76 Jun 21, 2017

Works perfectly for me. Can anyone help with -

  1. Making it work in Android native browser. If there are any particular dependencies, setting requests etc. Ill be running it in the webview
  2. Train the agent on proper nouns. Do I specify entities,

viplav76 commented Jun 21, 2017

Works perfectly for me. Can anyone help with -

  1. Making it work in Android native browser. If there are any particular dependencies, setting requests etc. Ill be running it in the webview
  2. Train the agent on proper nouns. Do I specify entities,
@SinanGabel

This comment has been minimized.

Show comment
Hide comment
@SinanGabel

SinanGabel Jun 25, 2017

@panconjugo: It seems one can use:

var baseUrl = "https://api.api.ai/api/";

SinanGabel commented Jun 25, 2017

@panconjugo: It seems one can use:

var baseUrl = "https://api.api.ai/api/";

@nishkohli96

This comment has been minimized.

Show comment
Hide comment
@nishkohli96

nishkohli96 Jun 30, 2017

Can you please tell me how to set only the result of the bot's speech in the response section and not the entire json code.
I tried to make the folowing change in the exisiting code but it didnt help.

var debugJSON = JSON.stringify(val, undefined, 2),
spokenResponse = val.result.speech;
setResponse(spokenResponse);

thnks in advance

nishkohli96 commented Jun 30, 2017

Can you please tell me how to set only the result of the bot's speech in the response section and not the entire json code.
I tried to make the folowing change in the exisiting code but it didnt help.

var debugJSON = JSON.stringify(val, undefined, 2),
spokenResponse = val.result.speech;
setResponse(spokenResponse);

thnks in advance

@PatricioJulian

This comment has been minimized.

Show comment
Hide comment
@PatricioJulian

PatricioJulian Jul 4, 2017

SOLUTION TO GET THE SPEECH VALUE FROM THE JSON:

function send() {
			var text = $("#input").val();
			$.ajax({
				type: "POST",
				url: baseUrl + "query?v=20150910",
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				headers: {
					"Authorization": "Bearer " + accessToken
				},
				data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }),
				success: function(data) {
					var respText = data.result.fulfillment.speech;
					console.log("Respuesta: " + respText);
					setResponse(respText);
				},
				error: function() {
					setResponse("Internal Server Error");
				}
			});
			setResponse("Thinking...");
		}

PatricioJulian commented Jul 4, 2017

SOLUTION TO GET THE SPEECH VALUE FROM THE JSON:

function send() {
			var text = $("#input").val();
			$.ajax({
				type: "POST",
				url: baseUrl + "query?v=20150910",
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				headers: {
					"Authorization": "Bearer " + accessToken
				},
				data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }),
				success: function(data) {
					var respText = data.result.fulfillment.speech;
					console.log("Respuesta: " + respText);
					setResponse(respText);
				},
				error: function() {
					setResponse("Internal Server Error");
				}
			});
			setResponse("Thinking...");
		}
@SachinNarkhede

This comment has been minimized.

Show comment
Hide comment
@SachinNarkhede

SachinNarkhede Jul 18, 2017

how can get text response instead of json

SachinNarkhede commented Jul 18, 2017

how can get text response instead of json

@nikhil-1337

This comment has been minimized.

Show comment
Hide comment
@nikhil-1337

nikhil-1337 Jul 21, 2017

what should I write in base URL?

nikhil-1337 commented Jul 21, 2017

what should I write in base URL?

@boegi

This comment has been minimized.

Show comment
Hide comment
@boegi

boegi Jul 24, 2017

@SachinNarkhede see the solution from PatricioJulian (Works like a charm)
@nikhil-1337 see the solution from SinanGabel

#var baseUrl = "https://api.api.ai/api/";**

boegi commented Jul 24, 2017

@SachinNarkhede see the solution from PatricioJulian (Works like a charm)
@nikhil-1337 see the solution from SinanGabel

#var baseUrl = "https://api.api.ai/api/";**

@venkatraghava1980

This comment has been minimized.

Show comment
Hide comment
@venkatraghava1980

venkatraghava1980 Aug 4, 2017

Application responds successfully in chat , My concern is "How to use other intents like web search and map location , navigation etc ". I had added web search, map intents but i get empty responses. I would like to know how application will respond on browser or map instead empty responses or successful json. plz help with the coding

venkatraghava1980 commented Aug 4, 2017

Application responds successfully in chat , My concern is "How to use other intents like web search and map location , navigation etc ". I had added web search, map intents but i get empty responses. I would like to know how application will respond on browser or map instead empty responses or successful json. plz help with the coding

@gitdana

This comment has been minimized.

Show comment
Hide comment
@gitdana

gitdana Aug 9, 2017

i want immediate help??

gitdana commented Aug 9, 2017

i want immediate help??

@gitdana

This comment has been minimized.

Show comment
Hide comment
@gitdana

gitdana Aug 9, 2017

when the page loading microphone automatically blocked ? what the reason for that ? i changed access settings and all but issue is occur .

gitdana commented Aug 9, 2017

when the page loading microphone automatically blocked ? what the reason for that ? i changed access settings and all but issue is occur .

@Akayeshmantha

This comment has been minimized.

Show comment
Hide comment
@Akayeshmantha

Akayeshmantha Aug 14, 2017

Hi @gitdana it's because it needs a http server up and running to up and run with the microphone simply add a nodejs server and it will notblock microphone and will run with http protocol so it's done

Akayeshmantha commented Aug 14, 2017

Hi @gitdana it's because it needs a http server up and running to up and run with the microphone simply add a nodejs server and it will notblock microphone and will run with http protocol so it's done

@jbakoume

This comment has been minimized.

Show comment
Hide comment
@jbakoume

jbakoume Aug 16, 2017

hello
please urgent
how can I get the messages I send appear in the discussion with the bot

jbakoume commented Aug 16, 2017

hello
please urgent
how can I get the messages I send appear in the discussion with the bot

@Towerss

This comment has been minimized.

Show comment
Hide comment
@Towerss

Towerss Aug 18, 2017

@jbakoume, to have a chat-alike version you need to start by implementing @PatricioJulian solution to extract from the JSON reply only the answer. This is a simple approach:

  1. Create an array var conversation = [];
  2. Add conversation.push("Me: " + text + '\r\n'); just before var text = $("#input").val(); to store your query.
  3. Comment or delete setResponse("Loading...");
  4. In setResponse(val) function add conversation.push("AI: " + val + '\r\n'); at the top.
  5. Finally modify the printing method with $("#response").text(conversation.join(""));

untitled

Towerss commented Aug 18, 2017

@jbakoume, to have a chat-alike version you need to start by implementing @PatricioJulian solution to extract from the JSON reply only the answer. This is a simple approach:

  1. Create an array var conversation = [];
  2. Add conversation.push("Me: " + text + '\r\n'); just before var text = $("#input").val(); to store your query.
  3. Comment or delete setResponse("Loading...");
  4. In setResponse(val) function add conversation.push("AI: " + val + '\r\n'); at the top.
  5. Finally modify the printing method with $("#response").text(conversation.join(""));

untitled

@MarcoBoer

This comment has been minimized.

Show comment
Hide comment
@MarcoBoer

MarcoBoer Aug 19, 2017

if you want spoken reactions do this:
1: Add ....<script src="https://code.responsivevoice.org/responsivevoice.js"></script> in de head section
2:update function send:
function send() {
var text = $("#input").val();
conversation.push("Me: " + text + '\r\n');
$.ajax({
type: "POST",
url: baseUrl + "query?v=20150910",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }),
success: function(data) {
var respText = data.result.fulfillment.speech;
console.log("Respuesta: " + respText);
setResponse(respText);
responsiveVoice.speak(respText);
},
error: function() {
setResponse("Internal Server Error");
}
});
//setResponse("Thinking...");
}
function setResponse(val) {
conversation.push("AI: " + val + '\r\n');
//$("#response").text(val);
$("#response").text(conversation.join(""));
}

MarcoBoer commented Aug 19, 2017

if you want spoken reactions do this:
1: Add ....<script src="https://code.responsivevoice.org/responsivevoice.js"></script> in de head section
2:update function send:
function send() {
var text = $("#input").val();
conversation.push("Me: " + text + '\r\n');
$.ajax({
type: "POST",
url: baseUrl + "query?v=20150910",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }),
success: function(data) {
var respText = data.result.fulfillment.speech;
console.log("Respuesta: " + respText);
setResponse(respText);
responsiveVoice.speak(respText);
},
error: function() {
setResponse("Internal Server Error");
}
});
//setResponse("Thinking...");
}
function setResponse(val) {
conversation.push("AI: " + val + '\r\n');
//$("#response").text(val);
$("#response").text(conversation.join(""));
}

@Towerss

This comment has been minimized.

Show comment
Hide comment
@Towerss

Towerss Aug 22, 2017

@MarcoBoer thanks for the text to speech feature, it is pretty cool.

Towerss commented Aug 22, 2017

@MarcoBoer thanks for the text to speech feature, it is pretty cool.

@saswat3115

This comment has been minimized.

Show comment
Hide comment
@saswat3115

saswat3115 Sep 15, 2017

it is not working in android chrome browser. microphone is not enabling when clicking on speech button.

saswat3115 commented Sep 15, 2017

it is not working in android chrome browser. microphone is not enabling when clicking on speech button.

@tommyhahn

This comment has been minimized.

Show comment
Hide comment
@tommyhahn

tommyhahn Sep 20, 2017

The voice output is not working in iPhone devices, both Chrome and Safari browsers. Any solutions to this issue, please?

tommyhahn commented Sep 20, 2017

The voice output is not working in iPhone devices, both Chrome and Safari browsers. Any solutions to this issue, please?

@thealexin05

This comment has been minimized.

Show comment
Hide comment
@thealexin05

thealexin05 Oct 4, 2017

@Towerss the code is not working for me. The textbox is not taking any input.

thealexin05 commented Oct 4, 2017

@Towerss the code is not working for me. The textbox is not taking any input.

@Samarth26

This comment has been minimized.

Show comment
Hide comment
@Samarth26

Samarth26 Oct 11, 2017

Hi guys, If I want a picture after a specific response? How do I get it do that? I have tried using custom payload but I can't get it to work!

Samarth26 commented Oct 11, 2017

Hi guys, If I want a picture after a specific response? How do I get it do that? I have tried using custom payload but I can't get it to work!

@rbcabreraUPM

This comment has been minimized.

Show comment
Hide comment
@rbcabreraUPM

rbcabreraUPM Oct 16, 2017

i was able to run it using python simple httpserver

rbcabreraUPM commented Oct 16, 2017

i was able to run it using python simple httpserver

@OrdinaryJellyfish

This comment has been minimized.

Show comment
Hide comment
@OrdinaryJellyfish

OrdinaryJellyfish Oct 23, 2017

REVISED HTML5 CODE

<html>
<head>
	<title>API Example</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
    var accessToken ="youraccesstokenhere";
    var baseUrl = "https://api.dialogflow.com/v1/";
    $(document).ready(function() {
        $("#input").keypress(function(event) {
            if (event.which == 13) {
                event.preventDefault();
                send();
this.value = '';
            }
        });
        $("#rec").click(function(event) {
            switchRecognition();
        });
    });
    var recognition;
    function startRecognition() {
        recognition = new webkitSpeechRecognition();
        recognition.onstart = function(event) {
            updateRec();
        };
        recognition.onresult = function(event) {
            var text = "";
            for (var i = event.resultIndex; i < event.results.length; ++i) {
                text += event.results[i][0].transcript;
            }
            setInput(text);
            stopRecognition();
        };
        recognition.onend = function() {
            stopRecognition();
        };
        recognition.lang = "en-US";
        recognition.start();
    }
    function stopRecognition() {
        if (recognition) {
            recognition.stop();
            recognition = null;
        }
        updateRec();
    }
    function switchRecognition() {
        if (recognition) {
            stopRecognition();
        } else {
            startRecognition();
        }
    }
    function setInput(text) {
        $("#input").val(text);
        send();
    }
    function updateRec() {
        $("#rec").text(recognition ? "Stop" : "Speak");
    }
function send() {
        var text = $("#input").val();
    conversation.push("Me: " + text + '\r\n');
        $.ajax({
            type: "POST",
            url: baseUrl + "query?v=20150910",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            headers: {
                "Authorization": "Bearer " + accessToken
            },
            data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }),
            success: function(data) {
                var respText = data.result.fulfillment.speech;
                console.log("Respuesta: " + respText);
                setResponse(respText);
                $("#response").scrollTop($("#response").height());
            },
            error: function() {
                setResponse("Internal Server Error");
            }
        });
    }
    function setResponse(val) {
	    //Edit "AI: " to change name
        conversation.push("AI: " + val + '\r\n');
        $("#response").text(conversation.join(""));
    }
    var conversation = [];
</script>
  <style type="text/css">
		bot.body { width: 500px; margin: 0 auto; margin-top: 20px; }
		bot.div {  position: absolute; }
		bot.input { width: 400px; }
		bot.button { width: 50px; }
		bot.textarea { width: 100%; }
	</style>
</head>
<body>
	<div class="bot">
  <textarea readOnly = true; id="response" cols="40" rows="20" style="resize: none;"></textarea>
  <br />
    <input id="input" type="text" placeholder="Type here..." autocomplete="off" /><button id="rec">Speak</button>
	</div>
</body>
</html>

Added: Text response only, auto-clear input box, "conversation" view, auto-scroll (not entirely working, after a little bit stops working)
(That extra code was me, I think it made it look better, plus the classes keep it from styling other parts of your page)
-Thanks to @Towerss @PatricioJulian and @Adetee for some of the additional code
I made a fiddle with a demo bot so you can see how it works: https://jsfiddle.net/TristianK3604/9kz7sx7h/

OrdinaryJellyfish commented Oct 23, 2017

REVISED HTML5 CODE

<html>
<head>
	<title>API Example</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
    var accessToken ="youraccesstokenhere";
    var baseUrl = "https://api.dialogflow.com/v1/";
    $(document).ready(function() {
        $("#input").keypress(function(event) {
            if (event.which == 13) {
                event.preventDefault();
                send();
this.value = '';
            }
        });
        $("#rec").click(function(event) {
            switchRecognition();
        });
    });
    var recognition;
    function startRecognition() {
        recognition = new webkitSpeechRecognition();
        recognition.onstart = function(event) {
            updateRec();
        };
        recognition.onresult = function(event) {
            var text = "";
            for (var i = event.resultIndex; i < event.results.length; ++i) {
                text += event.results[i][0].transcript;
            }
            setInput(text);
            stopRecognition();
        };
        recognition.onend = function() {
            stopRecognition();
        };
        recognition.lang = "en-US";
        recognition.start();
    }
    function stopRecognition() {
        if (recognition) {
            recognition.stop();
            recognition = null;
        }
        updateRec();
    }
    function switchRecognition() {
        if (recognition) {
            stopRecognition();
        } else {
            startRecognition();
        }
    }
    function setInput(text) {
        $("#input").val(text);
        send();
    }
    function updateRec() {
        $("#rec").text(recognition ? "Stop" : "Speak");
    }
function send() {
        var text = $("#input").val();
    conversation.push("Me: " + text + '\r\n');
        $.ajax({
            type: "POST",
            url: baseUrl + "query?v=20150910",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            headers: {
                "Authorization": "Bearer " + accessToken
            },
            data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }),
            success: function(data) {
                var respText = data.result.fulfillment.speech;
                console.log("Respuesta: " + respText);
                setResponse(respText);
                $("#response").scrollTop($("#response").height());
            },
            error: function() {
                setResponse("Internal Server Error");
            }
        });
    }
    function setResponse(val) {
	    //Edit "AI: " to change name
        conversation.push("AI: " + val + '\r\n');
        $("#response").text(conversation.join(""));
    }
    var conversation = [];
</script>
  <style type="text/css">
		bot.body { width: 500px; margin: 0 auto; margin-top: 20px; }
		bot.div {  position: absolute; }
		bot.input { width: 400px; }
		bot.button { width: 50px; }
		bot.textarea { width: 100%; }
	</style>
</head>
<body>
	<div class="bot">
  <textarea readOnly = true; id="response" cols="40" rows="20" style="resize: none;"></textarea>
  <br />
    <input id="input" type="text" placeholder="Type here..." autocomplete="off" /><button id="rec">Speak</button>
	</div>
</body>
</html>

Added: Text response only, auto-clear input box, "conversation" view, auto-scroll (not entirely working, after a little bit stops working)
(That extra code was me, I think it made it look better, plus the classes keep it from styling other parts of your page)
-Thanks to @Towerss @PatricioJulian and @Adetee for some of the additional code
I made a fiddle with a demo bot so you can see how it works: https://jsfiddle.net/TristianK3604/9kz7sx7h/

@OrdinaryJellyfish

This comment has been minimized.

Show comment
Hide comment
@OrdinaryJellyfish

OrdinaryJellyfish Oct 23, 2017

@thealexin05 I think it's because he said "Add conversation.push("Me: " + text + '\r\n'); just before var text = $("#input").val(); to store your query." Really, you're supposed to put conversation.push("Me: " + text + '\r\n'); after var text = $("#input").val();. Hope that helps!

OrdinaryJellyfish commented Oct 23, 2017

@thealexin05 I think it's because he said "Add conversation.push("Me: " + text + '\r\n'); just before var text = $("#input").val(); to store your query." Really, you're supposed to put conversation.push("Me: " + text + '\r\n'); after var text = $("#input").val();. Hope that helps!

@ignaciostellino

This comment has been minimized.

Show comment
Hide comment
@ignaciostellino

ignaciostellino Oct 24, 2017

Hey guys,
Does someone know about some css or jquery ui to use to integrate this in a nice way as a chat window in an existing web page?

Thanks!

ignaciostellino commented Oct 24, 2017

Hey guys,
Does someone know about some css or jquery ui to use to integrate this in a nice way as a chat window in an existing web page?

Thanks!

@OrdinaryJellyfish

This comment has been minimized.

Show comment
Hide comment
@OrdinaryJellyfish

OrdinaryJellyfish Oct 25, 2017

@ignaciostellino You could just implement this in it's own stand-alone web page and use some other code to have it pop-up as a new window, and also adjust the height and width settings.

OrdinaryJellyfish commented Oct 25, 2017

@ignaciostellino You could just implement this in it's own stand-alone web page and use some other code to have it pop-up as a new window, and also adjust the height and width settings.

@Samarth26

This comment has been minimized.

Show comment
Hide comment
@Samarth26

Samarth26 Oct 25, 2017

Is there any way I can integrate images to my response?

Samarth26 commented Oct 25, 2017

Is there any way I can integrate images to my response?

@Adetee

This comment has been minimized.

Show comment
Hide comment
@Adetee

Adetee Oct 26, 2017

      if (event.which == 13) {
            event.preventDefault();
            send();
            this.value = ''; //add this line to auto clear your text field so that you won't have to press backspace to clear the text field
        }

Adetee commented Oct 26, 2017

      if (event.which == 13) {
            event.preventDefault();
            send();
            this.value = ''; //add this line to auto clear your text field so that you won't have to press backspace to clear the text field
        }
@smartin681

This comment has been minimized.

Show comment
Hide comment
@smartin681

smartin681 Oct 31, 2017

Hi, thanks @TristianK3604 etc for your great work. Does anyone have any code that we could add in order to automatically send the voice messages? (ie speech to text). Currently the speech is converted into text and user has to automatically press enter to send this text.
Cheers!

smartin681 commented Oct 31, 2017

Hi, thanks @TristianK3604 etc for your great work. Does anyone have any code that we could add in order to automatically send the voice messages? (ie speech to text). Currently the speech is converted into text and user has to automatically press enter to send this text.
Cheers!

@ignaciostellino

This comment has been minimized.

Show comment
Hide comment
@ignaciostellino

ignaciostellino Nov 1, 2017

Hi @TristianK3604,
Do you know why we are using "query?v=20150910" if I am not wrong the "v" represents the version realeased by dialogflow and I think there are more recent ones. Is that right?

ignaciostellino commented Nov 1, 2017

Hi @TristianK3604,
Do you know why we are using "query?v=20150910" if I am not wrong the "v" represents the version realeased by dialogflow and I think there are more recent ones. Is that right?

@mirovaa

This comment has been minimized.

Show comment
Hide comment
@mirovaa

mirovaa Nov 1, 2017

Here's the stuff mentioned above. Just put in your access token and it should all work.

`

<title>API Example</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript"> var accessToken ="INSERT YOUR ACCESS TOKEN"; var baseUrl = "https://api.dialogflow.com/v1/"; $(document).ready(function() { $("#input").keypress(function(event) { if (event.which == 13) { event.preventDefault(); send(); this.value = ''; } }); $("#rec").click(function(event) { switchRecognition(); }); }); var recognition; function startRecognition() { recognition = new webkitSpeechRecognition(); recognition.onstart = function(event) { updateRec(); }; recognition.onresult = function(event) { var text = ""; for (var i = event.resultIndex; i < event.results.length; ++i) { text += event.results[i][0].transcript; } setInput(text); stopRecognition(); }; recognition.onend = function() { stopRecognition(); }; recognition.lang = "en-US"; recognition.start(); } function stopRecognition() { if (recognition) { recognition.stop(); recognition = null; } updateRec(); } function switchRecognition() { if (recognition) { stopRecognition(); } else { startRecognition(); } } function setInput(text) { $("#input").val(text); send(); } function updateRec() { $("#rec").text(recognition ? "Stop" : "Speak"); } function send() { var text = $("#input").val(); conversation.push("Me: " + text + '\r\n'); $.ajax({ type: "POST", url: baseUrl + "query?v=20150910", contentType: "application/json; charset=utf-8", dataType: "json", headers: { "Authorization": "Bearer " + accessToken }, data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }), success: function(data) { var respText = data.result.fulfillment.speech; console.log("Respuesta: " + respText); setResponse(respText); }, error: function() { setResponse("Internal Server Error"); } }); } function setResponse(val) { //Edit "AI: " to change name conversation.push("AI: " + val + '\r\n'); $("#response").text(conversation.join("")); } var conversation = []; </script> <style type="text/css"> body { background-color: #333333; width: 500px; margin: 0 auto; text-align: center; margin-top: 20px; } div { position: absolute; } input { color: #000000; background-color: #00BFFF; width: 500px; } button { color: #FFD700; background-color: #228B22; width: 100px; } textarea { background-color: #FFD700; width: 100%; } </style>
Chat

Response

<textarea id="response" cols="40" rows="20"></textarea>
`

mirovaa commented Nov 1, 2017

Here's the stuff mentioned above. Just put in your access token and it should all work.

`

<title>API Example</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript"> var accessToken ="INSERT YOUR ACCESS TOKEN"; var baseUrl = "https://api.dialogflow.com/v1/"; $(document).ready(function() { $("#input").keypress(function(event) { if (event.which == 13) { event.preventDefault(); send(); this.value = ''; } }); $("#rec").click(function(event) { switchRecognition(); }); }); var recognition; function startRecognition() { recognition = new webkitSpeechRecognition(); recognition.onstart = function(event) { updateRec(); }; recognition.onresult = function(event) { var text = ""; for (var i = event.resultIndex; i < event.results.length; ++i) { text += event.results[i][0].transcript; } setInput(text); stopRecognition(); }; recognition.onend = function() { stopRecognition(); }; recognition.lang = "en-US"; recognition.start(); } function stopRecognition() { if (recognition) { recognition.stop(); recognition = null; } updateRec(); } function switchRecognition() { if (recognition) { stopRecognition(); } else { startRecognition(); } } function setInput(text) { $("#input").val(text); send(); } function updateRec() { $("#rec").text(recognition ? "Stop" : "Speak"); } function send() { var text = $("#input").val(); conversation.push("Me: " + text + '\r\n'); $.ajax({ type: "POST", url: baseUrl + "query?v=20150910", contentType: "application/json; charset=utf-8", dataType: "json", headers: { "Authorization": "Bearer " + accessToken }, data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }), success: function(data) { var respText = data.result.fulfillment.speech; console.log("Respuesta: " + respText); setResponse(respText); }, error: function() { setResponse("Internal Server Error"); } }); } function setResponse(val) { //Edit "AI: " to change name conversation.push("AI: " + val + '\r\n'); $("#response").text(conversation.join("")); } var conversation = []; </script> <style type="text/css"> body { background-color: #333333; width: 500px; margin: 0 auto; text-align: center; margin-top: 20px; } div { position: absolute; } input { color: #000000; background-color: #00BFFF; width: 500px; } button { color: #FFD700; background-color: #228B22; width: 100px; } textarea { background-color: #FFD700; width: 100%; } </style>
Chat

Response

<textarea id="response" cols="40" rows="20"></textarea>
`
@OrdinaryJellyfish

This comment has been minimized.

Show comment
Hide comment
@OrdinaryJellyfish

OrdinaryJellyfish Nov 1, 2017

@ignaciostellino No idea. Sorry.
@smartin681 No problem, and I haven't been able to figure that out myself. Sorry, but I will add it into my comment above once I figure it out and let you know!

OrdinaryJellyfish commented Nov 1, 2017

@ignaciostellino No idea. Sorry.
@smartin681 No problem, and I haven't been able to figure that out myself. Sorry, but I will add it into my comment above once I figure it out and let you know!

@estarly

This comment has been minimized.

Show comment
Hide comment
@estarly

estarly Nov 22, 2017

Buenas, ya probe el ejemplo, y funciona, SOOOLO que el micro no funciona y en chorme me bloquea en migro y lo acepto y nada. Ayuda por favor.
tengo el codigo asi.

<title>API Example</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript"> var accessToken = "XXXXXXXXXX"; var baseUrl = "https://api.api.ai/v1/"; $(document).ready(function() { $("#input").keypress(function(event) { if (event.which == 13) { event.preventDefault(); send(); } }); $("#rec").click(function(event) { switchRecognition(); }); }); var recognition; function startRecognition() { recognition = new webkitSpeechRecognition(); recognition.onstart = function(event) { updateRec(); }; recognition.onresult = function(event) { var text = ""; for (var i = event.resultIndex; i < event.results.length; ++i) { text += event.results[i][0].transcript; } setInput(text); stopRecognition(); }; recognition.onend = function() { stopRecognition(); }; recognition.lang = "en-US"; recognition.start(); }
	function stopRecognition() {
		if (recognition) {
			recognition.stop();
			recognition = null;
		}
		updateRec();
	}
	function switchRecognition() {
		if (recognition) {
			stopRecognition();
		} else {
			startRecognition();
		}
	}
	function setInput(text) {
		$("#input").val(text);
		send();
	}
	function updateRec() {
		$("#rec").text(recognition ? "Stop" : "Speak");
	}
	
	function send() {
		var text = $("#input").val();
		$.ajax({
			type: "POST",
			url: baseUrl + "query?v=20150910",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			headers: {
				"Authorization": "Bearer " + accessToken
			},
			data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }),
			success: function(data) {
				setResponse(data);
				setResponse(JSON.stringify(data, undefined, 2));
			},
			error: function() {
				setResponse("Internal Server Error");
			}
		});
		setResponse("Loading...");
	}
	function setResponse(val) {
		$("#response").text(val);
		
		if (val.result) {
            var say=""; 
            say = val.result.fulfillment.speech;
            
            synth = window.speechSynthesis;
            var utterThis = new SpeechSynthesisUtterance(say);
            //utterThis.lang = "en-US";
            synth.speak(utterThis);
        }
	}
</script>
<style type="text/css">
	body { width: 500px; margin: 0 auto; text-align: center; margin-top: 20px; }
	div {  position: absolute; }
	input { width: 400px; }
	button { width: 50px; }
	textarea { width: 100%; }
</style>
Speak
Response
<textarea id="response" cols="40" rows="20"></textarea>

estarly commented Nov 22, 2017

Buenas, ya probe el ejemplo, y funciona, SOOOLO que el micro no funciona y en chorme me bloquea en migro y lo acepto y nada. Ayuda por favor.
tengo el codigo asi.

<title>API Example</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript"> var accessToken = "XXXXXXXXXX"; var baseUrl = "https://api.api.ai/v1/"; $(document).ready(function() { $("#input").keypress(function(event) { if (event.which == 13) { event.preventDefault(); send(); } }); $("#rec").click(function(event) { switchRecognition(); }); }); var recognition; function startRecognition() { recognition = new webkitSpeechRecognition(); recognition.onstart = function(event) { updateRec(); }; recognition.onresult = function(event) { var text = ""; for (var i = event.resultIndex; i < event.results.length; ++i) { text += event.results[i][0].transcript; } setInput(text); stopRecognition(); }; recognition.onend = function() { stopRecognition(); }; recognition.lang = "en-US"; recognition.start(); }
	function stopRecognition() {
		if (recognition) {
			recognition.stop();
			recognition = null;
		}
		updateRec();
	}
	function switchRecognition() {
		if (recognition) {
			stopRecognition();
		} else {
			startRecognition();
		}
	}
	function setInput(text) {
		$("#input").val(text);
		send();
	}
	function updateRec() {
		$("#rec").text(recognition ? "Stop" : "Speak");
	}
	
	function send() {
		var text = $("#input").val();
		$.ajax({
			type: "POST",
			url: baseUrl + "query?v=20150910",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			headers: {
				"Authorization": "Bearer " + accessToken
			},
			data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }),
			success: function(data) {
				setResponse(data);
				setResponse(JSON.stringify(data, undefined, 2));
			},
			error: function() {
				setResponse("Internal Server Error");
			}
		});
		setResponse("Loading...");
	}
	function setResponse(val) {
		$("#response").text(val);
		
		if (val.result) {
            var say=""; 
            say = val.result.fulfillment.speech;
            
            synth = window.speechSynthesis;
            var utterThis = new SpeechSynthesisUtterance(say);
            //utterThis.lang = "en-US";
            synth.speak(utterThis);
        }
	}
</script>
<style type="text/css">
	body { width: 500px; margin: 0 auto; text-align: center; margin-top: 20px; }
	div {  position: absolute; }
	input { width: 400px; }
	button { width: 50px; }
	textarea { width: 100%; }
</style>
Speak
Response
<textarea id="response" cols="40" rows="20"></textarea>
@Wtrapp

This comment has been minimized.

Show comment
Hide comment
@Wtrapp

Wtrapp Jan 17, 2018

I can get a response, but I do not see the rich content data in the JSON. Testing my app in Google Actions console and I get a beautiful image. But using this code I only get the text.

"fulfillment": { "speech": "We found the perfect product for you. Always Maxi Size 4 Overnight Pads with Wings, Unscented, 33 Count. View now at: https://walmart.com/ip/33469691", "messages": [ { "type": 0, "speech": "We found the perfect product for you. Always Maxi Size 4 Overnight Pads with Wings, Unscented, 33 Count. View now at: https://walmart.com/ip/33469691" } ], "data": { "google": { "expect_user_response": false, "no_input_prompts": [], "is_ssml": false } } }, "score": 1 }, "status": { "code": 200, "errorType": "success", "webhookTimedOut": false }, "sessionId": "somerandomthing"

How do I actually get the rich content back?

Wtrapp commented Jan 17, 2018

I can get a response, but I do not see the rich content data in the JSON. Testing my app in Google Actions console and I get a beautiful image. But using this code I only get the text.

"fulfillment": { "speech": "We found the perfect product for you. Always Maxi Size 4 Overnight Pads with Wings, Unscented, 33 Count. View now at: https://walmart.com/ip/33469691", "messages": [ { "type": 0, "speech": "We found the perfect product for you. Always Maxi Size 4 Overnight Pads with Wings, Unscented, 33 Count. View now at: https://walmart.com/ip/33469691" } ], "data": { "google": { "expect_user_response": false, "no_input_prompts": [], "is_ssml": false } } }, "score": 1 }, "status": { "code": 200, "errorType": "success", "webhookTimedOut": false }, "sessionId": "somerandomthing"

How do I actually get the rich content back?

@alkateb

This comment has been minimized.

Show comment
Hide comment
@alkateb

alkateb Mar 6, 2018

@TristianK3604 Man you are amazing :) thanks a lot for putting the whole filtered code

alkateb commented Mar 6, 2018

@TristianK3604 Man you are amazing :) thanks a lot for putting the whole filtered code

@ruchit2277

This comment has been minimized.

Show comment
Hide comment
@ruchit2277

ruchit2277 Mar 24, 2018

i am getting this error can anyone help please urgent!!!

mato.html:1 Failed to load https://api.dialogflow.com/v1/query?v=20150910: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'null' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access.

ruchit2277 commented Mar 24, 2018

i am getting this error can anyone help please urgent!!!

mato.html:1 Failed to load https://api.dialogflow.com/v1/query?v=20150910: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'null' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access.

@sai2018

This comment has been minimized.

Show comment
Hide comment
@sai2018

sai2018 Mar 25, 2018

getting same error @ruchit2277
did u find any solution?
please help!

sai2018 commented Mar 25, 2018

getting same error @ruchit2277
did u find any solution?
please help!

@cassanellicarlo

This comment has been minimized.

Show comment
Hide comment
@cassanellicarlo

cassanellicarlo Mar 27, 2018

Getting the same error of @ruchit2277 and @sai2018

Failed to load https://api.dialogflow.com/v1/query?v=20150910: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'null' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access.

cassanellicarlo commented Mar 27, 2018

Getting the same error of @ruchit2277 and @sai2018

Failed to load https://api.dialogflow.com/v1/query?v=20150910: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'null' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access.

@sai2018

This comment has been minimized.

Show comment
Hide comment
@sai2018

sai2018 Mar 29, 2018

@cassanellicarlo
just upload the file to web server and open it in localhost.for ex: localhost:8080/filename.html.
I have used wamp server ,but any server can be used .

sai2018 commented Mar 29, 2018

@cassanellicarlo
just upload the file to web server and open it in localhost.for ex: localhost:8080/filename.html.
I have used wamp server ,but any server can be used .

@cassanellicarlo

This comment has been minimized.

Show comment
Hide comment
@cassanellicarlo

cassanellicarlo Mar 29, 2018

Thanks, it works!

(I was trying without a web server with Microsoft Edge and it worked)

cassanellicarlo commented Mar 29, 2018

Thanks, it works!

(I was trying without a web server with Microsoft Edge and it worked)

@sai2018

This comment has been minimized.

Show comment
Hide comment
@sai2018

sai2018 Apr 6, 2018

How do i add microphone glyphicon in the place of chat button ?
Is it possible get a response without clicking stop button i.e just by recording and sending after few seconds??

sai2018 commented Apr 6, 2018

How do i add microphone glyphicon in the place of chat button ?
Is it possible get a response without clicking stop button i.e just by recording and sending after few seconds??

@gopal10

This comment has been minimized.

Show comment
Hide comment
@gopal10

gopal10 Apr 18, 2018

internal server error is displaying. i tried a lot please.. anyone give solution to it

gopal10 commented Apr 18, 2018

internal server error is displaying. i tried a lot please.. anyone give solution to it

@bootyButtersauce

This comment has been minimized.

Show comment
Hide comment
@bootyButtersauce

bootyButtersauce Apr 27, 2018

Dude I was trying to get this working for a hot minute. Thanks a lot!

bootyButtersauce commented Apr 27, 2018

Dude I was trying to get this working for a hot minute. Thanks a lot!

@safee6816

This comment has been minimized.

Show comment
Hide comment
@safee6816

safee6816 Jun 1, 2018

Hey Guys,

Dose anyone have HTML + JS sdk for V2 version. ?

Thanks.

safee6816 commented Jun 1, 2018

Hey Guys,

Dose anyone have HTML + JS sdk for V2 version. ?

Thanks.

@latestscoop

This comment has been minimized.

Show comment
Hide comment
@latestscoop

latestscoop Jun 11, 2018

@Samarth26 - Expanding on @TristianK3604 comment on Oct 23, 2017 I have used a div to display the user and bot output rather than a textarea. This way any html in the output (links,images,etc) will display. I have also added some additional styling allowing you to easily hide the user/bot name, highlight the current response, general prettyness and added a container to hide the response scroll bar if needed:
https://github.com/latestscoop/DialogFlow-HTML5/blob/edfae95c8283fb58c54339b99253a5470539debd/Simple-DialogFlow-HTML5.html#L1-L121

latestscoop commented Jun 11, 2018

@Samarth26 - Expanding on @TristianK3604 comment on Oct 23, 2017 I have used a div to display the user and bot output rather than a textarea. This way any html in the output (links,images,etc) will display. I have also added some additional styling allowing you to easily hide the user/bot name, highlight the current response, general prettyness and added a container to hide the response scroll bar if needed:
https://github.com/latestscoop/DialogFlow-HTML5/blob/edfae95c8283fb58c54339b99253a5470539debd/Simple-DialogFlow-HTML5.html#L1-L121

@alfrededwin

This comment has been minimized.

Show comment
Hide comment
@alfrededwin

alfrededwin Aug 19, 2018

@latestscoop Thanks alot i was looking for a code like this thanks again

alfrededwin commented Aug 19, 2018

@latestscoop Thanks alot i was looking for a code like this thanks again

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment