Why this code not working
I am building a chatbot application using php and aiml. I have made the chat window for the same. But in chat window when I enter the message it overwrites the previous message every time. I want that the new message should come in the new line. Please help
My Code is
<div class="panel" id="chat">
<div class="panel-heading" style="background-color:#337ab7">
<h3 class="panel-title" style="color:#FFF">
<i class="icon wb-chat-text" aria-hidden="true" ></i> How Can I Help You
</h3>
</div>
<div class="panel-body">
<div class="chats">
<div class="chat">
<div class="chat-avatar">
<a class="avatar avatar-online" data-toggle="tooltip" href="#" data-placement="right" title="" data-original-title="June Lane">
<i></i>
</a>
</div>
<div class="chat-body">
<div class="chat-content">
<p>
<div class="botsay">Hey!</div>
</p>
<time class="chat-time" datetime="2015-07-01T11:37">
<?php
echo date("h:i:sa");
?></time>
</div>
</div>
</div>
<div class="chat chat-left">
<div class="chat-avatar">
<a class="avatar avatar-online" data-toggle="tooltip" href="#" data-placement="left" title="" data-original-title="Edward Fletcher">
<i></i>
</a>
</div>
<div class="chat-body">
<div class="chat-content">
<p><div class="usersay"> </div></p>
<time class="chat-time" datetime="2015-07-01T11:37">
<?php
echo date("h:i:sa");
?></time>
</div>
</div>
</div>
</div>
</div>
<div class="panel-footer">
<form method="post" name="talkform" id="talkform" action="index.php">
<div class="input-group">
<input type="text" class="form-control" name="say" >
<input type="hidden" name="convo_id" id="convo_id" value="<?php echo $convo_id;?>" />
<input type="hidden" name="bot_id" id="bot_id" value="<?php echo $bot_id;?>" />
<input type="hidden" name="format" id="format" value="json" />
<span class="input-group-btn">
<input class="btn btn-primary" type="submit" name="submit" id="submit" value="Send" />
</span>
</div>
</form>
</div>
I am using ajax to input values in the chat window using aiml.
$(document).ready(function() {
// put all your jQuery goodness in here.
$('#talkform').submit(function(e) {
e.preventDefault();
var user = $('#say').val();
$('.usersay').text(user);
var formdata = $("#talkform").serialize();
$('#say').val('');
$('#say').focus();
$.get('<?php echo $url ?>', formdata, function(data){
var b = data.botsay;
if (b.indexOf('[img]') >= 0) {
b = showImg(b);
}
if (b.indexOf('[link') >= 0) {
b = makeLink(b);
}
var usersay = data.usersay;
if (user != usersay) {
$('.usersay').text(usersay);
}
$('.botsay').html(b);
}, 'json').fail(function(xhr, textStatus, errorThrown){
$('#urlwarning').html("Something went wrong! Error = " + errorThrown);
});
return false;
});
});
function showImg(input) {
var regEx = /\[img\](.*?)\[\/img\]/;
var repl = '<br><img src="$1" alt="$1" width="150" />';
var out = input.replace(regEx, repl);
console.log('out = ' + out);
return out
}
function makeLink(input) {
var regEx = /\[link=(.*?)\](.*?)\[\/link\]/;
var repl = '$2';
var out = input.replace(regEx, repl);
console.log('out = ' + out);
return out;
}
The problem with your code is you are just keeping on replacing the contents of usersay and botsay. You need to append or prepend as per your need to make it work.
Consider this bit of code, you need to change as per comments:
$.get('<?php echo $url ?>', formdata, function(data){
var b = data.botsay;
if (b.indexOf('[img]') >= 0) {
b = showImg(b);
}
if (b.indexOf('[link') >= 0) {
b = makeLink(b);
}
var usersay = data.usersay;
if (user != usersay) {
$('.usersay').append(usersay); // 1. Change here.
}
$('.botsay').append(b); // 2. Change here.
}, 'json')
Related
I would like to be suggested on how to solve an Ajax post through a looping input form (Dynamically) from MySql query result.
<?php
// Query Result
foreach ($sql->result() as $row) {
echo '
<div class="media mt-4">
<div class="media-body text-muted text-small">
<input class="d-none" value="'.$row->cY.'" name="post_X" id="post_X">
<input class="d-none" value="'.$row->cZ.'" name="post_Y" id="post_Y">
<div class="input-group">
<input style="background:#fafafa" type="text" name="post_Z" id="post_Z" placeholder="Join conversation here..." class="form-control">
<div class="input-group-append">
<button type="button" onclick="addPost()" class="btn btn-outline-secondary"><i class="fa fa-send"></i></button>
</div>
</div>
</div>
</div>';
}
?>
Ajax script
<script>
function addPost() {
if(!$("#post_Z").val()) {
// An Alert!
} else {
var post_X = $("#post_X").val();
var post_Y = $("#post_Y").val();
var post_Z = $("#post_Z").val();
$.post("reply.php", {
uid: post_X,
cid: post_Y,
txt: post_Z
}, function (data, status) {
// An Alert!
});
};
}
</script>
Thanks alot
give an id for each iteration, and add the id in the addPost event so that the post only retrieves data according to the id that is defined
change the code to be like this
<?php
// Query Result
$uniq = 1;
foreach ($sql->result() as $row) {
echo '
<div class="media mt-4">
<div class="media-body text-muted text-small">
<input class="d-none" value="'.$row->cY.'" name="post_X_'.$uniq.'" id="post_X_'.$uniq.'">
<input class="d-none" value="'.$row->cZ.'" name="post_Y_'.$uniq.'" id="post_Y_'.$uniq.'">
<div class="input-group">
<input style="background:#fafafa" type="text" name="post_Z_'.$uniq.'" id="post_Z_'.$uniq.'" placeholder="Join conversation here..." class="form-control">
<div class="input-group-append">
<button type="button" onclick="addPost('.$uniq.')" class="btn btn-outline-secondary"><i class="fa fa-send"></i></button>
</div>
</div>
</div>
</div>';
$uniq++;
}
?>
and the ajax
<script>
function addPost(id) {
if(!$("#post_Z_"+id).val()) {
// An Alert!
} else {
var post_X = $("#post_X_"+id).val();
var post_Y = $("#post_Y_"+id).val();
var post_Z = $("#post_Z_"+id).val();
$.post("reply.php", {
uid: post_X,
cid: post_Y,
txt: post_Z
}, function (data, status) {
// An Alert!
});
};
}
</script>
may these help
My jQuery code is not sending a value from the textarea name="post_description"
<form id="post" method="post">
<div class="input-group">
<textarea name="post_description" class="form-control" placeholder="<?php echo $lang['description']; ?>" rows="4" ng-model="description"></textarea>
</div>
<div id="share_result"></div>
<a id="share" class="btn-custom">
<i class="fa fa-th-large"></i> <?php echo $lang['share']; ?>
</a>
</form>
$(document).ready(function() {
$("#share").click(function(e) {
e.preventDefault();
var postimg = $("#post").serialize();
$.post("posts/post_image.php", postimg).done(function(data) {
$("#share_result").html(data);
}).fail(function() {
//alert("Error submitting forms!");
})
})
})
On the backend:
$post_description = $_POST['post_description'];
It's returning as undefined index but the names do match
May be because you prevent event onclick you have to set event prevent on form submit like this :
<form id="post" method="post">
<div class="input-group">
<textarea name="post_description" class="form-control" placeholder="<?php echo $lang['description']; ?>" rows="4" ng-model="description"></textarea>
</div>
<div id="share_result"></div>
<a id="share" class="btn-custom">
<i class="fa fa-th-large"></i> <?php echo $lang['share']; ?>
</a>
<button type="submit" id="postform">Submit form</button>
</form>
When you click on submit button your form will submit and then
$("#post").submit(function (e) {
e.preventDefault();
// here is your code
});
Or if you don't want to add this button you have to change from
var postimg = $("#post").serialize();
to
var postimg = {post_description:$("textarea[name='post_description']").val()};
It was the Angular js conflict so I had to write my own jquery function to replace the angular and keep the same angular beraviour on the page, here is my jquery solution for angular replacement:
<script type="text/javascript">
$(document).ready(function(){
$("#post_description").keyup(function(){
// Getting the current value of textarea
var currentText = $(this).val();
// Setting the Div content
$("#text_output").text(currentText);
//$("#text_output").value(currentText);
$("#text_output").attr("value", currentText);
});
});
</script>
I created a form upload which contains some inputs but when I submitted the form to ajax, ajax was unable to grap the file name.
I keep on getting Notice: Undefined index: userImage in C:\wamp\www\osun\i_admin\php_action\uploadImage.php on line 14 . userImage is the name of the file
index.php
<?php include('header.php'); ?>
<?php include('top.php'); ?>
<?php include('links.php'); ?>
<section class="content">
<div class="container-fluid">
<div class="block-header">
<h2>Worker of the Month</h2>
</div>
<!-- Basic -->
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="card">
<div id="error" class="closeit"></div>
<div id="messages"></div>
<div class="body">
<form enctype="multipart/form-data" id="uploadImageForm">
<div class="form-group form-float">
<div class="form-line">
<input type="text" class="form-control" name="name" id="name">
<label class="form-label">Worker's Name</label>
</div>
</div>
<div class="form-group form-float">
<div class="form-line">
<input type="text" class="form-control" name="dept" id="dept">
<label class="form-label">Department</label>
</div>
</div>
<div class="form-group form-float">
<div class="input-group">
<div class="form-line">
<input type="text" data-type="date" id="date" name="date" placeholder="Date" class="form-control datepicker">
</div>
</div>
</div>
<div class="form-group form-float">
<div class="form-line">
<textarea name="description" id="description" cols="30" rows="5" class="form-control no-resize"></textarea>
<label class="form-label">Description</label>
</div>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Photo</label>
<div id="kv-avatar-errors-2" class="center-block" style="width:800px;display:none"></div>
<div class="kv-avatar center-block" style="width:200px">
<input id="avatar-2" name="userImage" type="file" class="file-loading">
</div>
</div>
<div class="form-group" align="center">
<button type="input" name="submit" class="btn btn-success btn-md btn-icon waves-effect" id="btn-submit" ><i class="fa fa-check-square-o"></i> Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- #END# Basic -->
</div>
</section>
<?php include('footer.php'); ?>
uploadimage.php
include('../../includes/functions.php');
if($_POST) {
$valid = array('success' => false, 'messages' => array());
$name = $mysqli->real_escape_string($_POST['name']);// user name
$dept = $mysqli->real_escape_string($_POST['dept']);
$desc = $mysqli->real_escape_string($_POST['description']);// user email
$yr = $mysqli->real_escape_string($_POST['date']);
$fileName = $_FILES['userImage']['name'];
$type = explode('.', $fileName);
$type = $type[count($type) - 1];
$url = '../user_images/' . uniqid(rand()) . '.' . $type;
if(in_array($type, array('gif', 'jpg', 'jpeg', 'png'))) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
if(move_uploaded_file($_FILES['userImage']['tmp_name'], $url)) {
// insert into database
$sql = "INSERT INTO worker_of_the_month (name, dept, description, given, img) VALUES ('$name','$dept','$desc','$yr', '$url')";
if($mysqli->query($sql) === TRUE) {
$valid['success'] = true;
$valid['messages'] = "Successfully Saved.";
}
else {
$valid['success'] = false;
$valid['messages'] = "Error while saving. " . $mysqli->error;
}
$mysqli->close();
}
else {
$valid['success'] = false;
$valid['messages'] = "Error while saving. " . $mysqli->error;
}
}
}
echo json_encode($valid);
// upload the file
}
Ajax.js
$('document').ready(function() {
/* validation */
$("#uploadImageForm").validate({
rules:
{
name:{
required: true
},
dept:{
required: true
},
description:{
required: true
},
date:{
required: true
},
},
messages:
{
name: "Worker name required",
dept: "Worker department name required",
description: "Enter description for this honour.",
date: "Please select date",
},
submitHandler: submitForm
});
/* validation */
/* form submit */
function submitForm()
{
var data = $("#uploadImageForm").serialize();
$.ajax({
type : 'POST',
url : 'php_action/uploadImage.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#btn-submit").html('<img src="../img/processing.gif" width="30" /> processing');
},
success : function(data)
{
if(data.success == true)
{
$("#btn-submit").html('<img src="../img/processing.gif" width="30" /> Saving ...');
$("#messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
data.messages +
'</div>');
$('#uploadImageForm')[0].reset();
/*setTimeout(' window.location.href = "success.php"; ',4000);*/
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#btn-submit").html('<span class="fa fa-check-square-o"></span> Save');
});
}
}
});
return false;
}
/* form submit */
});
</script>
What am I doing wrong?
You need to use a FormData() to pass files.
Change
var data = $('#uploadImageForm').serialize();
to
var form = $('#uploadImageForm')[0];
var data = new FormData(form);
As #ThisGuyHasTwoThumbs pointed you should set cache, contentType and processData via your ajax call
$.ajax({
cache: false,
processData: false,
contentType: false,
//other ajax parameters
});
You cannot POST files via AJAX like you have your code now.
This is how you can upload files using javascript and way better option:
PHP:
<?php
$fileName = $_FILES['afile']['name'];
$fileType = $_FILES['afile']['type'];
$fileContent = file_get_contents($_FILES['afile']['tmp_name']);
$dataUrl = 'data:' . $fileType . ';base64,' . base64_encode($fileContent);
$json = json_encode(array(
'name' => $fileName,
'type' => $fileType,
'dataUrl' => $dataUrl,
'username' => $_REQUEST['username'],
'accountnum' => $_REQUEST['accountnum']
));
echo $json;
?>
HTML:
<!DOCTYPE html>
<!--
Copyright 2012 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Author: Eric Bidelman (ericbidelman#chromium.org)
-->
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
<title>xhr.send(FormData) Example</title>
</head>
<body>
<input type="file" name="afile" id="afile" accept="image/*"/>
<script>
document.querySelector('#afile').addEventListener('change', function(e) {
var file = this.files[0];
var fd = new FormData();
fd.append("afile", file);
// These extra params aren't necessary but show that you can include other data.
fd.append("username", "Groucho");
fd.append("accountnum", 123456);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'handle_file_upload.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete + '% uploaded');
}
};
xhr.onload = function() {
if (this.status == 200) {
var resp = JSON.parse(this.response);
console.log('Server got:', resp);
var image = document.createElement('img');
image.src = resp.dataUrl;
document.body.appendChild(image);
};
};
xhr.send(fd);
}, false);
</script>
<!--[if IE]>
<script src="http://ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js"></script>
<script>CFInstall.check({mode: 'overlay'});</script>
<![endif]-->
</body>
</html>
Quick example taken from: https://gist.github.com/ebidel/2410898
here it is my html part from where i m trying to enter details ..
<div ng-app="angularPHP">
<div ng-controller="mainpagecntl">
<div id="customer" class="cuscontainer" hidden="hidden">
<div>
<h3 class="modal-title" >Add customer</h3>
<i class="fa fa-times" id="clo" aria-hidden="true"></i>
</div>
<table>
<tr>
<div class="form-group" >
<td><label id="label" class="control-label">customer Name:</label>
<td><input type="text" class="form-control" ng-model="customer_name" />
</div>
</tr>
<tr>
<div class="form-group">
<td><label id="label" class="control-label">Address:</label></td>
<td><input type="text" class="form-control" ng-model="customer_add"/></td>
</div>
</tr>
</table>
<div class="madal-footer">
<button class="btn btn-primary" ng-click="custadd()">ADD</button><br />
</div>
</div>
</div>
</div>
here is my angular-js part..
var app = angular.module('angularPHP', []);
app.controller('mainpagecntl', function($http,$scope)
{
$scope.custadd= function()
{
data={
cname :$scope.customer_name,
cadd: $scope.customer_add,
}
$http.post("../pos_system/Widgets/addcust.php?add",data).success(function(data)
{
});
}
});
but when i click on button nothing happened my ng-click function is not firing.
try adding ng-controller="myCtrl"at the <div id="customer" class="cuscontainer" hidden="hidden"> like this
<div id="customer" class="cuscontainer" hidden="hidden" ng-controller="myCtrl">
Are you sure the function is not firing at all? It may be firing but just failing to post the data. console.log something straight away inside the function to check e.g.
var app = angular.module('angularPHP', []);
app.controller('mainpagecntl', function($http,$scope) {
var vm = this;
vm.custadd = function() {
console.log('test');
var data = { cname :$scope.customer_name, cadd: $scope.customer_add};
$http.post("../pos_system/Widgets/addcust.php?add",data)
.success(function(data) {
console.log(data);
});
}
}
Then your ng-click should look like this
ng-click='vm.custadd()'
See if that makes any difference.
Note: Your ng-controller should also look like
ng-controller="mainpagecntl as vm"
as noted in the comments below.
Here's the working demo https://plnkr.co/edit/k7yApAavre66KFAiVlOp?p=preview for your code and it worked perfectly when I clicked on Add button. Although I have removed some div tags from table as it's bad practice and Angular will not identify those tags when its directives are used on them.
var app = angular.module('angularPHP', []);
app.controller('mainpagecntl', function($http, $scope) {
$scope.custadd = function() {
$scope.data = {
cname: $scope.customer_name,
cadd: $scope.customer_add,
}
// $http.post("../pos_system/Widgets/addcust.php?add", data).success(function(data) {});
}
});
I've been working with Ajax to send and upload files, everything worked perfect, I could upload both photos and files with no problem, but now it just don't work for .pdf files.
This is why I got, from my jQuery file:
function uploadImage(){
$('#file').change(function(){
var file = this.files[0]
if(file){
$('.alert.alert-danger').hide();
$('#filename').text(file.name);
$('#filename').show();
$('.cargando').show();
$('.uploaded').hide();
$('#file').hide();
name = file.name;
size = file.size;
type = file.type;
uploadAjax();
}
});
$('#uploadremove').click(function(e){
e.preventDefault();
$('.alert.alert-danger').hide();
$('#file').show();
$('.cargando').hide();
$('#filename').hide();
$('#uploadok').hide();
$('#uploadremove').hide();
$('#file_id').val("0");
$('.fileinput-button').show();
$('.savebtn').toggleClass('disabled');
$('.uploaded').hide();
});
}
function uploadAjax(){
var inputFileImage = document.getElementById("file");
var filelocation = $('#file').val();
var file = inputFileImage.files[0];
var info = new FormData();
var tipo_archivo = $("#file").attr('accept');
var tipo_archivo = type;
info.append('tipo', tipo_archivo); console.log(file);
var url = HTTP+"admin/uploadfile";
$.ajax({
url:url,
type:'POST',
contentType:false,
data: info,//{archivo : file, tipo : tipo_archivo},
processData:false,
cache:false,
success:function(response){
if(response != '' && !($.isNumeric(response)) ){
$('.alert.alert-danger #uploaderror').html(response);
$('.alert.alert-danger').fadeIn(2000);
$('.cargando').hide();
$('#filename').hide();
$('#file').show();
}
else{
$('.cargando').hide();
$('#uploadok').show();
$('#uploadremove').show();
$('#file_id').val(response);
$('.fileinput-button').hide();
$('.savebtn').toggleClass('disabled');
if(tipo_archivo == "image/*"){
console.log(file);
}
}
}
});
}
And this is the HTML form:
<form class="form-horizontal validate" role="form" method="post" action="<?=fk_link().'admin/savecv'?>">
<input name="location" type="hidden" class="location" value="admin/addcv/<?=#$profesor['id']?>" >
<input name="profesor_id" type="hidden" value="<?=#$profesor['id']?>" >
<div class="form_message">
<div class="alert alert-warning">
</div>
</div>
<?
$texto = "Seleccionar Archivo PDF";
if(#$profesor['profesor_cv']){ $texto = "Cambiar Cv";?>
<div class="uploaded">
<a class="btn btn-success fileDownloadPromise" target="_blank" href="<?=fk_link().'uploads/'.#$cv['cv']?>">
<i class="glyphicon glyphicon-cloud-download"></i>
<span>Descargar</span>
</a>
</div>
<?
} else $texto = "Seleccionar Archivo PDF";?>
<span class="btn btn-danger fileinput-button">
<i class="glyphicon glyphicon-cloud-upload"></i>
<span><?=$texto?></span>
<!-- The file input field used as target for the file upload widget -->
<input id="file" type="file" name="fileToUpload" id="filesToUpload">
</span>
<span class="cargando"><img src="<?=fk_theme_url().'/images/loading.gif'?>"></span>
<span id="filename"></span>
<input id="file_id" name="file_id" type="hidden" value="0" >
<span id="uploadok" class="glyphicon glyphicon-ok"></span>
Cambiar
<div class="clearfix" style="height:10px"></div>
<div class="alert alert-danger col-md-3" style="display:none;">
<span class="glyphicon glyphicon-warning-sign"></span>
<span id="uploaderror">error example</span>
</div>
<input class="btn btn-primary savebtn disabled" value="Guardar" type="submit">
</form>
As I said, everything worked fine but now it only works with images.
info.append('tipo', tipo_archivo);
Up there should be:
info.append('tipo', file);