GithubHelp home page GithubHelp logo

eduardotkoller / convform Goto Github PK

View Code? Open in Web Editor NEW
178.0 15.0 109.0 102 KB

A jQuery plugin that transforms a form into an interactive chat.

Home Page: https://eduardotkoller.github.io/convForm

License: MIT License

CSS 3.97% HTML 96.03%
jquery-plugin jquery chat form javascript conversation chatbot plugin

convform's Introduction

Note: I will not maintain this anymore. I unfortunately don't have enough time to work on new features and bugfixes.

I started this as a side project and it brought itself to life, with many people seeing different uses to this, in ways completely different from what it was originally supposed to do. I may sometime in the uncertain future re-do this from the ground up to attain to those possibilities, but currently I don't have enough time to work on this, sorry. If you want to help with anything, feel free to open pull requests.

convForm

A plugin that transforms a form into a interative chat.

Features:

  • Transform any input, select (multi or not) to questions on a interative chat
  • regex patterns
  • random question from within options
  • Fork conversation based on answer
  • Access previous answers to use on questions
  • Messages that doesn't expect answer
  • Dynamically create new questions (like using an API)! Demo - please see the example code inside the html to understand how it works

To build the chat, just wrap the form inside an element, and call .convform() on it's jquery selector.

Example:

$(function(){
  var convForm = $('.my-conv-form-wrapper').convform();
});

For the plugin to know which question to ask, every input and select must have a data-conv-question attribute to it. Example:

<select data-conv-question="Hello! I'm a bot created from a HTML form. Can I show you some features?">
	<option value="yes">Yes</option>
	<option value="sure">Sure!</option>
</select>

Pick a question

If you want, you can write more than one question for each tag, using pipe | to separate them. The plugin will randomly choose one to use each time the chat is generated. Example:

<input type="text" name="name" data-conv-question="Alright! First, tell me your full name, please.|Okay! Please, tell me your name first.">

Regex patterns

You can use regex patterns on inputs, just use the data-pattern attribute on the tag. When the user types an answer, if it doesn't fit the pattern, he can't send it and the input color turns red. Example:

<input data-conv-question="Type in your e-mail" data-pattern="^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$" type="email" name="email">

Forking the conversation

You can fork the conversation and ask specific questions based on user's answer. This only works when forking from selects.

To do this, you need to put a div tag after the question you want to fork the conversation from, with a data-conv-fork tag with the select's name on it.

Inside that div, you need to create div tags with data-conv-case attribute referencing the answer that will fork the conversation to it's child elements.

<select name="programmer" data-conv-question="So, are you a programmer? (this question will fork the conversation based on your answer)">
	<option value="yes">Yes</option>
	<option value="no">No</option>
</select>
<div data-conv-fork="programmer">
	<div data-conv-case="yes">
	 	<input type="text" data-conv-question="A fellow programmer! Cool." data-no-answer="true">
	</div>
	<div data-conv-case="no">
		<select name="thought" data-conv-question="Have you ever thought about learning? Programming is fun!">
			<option value="yes">Yes</option>
			<option value="no">No..</option>
		</select>
	</div>
</div>

Referencing previous answers

To use user's answers on questions, you can use {inputname} inside a data-conv-question tag, in which inputname references the question you need the answer from. If you want, you can get specific words from the answer using : selector (0-indexed). For example, when you need the user's first name, you can use {name}:0, and the plugin will get the first word from the "name" question's answer. Example:

<input type="text" data-conv-question="Howdy, {name}:0! It's a pleasure to meet you. How's your day?">

Questions that doesn't expect answer (acts like messages)

You can put messages in the chat flow. They are questions that doesn't expect any answer from the user, so the plugin will go on to the next question instantly. To do this, put a data-no-answer="true" attribute on an input tag. Example:

<input type="text" data-conv-question="A fellow programmer! Cool." data-no-answer="true">

Callbacks

You can use custom functions to be called when a user clicks on an answer from a select, or at the end of the question (If the question expects an answer, the callback will be called after user input. If it doesn't, callback will be called after printing the message.). To do this, simply put the name of the function to be called in the "data-callback" attribute of the option tag, or in the input tag:

<select data-conv-question="Selects also support callback functions. For example, try one of these:">
		<option value="google" data-callback="google">Google</option>
		<option value="bing" data-callback="bing">Bing</option>
</select>
<script>
	function google(stateWrapper, ready) {
		window.open("https://google.com");
		ready();
	}
	function bing(stateWrapper, ready) {
		window.open("https://bing.com");
		ready();
	}
</script>

Callback functions are called with parameters stateWrapper and a callback function ready. State wrapper is the convForm object, and ready is a function that you MUST call to proceed to the next question.

Options

You can add an options object as a parameter to the convForm function, containing:

  • placeHolder: the placeholder you want to appear on the user's input
  • typeInputUi: 'input' or 'textarea', to choose the type of the html element to use as the user's input
  • timeOutFirstQuestion: time in ms as the duration for the load-up animation before the first question
  • buttonClassStyle: class for the user's submit answer button
  • eventList: an object with functions to be called at specific times, the only supported at the moment are onSubmitForm (function is called with the convState as a parameter) and onInputSubmit (function called with the convState as the first parameter, and a ready callback function to print the next question as the second parameter)
  • formIdName: html id for the form
  • inputIdName: html id for the user's input
  • loadSpinnerVisible: class for the loadSpinner
  • selectInputStyle: show (default), disable or hide -- tells the plugin how to handle the input field when a question is a select.
  • selectInputDisabledText: The text to show on the input on select questions in case the selectInputStyle is set to disable.
$(function(){
  var convForm = $('.my-conv-form-wrapper').convform({
    eventList: {
        onSubmitForm: function(convState) {
            console.log('The form is being submitted!');
            convState.form.submit();
        }
    }
  });
});

Beware that the callback functions are called inside the onInputSubmit function. If you are changing this event function, you shouldn't need to use callback functions in the HTML tags, but if you for some reason do need them, besure to call them here using window[convState.current.input.callback](convState, readyCallback);

Stuff used to make this:

convform's People

Contributors

basiletrujillo avatar eduardotkoller avatar stiubhart avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

convform's Issues

New Feature Enquiry

Hi, thanks for making this cool plugin
i have a question, suppose we are in middle of the conversation and we need to jump back to a certain question and resume the whole conversation from there, how can i build all the states from that point? i kinda want ability to jump to previous questions and start conversation from that point instead of starting from the very first question in the initial form. i tried something like this:
[suppose when user click Dashboard button in one of the answers (value = main) so in print answers i change the next state to this dashboard state ]

//get the index at which that question is present
var check = inputs.map(function(element) {
return element.name;
}).indexOf('main');

//build the first quesiton
var dashboard = new SingleConvState(inputs[check]);

//build its states ( but this is not working)
for(var i in inputs) {
// jumping to that index where dashboard question is present
i = check;
console.log("i is: "+i);
if(i != 0 && inputs.hasOwnProperty(i)){
dashboard.next = new SingleConvState(inputs[i]);
dashboard = dashboard.next;
}
}
//this prints the question i want to jump back to
console.log(dashboard);

you don't have to build this feature just if you can help me understand how to build all states from a certain point that would be awesome(I am kinda new in Web development), thanks in advance

Can I Fetch the data from database and show the result in chatbox

Hai,

I am new to this Jquery convForm. Also, I am confusing of displaying DB data to the chatbox. can you help me?
Inside the form (id = formResult) i have an input like

<input id="InputNumber" data-conv-question="Alright! Can you enter the Inventory number, please.|Okay! Please, enter your Order Number." data-pattern="^[0-9]*$" name="Management" required placeholder="Enter corresponding value " type="number" maxlength="15" data-callback="getinfo">

In this input, I put data callback Function -: getinfo() . So function is below.

` function getinfo() {
var number = $('#InputNumber').val();

        $.ajax({
            url: '<%=ResolveUrl("Default.aspx/GetNumberDetails") %>',
            type: "POST",
            dataType: "json",
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({ 'number': number }),
            success: function (response) {

                  $('#formResult').append('<input type="text" data-conv-question="Your Result is "' + response.d + '"." data-no-answer="true">')
               

            },
            error: function (response) { alert(response.d); }
        });

    }`

My Code (.cs) below.

[WebMethod]
        public static string GetNumberDetails(string number)
        {
            DataAccess _db = new DataAccess();
            string strResult = _db.GetInputNumberDetails(Convert.ToInt32(number));
            return strResult;
        
        }

I got the return result back. But how can I show the return result to the Chatbox. I append the result with form but not showing. Is there is any mistake.. Please help.

I am attaching my .aspx file.
Test.aspx.zip

UTF-8 character for submit element not supported on many systems

First off, thank you for this incredible library! Very cool work, that while perhaps obvious now that it's done, clearly took some ingenuity and hard work to get it to the elegant state it's in. Anyway, I have a minor issue to raise:

Currently the submit button uses "Black Medium Right-Pointing Triangle Centred" as the value. Unfortunately, this is not supported on some systems which results in the classic "empty square of death" as shown here:

screen shot 2018-02-22 at 2 33 46 pm

I've replaced with "Black Right-Pointing Triangle" for my implementation, which seems to be much more widely supported.

I'd have submitted a pull request to update this (e.g. on lines 261, 264 of dist/jquery.convform.js), but figured I'd submit as an issue instead, since it occurs in the minified js and perhaps other places as well.

How to use html drop down option in the form

Hi,

I have long list of values to show in select drop down which breaks the UI with current implementation. Could you please tell me how to use the normal drop down itself instead of convForm UI

Using Datepicker

Hi @eduardotkoller ,
I am unable to use jquery datepicker inside Convform. Inside conv-form-wrapper the default date pop-up behaviour is suppressed. Pls suggest how to oversome this.

Handling input value

Hi.

Is it possible to handle an input text value so that it can be sent to something like an api.ai backend?
if yes, can you post a sample code.

I have tried different way to take the input and pass it to a callback function, but have not been able to do, leave alone sending it to another backend

Can I send some input from Chat Bot to my mail

hii,

Actually i used POST method but this is not working so i have use GET method and got the data from chat bot form but the mail function is not working. Please help me.

thanks

This is my chat bot form

<form action="send_form_email.php" method="GET" class="hidden" id=""> <input type="text" name="name" data-conv-question="Welcome to Citiyano De Solution. Please provide your name.|Okay! Please, tell me your name first."> <input type="text" data-conv-question="Hello, {name}:0! It's a pleasure to meet you." data-no-answer="true"> <input type="text" data-conv-question="What kind of service do you like?" data-no-answer="true"> <select name="multi[]" data-conv-question="Our services are:" multiple> <option value="IT & E-Governance">IT</option> <option value="Human Resource">HR</option><br> <option value="Urban Planning">Urban Planning </option> </select> <input type="text" data-conv-question="Please provide your Email id" data-no-answer="true"> <input data-conv-question="" data-pattern="^[a-zA-Z0-9.!#$%&’*+/=?^_{|}~-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-]+(?:.[a-zA-Z0-9-]+)*$" id="email" type="email" name="email" required placeholder="What's your e-mail?">
Awesome!
`

This is my mail Script

`<?php

if(isset($_GET['email']) && !empty($_GET['email']))

{
$emailAddress = $_GET['email'];
}

if(isset($_GET['name']) && !empty($_GET['name'])){
$name= $_GET['name'];
}
if(isset($_GET['multi[]']) && !empty($_GET['multi[]'])){
$multi= $_GET['multi[]'];
}


	$to      = '[email protected]';
    $subject = 'Received from Chat bot';
    $message = 'hii ' . $name;
    $headers = 'From: [email protected]' . "\r\n" .
        'Reply-To: [email protected]' ;
	/*$htmlContent = '<h2>Received from Chat bot</h2>
                <p><b>Name:</b> '.$name.'</p>
                <p><b>Email:</b> '.$from.'</p>
                <p><b>Position:</b> '.$subject.'</p>
				<p><b>Message:</b><br/>'.$message.'</p>';*/
	
	$result=mail($to, $subject, $message, $headers, $multi);
    if(!$result)
    {
        die('There was an error sending out the email');
    }
//header('Location:index.php');

?>
`

How to have a continuous conversation without page refresh

Hello.
I like this template with the features.
However i'm still green when it comes to js/jquery and the bot stuff.
I would like to have a continuous chat option where the user interacts with the app without any page refresh.
I put extra lines of code to make it work but i'm sure there must be a better way that this:

















How to use chart js along side

I am trying to use chart js library along side , since the id of the canvas is in quotes of data-conv-question , is there any way around to utilize the canvas id ? I have added the link of the library below

https://www.chartjs.org

<input type="text" data-conv-question='<canvas id="myChart"></canvas>' data-no-answer="true">

Questions and features

Hi Eduardo, the project its looking good, congrats
I was wondering is it's possible to do this things:

  1. is it possible to make the conversation persistent between the different pages, similar to something like drift pop up? for example if I go from home to the about page
  2. is it possible to submit using ajax, so for example the server can respond: "thanks, appointment is on Monday 10am", and the user sees the message in the chat
  3. does it accept file inputs?

Once again, thanks for your work
Appreciate any help

Link to external website

I'd like to use some URL in the replay of the conversation, is it possible?
Something like this:

<select conv-question="Go searching ... ">
	<option value="www.google.com">Google</option>
	<option value="www.bing.com">Bing</option>
</select>

Thanks :)

Fork based on answer

I'm trying to make a simple Q&A bot but I'm having trouble with the fork, I list of answers and would like to have a "default" one in case the user question doesn't match one of the options. Is there a way to do this?

how to add images in the conversation?

hi Team,
firstly thanks very much for your work it's very nice
basically Im not a dev and I can use your script without difficulty

just one thing is missing for me. the robot is not able to send message with images.

did I miss something or it s not possible?

thanks
Louis

cannot see another answer with select

Hi,

I write answer for selection like that:
answers: [
{text: 'Answer 1 ioji ojo j oi oi ho h oh oi ho nh dskfjhbaslifh aksjd hfkjasdbnfkjasd\n', value: '1'},
{text: 'Answer 2 ioji ojo j oi oi ho h oh oi ho nh dskfjhbaslifh aksjd hfkjasdbnfkjasd\n', value: '2'},
{text: 'END', value: 'end'}
]

  • Result:
    image
    I cannot click answer 2, If answer 2 is in new line I can click it, how can I do it???

Thanks

Last Question no-answer="true", Form Does not submit

Hi Edoardotkoller,

Thank you for this great plugin.

I am trying to implement it on my website, Where last question does not expect an answer (no-answer="true"). But in that case form does not submit.

For example at the last, once collected all the details, I would like to send a thanks message for which I dont expect an answer, but in this case form is not being submitted.

Please help I am stuck in between.

Thanks,
Rahul

Reload Function

Hello friend
First of all, thank you very much for share you nice plugin.
I would like to know how to do it for example if I want to start again once the chat has already started or finished.
Can you help me please.

New features :

Hello @eduardotkoller ,

I did extensive changes to your plugins, such as :

  • including google map;
  • handle 'hidden' input field;
  • handle repetitive steps;
  • new validation method including remote (AJAX);
  • ...

Would you be interested by such changes ?

Br,
fas3r

Repeat a question

Hello,

is it possible to repeat a question ? or to come back to a question ? A scenario like this :

Q1 -- bot -- how much do you pay ?
-- answer user -- 400
Q2 -- bot -- Do you want to add more expense ? ( select yes - no )
-- answer user -- yes
-- answer user -- 200
Q2 -- bot -- Do you want to add more expense ? ( select yes - no )
-- answer user -- yes
-- answer user -- 600
Q2 -- bot -- Do you want to add more expense ? ( select yes - no )
-- answer user -- no
Q3 -- bot -- next question ...

The Question 2 can be repeated indefinitely ;

Thanks

Another question about nested forks

Hi, I'm having some trouble working with nested conv-fork.

Here's my example, assuming I chose false in the next select:

<select name="accompanied" conv-question="¿Tienes pensado pedir la hipoteca solo o acompañado? ">
    <option value="false">Solo</option>
    <option value="true">Acompañado</option>
</select>
<div conv-fork="accompanied">
    <div conv-case="false" class="alone">
        ...
    </div>
    <div conv-case="true" class="alone">
        ...
    </div>
</div>

Then after that, I have the next code:

<select name="selectedProperty" conv-question="¿La casa ha sido elegida? ">
    <option value="true">Sí</option>
    <option value="false">No</option>
</select>
<!-- selected Properties -->
<div conv-fork="selectedProperty">
    <div conv-case="false">
        <div conv-fork="accompanied">
            <div conv-case="false">
                <!-- purchaseAmount -->
                <input type="number" pattern="^(0|[1-9][0-9]*)$" name="purchaseAmount"  conv-question=" true false">
            </div>
            <div conv-case="true">
                <!-- purchaseAmount -->
                <input type="number" pattern="^(0|[1-9][0-9]*)$" name="purchaseAmount"  conv-question=" true true">
            </div>
        </div>
    </div>
    <div conv-case="true">
        <div conv-fork="accompanied">
            <div conv-case="false">
                <!-- purchaseAmount -->
                <input type="number" pattern="^(0|[1-9][0-9]*)$" name="purchaseAmount"  conv-question=" false false">
            </div>
            <div conv-case="true">
                <!-- purchaseAmount -->
                <input type="number" pattern="^(0|[1-9][0-9]*)$" name="purchaseAmount"  conv-question=" false true">
            </div>
        </div>
    </div>
</div>

The thing is, at the conv-fork of "selectedProperty", it prints both conv-case divs (and only one of the inner "accompanied" forks).

I have named the questions so I know wich child is being printed in order to debug.

When you select "true" at the "selectedProperty" field, the conv-question is: true false. After you input some value, it asks again: false false, and I think it shouldn't.

Am I doing something wrong? Is it a bug?

Thanks !

Class "Error" Not Removed, When the Option is selected.

Hi Eduardotkoller,

I came across another issue, It seems like a bug. I thought to bring it to your notice.

In case of options, if a user starts typing, it adds a class error so the text can not be submitted. Then the user presses the one option (Without removing the text entered earlier). Option value gets submitted, but the class error still remains as the text entered is still there, and even if the user deletes the text entered, error class still remains and thus the form does not get submitted.

I hope I am able to explain it properly (Screenshot attached).

image

Thanks again for this great plugin.
Rahul

Display behavior not as expected

Hello !
Your project is cute!

I tried to plug the answers to an API, but the result is not what I expected.
Let's say my API takes 10 seconds to respond.
Expected behavior:

  • form asks "choice 1" or "choice 2"
  • user clicks on his choice
  • form prints in the right the selected answer (green)
  • form prints in the left a "..." bubble
  • wait for 10 seconds (time for the API to respond)
  • "..." is replaced by the actual message

Actual behavior:

  • form asks "choice 1" or "choice 2"
  • user clicks on his choice
  • wait for 10 seconds (time for the API to respond)
  • form prints in the right the selected answer (green)
  • form prints in the left a "..." bubble
  • "..." is replaced by the actual message

The actual behavior gives the feeling that the system is stuck. Is there a way to display (at least) the selected answer (green bubble) before the display of the response?

Thank you.

Re Building States [ Not Working ]

gittt

I saved all the inputs in a global array (access) and i wrote this callback

function jump(stateWrapper) {
var singleState = new SingleConvState(access[0]);
stateWrapper.current.next = singleState;
for(var i in access) {
if(i != 0 && access.hasOwnProperty(i)){
singleState.next = new SingleConvState(access[i]);
singleState = singleState.next;
}
}
console.log("Calling jump");
}

this is working but sometimes the questions and it's order are not correct, the questions comes randomly sometimes even though i m building all the states again can u please help me fix this?

Disappearing chat box

Commit 23275cf seems to eat the chatbox if the user filters a select box. On the demo page, if you just type in 'Y' 'E' and then alternate between 'S' and backspace, the message box disappears until it is just the buttons.

disable text area

hi,
first i want to say that this is a great plugin.

i have 2 questions :

  1. can i disable the option to insert text ? i am using only buttons,
  2. is it possible to add image ?
    thanks
    gil

select multiple options on API version

Hi Eduardo - I sent you a $ donation because I love this plugin. I made some changes to hide the text input field when not required and other small things. However, I'm having trouble adding multiple select option functionality to the "API" version. I've been playing with the newState() function, but have not been able to get multiple select options to work yet. Do you have any tips?

Thanks!
David

Send multiple messages between agent and user

Hello, how to send multiple messages between agent and user? Like, the user can send multiple messages chat after he/she sent the first message (vice versa - agent side) even the agent is not yet answer the chat. And if the user did not type and send anything within 5 minutes, the chat will ended.

How to do this? Please help me. Thank you

Here's the current code:

success: function (data) {
								original = convState.current;
								convState.current.next = convState.newState({
									type: 'text',
									questions: [data.messages],
								});

								convState.current.next.next = convState.newState({
									type: 'text',
									questions: [data.messages],
									answers: $('input[type=text]#chatConcern').val()
								});
										
								setTimeout(ready, Math.random() * 500 + 100);
							}

How to dynamically insert input fields as a Reply

Hello,

I am able to dynamically create an Input Field when asking the initial question. But when I try to get the User's reply, Process it in the back-end server and Send a reply to the front-end, I am unable to create a New Input Field as a Reply.

<form id="form" onsubmit="form(); return false;" method="POST" class="hidden">
  <!-- Form Fields will be created dynamically here -->
</form>
    <script>
        $('#form').append('<input type="text" id="question" name="question" conv-question="What is your name?">');
        function form() {
            var form = document.getElementById('form');
            var question = form.elements.question.value;
                $.post("/answer",
                    {
                        question: question
                    },
                    function(data){
                      $("<input type='text' />")
                         .attr("id", "answer")
                         .attr("name", "answer")
                         .attr("conv-question", data)
                         .appendTo("#form");
                });
        }
    </script>

Can't sent multiple answers with select options

Hello! I have a problem with the mutiple select, when I'm filling out the form it detects all the ones I activated, but when my PHP is executed, only sent the last option selected .... any sendmail.php that you recommend? or some rule that I should add to mine? .... BTW, I know about HTML and CSS, but I do not have much experience in PHP and JS.

Can I fetch the response data from/to web service and show the result in chatbox?

Hello,

I'm new to this JQuery convForm.
Also, I am confusing of displaying the response from web service to chatbox and vice versa (pass the data to web service.

Inside the form, I have a select box which has a 2 options, each options have a corresponding dummy chat message. What I need is when the user reach to the question with 'Type your concern', the data will pass in web service and get the real data chat message.

I can't get the response data fetch from/to the web service when the user reached to 'Type your concern', what is currently happening is the chatbox reload itself when reached to 'Type your concern' and everything was cleared.

Please help me.

JS:

jQuery(function($){
			var count = 0;
			var convForm = $('#chat').convform({eventList:{onInputSubmit: function(convState, ready) {
				console.log('input is being submitted...');
		        if(convState.current.answer.value==='end') {
		            convState.current.next = false;
					setTimeout(ready, Math.random()*500+100);
		        } else {
					if(Array.isArray(convState.current.answer)) var answer = convState.current.answer.join(', ');
					else var answer = convState.current.answer.text;
					setTimeout(ready, Math.random()*500+100);
		        }
				count++;
				
				/* function getinfo(stateWrapper, ready) {
					window.open("https://google.com");
					ready();
				} */

				function getinfo(convState) {
					var chatMsg = $('#chatConcern').val();
						if(chatMsg>=0) {
							$.ajax({
								url: 'https://example.webservice/',
								type: "POST",
								dataType: "json",
								contentType: 'application/json; charset=utf-8',
								data: JSON.stringify({ 'text': chatMsg }),
								success: function (response) {
									console.log("Thanks!");
								},
								error: function (response) { alert(response.d); }
							
						});
					}
					}
			}}});
		});

Here's the form look like:

<form action="" method="GET" class="hidden" id="chatUser">
	                                <select name="custType" data-conv-question="Are you a new or existing customer?" name="first-question">
	                                    <option value="newCust">New Customer</option>
	                                    <option value="existingCust">Existing Customer</option>
									</select>

									<div data-conv-fork="custType">
	                                   <div data-conv-case="newCust">
											<input type="text" name="custName" data-conv-question="What is your full name?">
											<input type="email" name="custEmail" data-conv-question="What is your e-mail address?">
											<input type="text" name="mobile" data-conv-question="What is your mobile number?">
											<input type="text" name="custConcern" id="chatConcern" data-conv-question="Type your concern or message to Customer Support" data-callback="getinfo">
	                                    </div>

										<div data-conv-case="existingCust">
											<select name="existingCust" data-conv-question="Which department would you like to talk to?">
												<option value="col">Dept 1</option>
												<option value="hr">Dept 2</option>
												<option value="cs">Dept 3</option>
											
												<div data-conv-case="col">
													<input type="text" name="custName" data-conv-question="What is your full name?">
													<input type="email" name="custEmail"  data-conv-question="What is your e-mail address?">
													<input type="text" name="mobile" data-conv-question="What is your mobile number?">
													<input type="text" name="custConcern" id="chatConcern" data-conv-question="Type your concern or message to Customer Support" data-callback="getinfo">
												</div>

												<div data-conv-case="hr">
													<input type="text" name="custName" data-conv-question="What is your full name?">
													<input type="email" name="custEmail" data-conv-question="What is your e-mail address?">
													<input type="text" name="mobile" data-conv-question="What is your mobile number?">
													<input type="text" name="custConcern" id="chatConcern" data-conv-question="Type your concern or message to Customer Support" data-callback="getinfo">
												</div>

												<div data-conv-case="cs">
													<input type="text" name="custName" data-conv-question="What is your full name?">
													<input type="email" name="custEmail" data-conv-question="What is your e-mail address?">
													<input type="text" name="mobile" data-conv-question="What is your mobile number?">
													<input type="text" name="custConcern" id="chatConcern" data-conv-question="Type your concern or message to Customer Support" data-callback="getinfo">
												</div>
											</select>
										</div>
									 </div>
	                            </form>

Display dynamic reply in bubble chat from external API

I'm trying to display a dynamic message/reply message from external API, but I'm getting an error like this Uncaught TypeError: Cannot read property 'current' of undefined in askAgain function, but in alert it's working.

How to fix this? Also how to append a p html tag outside the bubble chat?

Thank you.

var original = false;
function askAgain(convState, ready, message) {
	convState.current.next = convState.newState({
		type: 'text',
		questions: [message],
		callback: ['clientConcern']
	});
	convState.current.next.next = convState.newState({
		type: 'text',
		questions: [message],
		text: $('input[type=text]#chatConcern').val()
	});

	setTimeout(ready, Math.random() * 500 + 100);
	convState.current.next = false;
}


function clientConcern(convState){
	$.ajax({
		url: 'http://example/api',
		type: "POST",
		dataType: "json",
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify({
			"nickname": $('input[type=text]#custName').val(),
			"subject": $('select[name="custType"]').val()
		}),
		success: function (data){
			loadInterval = setInterval(receivedMsg, 1000);

		// load messages uniquely
		var messageInterval = setInterval(function(){
			for (const item of messageArray){
				if (!showedMap.has(item.index)){
					askAgain(item.text);
					showedMap.set(item.index, true);
				}
			}
		}, 100);
						
		sendMsg();
	},
		error: function (data){
			alert(data);
		}
	});
}
        
function sendMsg(){
	jQuery.ajax({
		url: 'http://example/api/chat_id',
		type: "POST",
		dataType: "json",
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify({
			operationName : "SendMessage",
			alias : ALIAS,
			secureKey : SECURE_KEY,
			text: $('input[type=text]#chatConcern').val()
		}),
		success: function (data){
			console.log(data);
		}
	});
}

function receivedMsg(convState){
	jQuery.ajax({
		method: "POST",
		url: "http://example/api/chat_id/messages",
		cache: false,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		data: JSON.stringify({
			"alias" : ALIAS,
			"secureKey" : SECURE_KEY,
			"userId" : USER_ID
		}),
	}).done(function(data){
		if (data.chatEnded){
			clearInterval(loadInterval);
			original = convState.current;
			convState.current.next = convState.newState({
				type: 'text',
				questions: [message],
				noAnswer: true
			});
			convState.current.next.next = convState.newState({
				type: 'text',
				questions: ['Chat ended.'],
				noAnswer: true,
				callback: ['askAgain']
			});
		} else {
			var len = data.messages.length;
			for (i = 0; i < len; i++){
				var messages = data.messages[i];

				if (messages.type === "Message" && 
				(messages.from.type === "Agent" || messages.from.type === "External")){
					if (!messageMap.has(messages.index)){
						messageMap.set(messages.index, true);
						messageArray.push(messages);
					}
				}
			}
		}	
	});
}

jQuery(function($){
	var convForm = $('#chat').convform();
	console.log(convForm);
});
```

Dialog rollback

Hi!
First of all, great plugin, really easy to implement;
My only issue, is it possible to rollback to a previous dialog without reloading the entire chatbot?
Like, recall the last select before the fork.

Thx!
Lucas.

rollback and reset answers

Hi,
Thank you for sharing your work, your plugin is very cool and pleasant to use !

I have a bug when rollbacking to the first question fork and choosing another answer, the "new choice" is not stored and I'm stuck in the loop of the "first time choice"
Is it possible to rollback to the first question and reseting all the old answers stored ?

I know you're very busy at the moment but really apreciate if you can help me with that.
Thanks a lot !

Script not working

Hello,

After clicking no option, all questions show, but after selecting next question script stop working.

required Placeholder attribute in ConvForm is not working

<input data-conv-question="Type in your e-mail" data-pattern="^[a-zA-Z0-9.!#$%&’*+/=?^_{|}~-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-]+(?:.[a-zA-Z0-9-]+)*$" id="email" type="email" name="email" required placeHolder="What's your e-mail?">

Google Bing `
But still the placeholder for Email and password is "type Here"

dead repo ?

Hello,

do you plan to keep this repo active or we should not expect support ?

br,
fas3r.

Add dynamically questions in javascript

Hello,
Thanks for your library its great.
I wont to use your library to working with a chatBot.
It is possible to add dynamically questions into convForm in JS ?

Thanks for the answer.

Visual problem with firefox

Hi Eduardo,

Thanks a lot for your awesome job with this script.

A noticed a small visual artefact using firefox : when form is long enough, select options are overlapping the question.

Any help ?

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.