I have created a chatbot using rivescript and javascript. I want to save the user's messages and chatbot responses to a database.
In html code I have made this form for the messages:
<div id="dialogue"></div>
<form onSubmit="return chatbot.sendMessage()">
<div class="text-box">
<input type="text" name="message" id="message" autocomplete="off" placeholder="Please wait... loading...">
<input class="send-button" type="submit" value=" " id="butsend">
</div>
</form>
</div>
I used a php file named connect.php to connect with the db.
I modified the command:
<form onSubmit = "return chatbot.sendMessage ()"> to
<form onSubmit = "return chatbot.sendMessage ()" method = "POST" "action =" connect.php>
resulting in the user's first message being entered in the database and then a new blank page appearing instead of the dialog.
Ιs there any way to continue the dialogue and at the same time store the data in the database when the send button is pressed?
I have solved the problem using this function:
function writetoDB(inputmessage, outputmessage){
$.ajax({
url: "save.php",
type: "POST",
data: {
user: inputmessage,
botreply: outputmessage,
},
cache: false,
success: function(dataResult){
}
})
}
that calls the php file:
<?php
include 'database.php';
$user=$_POST['user'];
$botreply=$_POST['botreply'];
$sql = "INSERT INTO `dialogs`( `user`, `bot`)
VALUES ('$user','$botreply')";
if (mysqli_query($conn, $sql)) {
echo json_encode(array("statusCode"=>200));
}
else {
echo json_encode(array("statusCode"=>201));
}
mysqli_close($conn);
?>
My problem now is that not all values are imported in database. For example, if there are 20 messages, only 10 are written to the db.
Related
Background
I am a complete beginner to web designing and i am using PHP and mySQL.
Code in hand
This is my HTML file named UserRegistration.php
<?php
session_start();
?>
<html>
<body>
<script>
function FillRecord(Id)
{
$.ajax({
type: "POST",
url: "Algorithm/UserRegistration-FillUserRecords.php",
data:'Id='+Id,
success: function(data)
{
document.forms["Frm_User"].elements["txtName"].value = "";
document.forms["Frm_User"].elements["txtFName"].value = "";
document.forms["Frm_User"].elements["txtMName"].value = "";
}
});
}
</script>
<form id="Frm_User" name="Frm_User" method="POST" action="Algorithm/UserRegistration-SaveDetails.php">
<label for="txtName">Name</label>
<input type="text" name="txtName" placeholder="Name" required>
<label for="txtFName">Father Name</label>
<input type="text" name="txtFName" placeholder="Father Name" required>
<label for="txtMName">Mother Name</label>
<input type="text" name="txtMName" placeholder="Mother Name" required>
</form>
<input type="button" onclick="FillRecord(1);">//1 is fixed at the moment
</body>
</html>
This is my PHP class named UserRegistration-FillUserRecords.php
<?php
session_start();
include_once 'Connection.php';
if ($dbcon->connect_error)
{
die("Connection failed: " . $dbcon->connect_error);
header('Location: ../UserRegistration.php');
exit();
}
//Search data from database on all fields except "SNo"
//----------------------------------------------------------------------------
$sql = "Select * from usertable where id=".$_POST["Id"];
$result = $dbcon->query($sql);
$rows = array();
foreach ($result as $RowRecord)
{
$_SESSION['UserRegistration_txtName'] = $RowRecord["Name"];
$_SESSION['UserRegistration_txtFName'] = $RowRecord["FName"];
$_SESSION['UserRegistration_txtMName'] = $RowRecord["MName"];
}
exit();
?>
The Algorithm/UserRegistration-SaveDetails.php is used to save the user details into database which is working perfectly.
Problem
I want to show the data which is being retrieved by UserRegistration-FillUserRecords.php into UserRegistration.php's already created textbox when the function FillRecord is called but i have no clue as to how to assign the session variable value to my input boxes.
I Tried
1) alert(<?php echo $_SESSION['UserRegistration_txtName']; ?>);
but the statement doesn't seem to work even when i have used
2) success: function(data) in AJAX reponse has the value which i need but when i echo it, it shows the value in continuation like:-
abc
----------------
a (Name)
b (Father Name)
c (Mother Name)
and i cant seperate it as the string can be anything, it can be full of comma's, new line characters and any special symbols
Your PHP code doesn't actually output those session variables you've created to the browser. To do that, you need something like this (I'm using JSON as the format in which to send the data, as it's easiest to work with on the receiving end).
foreach ($result as $RowRecord)
{
$_SESSION['UserRegistration_txtName'] = $RowRecord["Name"];
$_SESSION['UserRegistration_txtFName'] = $RowRecord["FName"];
$_SESSION['UserRegistration_txtMName'] = $RowRecord["MName"];
}
// Create an array to send the data
$data = [
'Name' => $_SESSION['UserRegistration_txtName'],
'FName' => $_SESSION['UserRegistration_txtFName'],
'MName' => $_SESSION['UserRegistration_txtMName']
];
// Tell the browser that a JSON data file is coming
header('Content-type: application/json');
print json_encode($data);
exit();
Your jQuery AJAX handler function can then easily populate the form with these values:
function FillRecord(Id)
{
$.ajax({
type: "POST",
url: "Algorithm/UserRegistration-FillUserRecords.php",
data:'Id='+Id,
dataType: "json", //Add this so data comes back as an Object
success: function(data)
{
document.forms["Frm_User"].elements["txtName"].value = data.Name;
document.forms["Frm_User"].elements["txtFName"].value = data.FName;
document.forms["Frm_User"].elements["txtMName"].value = data.MName;
}
});
}
I hope I've correctly understood (and satisfied) what you want to achieve, please feel free to say if not.
I was wondering why this code won't work for me. I am trying to append value from database into input field of this submit button as I want to send it back to another table in my database. Thanks!
</div>
<form>
<input type="input" value="'+ jobpost.jobID+'" id="jobID"/>
<br>
<button type="submit" id="submit3" name="submit3"
onclick="myFunctionjobStatus();">Submit</button></form></div>
I am using the following ajax post to send data to my php file to enter into the database. Please see below.
function myFunctionjobStatus() {
var jobID = document.getElementById("jobID").value;
//AJAX code to submit form.
$.ajax({
type: "POST",
url: "http://localhost:8888/EduSubOct/jobstatus.php",
data: { userEmail: localStorage.getItem("email"), jobID:
jobID},
cache: false,
success: function(html) {
alert("Request Sent");
}
});
}
php file -
<?php
// Selecting Database
include_once 'dbh.php';
/Here we fetch the data from the URL that was passed from our HTML
form
$userEmail = $_POST['userEmail'];
$jobID = $_POST['jobID'];
$sql = "INSERT INTO jobStatus (email, jobID) VALUES
('$userEmail','$jobID');";
mysqli_query($conn, $sql);
?>
I am trying to implement a simple form which will eventually connect to a database and make entries in it. In the tag,I am calling the php file which will connect me to the database in the back-end.
index.html
<html>
<head>
<script>
function submitForm(formId){
//var formData= $.(formId).serialize();
$.ajax({
url:'new-user.php',
type:'POST',
data:{
user_name=$("#user_name").val(),
password=$("#password").val();
}
success:function(response){
alert(response);
}
});
}
</script>
</head>
<body>
<form onsubmit="submitForm('#myForm');" id='myForm'>
User Name: <input type="text" name="user_name" id="user_name" />
Password: <input type="text" name="password" id="password" />
<input type="submit"/>
</form>
</body>
</html>
new-user.php
<?php include 'database.php';?>
<?php
mysqli_query($connect,"create table login(User_name varchar(50) NOT NULL,Password varchar(50) NOT NULL)");
$user_name=$_POST['user_name'];
$password=$_POST['password'];
if(empty($user_name)){
$name_error="name is required";
}
mysqli_query($connect,"Insert into login(User_name,Password) values('$user_name','$password')");
if(mysqli_affected_rows($connect)>0){
echo "<p>Credentials added</p>";
echo "<a href='index.html'>Go back</a>";
}else{
echo "<p>Error</p>";
echo mysqli_error($connect);
}
?>
database.php
<?php
$connect=mysqli_connect('localhost','root','','testdb');
if(mysqli_connect_errno($connect)){
echo 'failed to connect';
}
?>
The above is not creating any table in the testdb database.Neither,it is generating any alert messages.The Url however changes after clicking the submit button as http://localhost/try2/?user_name=aayushi&password=ded but after that nothing happens. This is my first php code, so I don't really know what's the meaning of this exactly.
Okay, since no one seems to actually be reading your code, there's a couple of syntax errors that I missed until I threw it into PhpStorm
Change your function to this:
function submitForm(formId){
$.ajax({
url:'/new-user.php',
type:'POST',
data:{
user_name: $("#user_name").val(),
password: $("#password").val()
}
})
.complete(function (response) {
alert(response)
})
return false; // Prevents the form from submitting the standard way
}
EDIT: Change the form to this:
<form onsubmit="return submitForm('#myForm');" id='myForm'>
In your ajax method, the success property is wrong
It is written as suceess, when it was supposed to be success
Also, to avoid refreshing the page, insert return false; at the end of the function submitForm
I make this form to send data to a php page in another domain but always it results error. can someone explain my problem
I search in Internet many times but exactly I didnt find my answer
here is my code
html:
<form action="#" id="smail" method="post" class="form">
<input type="text" name="name" value="Your Name *">
<input type="text" name="mailadd" value="Your E-mail *">
<textarea name="message" cols="0" rows="0">Your Message *</textarea>
<input type="submit" value="send message">
</form>
js:
$('#smail').submit(function(event) {
event.preventDefault();
var mail = $("#smail input[name=name]").val();
var message = $("#smail input[name=mailadd]").val()+' '+$("#smail textarea[name=message]").val();
$.ajax({
type: "POST",
url:"http://cofeebeen.dx.am/email.php",
crossDomain: true,
data:{
"mail": mail,
"message": message,
},
dataType: "text",
error: function(){
alert("error")
}
}).success(function(result){
alert(result)
});
});
php:
<?php
$subject = $_POST["mail"];
$msg = $_POST["message"];
mail("someone#example.com",$subject,$msg);
?>
Your PHP code is not correct, we can get data at your PHP page like below.
Correct code:
$subject = $_POST["mail"];
$msg = $_POST["message"]
Incorrect code:
$subject = $_POST["name"];
$msg = $_POST["mailadd"]
I hope it will work now.
Per #mpf82's comment, if this is a cross domain request, that changes things. However, the AJAX request is currently passing 2 PHP post variables:
...
data:{
"mail": mail,
"message": message,
},
...
And you reference 3:
$_POST['name'];
$_POST['mailadd'];
$_POST['message'];
As #Reghbendra pointed out, you are referencing the incorrect variable names. Plus, since you did the concatenation of mailadd and message in Javascript, you can skip that part in PHP.
Therefore, your code would need to reference the two post variables that were passed by their proper indexes.
Result code:
<?php
$subject = $_POST["mail"];
$msg = $_POST["message"];
mail("someone#example.com",$subject,$msg);
?>
You also should consider the headers for the PHP mail function to ensure that it sends properly and is handled correctly. See the documentation for the function here.
not sure what im missing but im having a few issues with my code im trying to build.
The data is not passing from the form to the database (blank entries)
Its also going to repsonse.php and not staying on the forms page
How can i pass the response for success and error back from response.php to the form to display on the frontend form?
Lastly its adding the data twice (blank entries but twice all the same)
HTML
<form action="response.php" method="post" id="add_product">
<input type="hidden" name="action" value="add_product">
<div class="row">
<div id="response" class="alert alert-success" style="display:none;">
×
<div class="message"></div>
</div>
<div class="col-xs-4">
<input type="text" class="form-control" id="product_name" placeholder="Enter product name">
</div>
<div class="col-xs-4">
<input type="text" class="form-control" id="product_desc" placeholder="Enter product description">
</div>
<div class="col-xs-4">
<div class="input-group">
<span class="input-group-addon"><?php echo CURRENCY ?></span>
<input type="text" id="product_price" class="form-control" placeholder="0.00" aria-describedby="sizing-addon1">
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 margin-top btn-group">
<input type="submit" id="action_add_product" class="btn btn-success float-right" value="Add product" data-loading-text="Adding...">
</div>
</div>
RESPONSE.PHP
//check if any connection error was encountered
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
$action = isset($_POST['action']) ? $_POST['action'] : "";
// Adding new product
if($action == 'add_product') {
$data = $_POST['serialize']; // serialize the data
$product_name = $data['product_name'];
$product_desc = $data['product_desc'];
$product_price = $data['product_price'];
//our insert query query
$query = "INSERT INTO products SET
product_name = '".$product_name."',
product_desc = '".$product_desc."',
product_price = '".$product_price."'
";
//execute the query
if($mysqli -> query($query)) {
//if saving success
echo "User was created.";
} else {
//if unable to create new record
echo "Database Error: Unable to create record.";
}
//close database connection
$mysqli -> close();
}
SCRIPTS.JS
// add product
$('#action_add_product').click(function(){
var $btn = $(this).button('loading');
$.ajax({
url: 'response.php',
type: 'POST',
data: $('#add_product').serialize(),
success: function(result){
$('#response .message').html('Product has been added successfully!');
$('#response').fadeIn();
$btn.button('reset');
}
});
});
The data is not passing from the form to the database (blank entries)
You're missing name attributes on your form inputs. Debugging the output of $('#add_product').serialize() verifies this.
Its also going to repsonse.php and not staying on the forms page
You can set the form action to # (as Harigovind points out), I prefer to bind the submit event of the form instead, and prevent the default execution of the form. This also fixes the issue of people not pressing the button (firing your click event) but using the enter key instead:
$("#add_product").on("submit", function(e) {
e.preventDefault(); // prevent default POST of form
$.ajax({
// etc
});
});
JSFiddle: https://jsfiddle.net/trL5t80w/
Your form is submitting when you click on #action_add_product button. If you want use ajax, you can:
Change your #action_add_product element from button to a with href='#' - that prevent your form from being submitted
Change your js code $('#action_add_product').click(function(){ to something like this: $('#add_product').submit(function(e){
e.preventDefault();
Hi the issue you are facing is because your data is getting posted twice. Since you are using ajax you dont have to give form action. You can replace it by a '#' symbol.
You can also use the jquery prevent default function to prevent the default posting of the form.
Your echo in Response.php will act only as the response to athe ajax call so even if your database query is not executed the result will be you have successfully created the fields.
Also check if your serialized values are correct.
You can get the values of the serialized data just by replacing
$data = $_POST['serialize']; // serialize the data
$product_name = $data['product_name'];
$product_desc = $data['product_desc'];
$product_price = $data['product_price'];
these with
//$data = $_POST['serialize'];
$product_name = $_POST['product_name'];
$product_desc = $_POST['product_desc'];
$product_price = $_POST['product_price'];
You are missing the name attribute of your fields. Any ajax request equivalent to $_GET or $_POST needs the fields.