JAVASCRIPT - jQuery - Inserting value into input field - javascript

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);
?>

Related

how to insert data information in db using html and javascript

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.

PHP : How to get value from DB to already created textbox

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.

Ajax Button to fetch data without refresh?

I would like to know how a button submit can interact with AJAX to SELECT FROM data as a MySQL query without refreshing the page . I already have a text box interacting with AJAX so that the page does not refresh when the user inputs the text and presses enter but have no idea how to make the button do it my code below shows how im getting the text box to insert data without refreshing
Here is my script for the textbox
<div id="container">
About me<input type="text" id="name" placeholder="Type here and press Enter">
</div>
<div id="result"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "about_me_action.php",
data: {name: info},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
};
});
});
</script>
Here is the action
<?php
if (isset($_POST['name'])) {
echo '<h1>'.$_POST['name'];
include('..\db.php');
$con = mysqli_connect($dbsrvname, $dbusername, $dbpassword, $dbname);
$name = $_POST['name'];
$name= mysqli_real_escape_string($con, $name);
$q = mysqli_query($con,"SELECT * FROM tbl1 WHERE username = '".$_COOKIE[$cookie_name]."'");
while($row = mysqli_fetch_assoc($q)){
//echo $row['id'];
$id = $row['id'];
}
$result=$con ->query=("REPLACE INTO about_user (about_me,number) VALUES ('".$name."','".$id."')");
$insert = $con->query($result);
echo "About Me Updated";
}
?>
Now all I need to do is have the below example of a button do something similar but instead of INSERTING just SELECT , how can i change the above script to allow a button to handle the action please?
<form
action="action_mail_view.php" method="post">
<input type="submit" class="button" name='msubmit' value="View Mail"/>
</form>
function callServer() {
$('#mail-button').on('click', function() {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "about_me_action.php",
data: {
name: info
},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
});
}
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
$('#mail-button').trigger('click');
};
});
});
<form action="action_mail_view.php" method="post">
<input type="submit" class="button" id="mail-button" name='msubmit' value="View Mail" />
</form>
You haven't showed us how you tried to make your button work so how can we give you feedback? Basically you want a similar ajax call that calls action_mail_view.php using the GET method
Ajax
$.ajax({
method: "GET",
url: "action_mail_view.php",
data: {},
success: function(results) {
var userinfo = JSON.parse(results);
//Todo: do what you want with the user's info
}
});
On the PHP side, you should first authenticate the user (not shown here), then SELECT her info from the DB and return it
action_mail_view.php
//Todo: authenticate
//this works with your setup, but it's a bad idea to trust
//a cookie value or anything else coming from the
//browser without verification
$username= mysqli_real_escape_string($con, $_COOKIE[$cookie_name]);
//get the user's info from your DB. By using a JOIN, we can execute
//just one query instead of two.
$sql = "SELECT t2.* FROM tbl1 as t1 "
."LEFT JOIN about_user as t2 "
."ON t1.id = t2.number"
."WHERE t1.username = $username";
//Todo: execute query. see what results you get and refine
// the SELECT clause to get just what you want
if($q = mysqli_query($con,$sql)):
$userinfo = mysqli_fetch_assoc($q);
//tell the browser to expect JSON, and return result
header('Content-Type: application/json');
echo json_encode($userinfo);
else:
//Todo: error handling
endif;

Updating div content with jQuery ajax function over PHP

I am trying to update my div content (#update_div) by sending the value of two input fields to a php file (search_value.php) using the .ajax() function from jQuery.
It works, if I just redirect the two values of the input fields using the html form POST method. So the search_value.php should be correct.
My HTML Code:
<form id="my_form">
<input id="food" name="food">
<input id="amount" value="amount in gram" name="amount">
<input type="button" value="Update" id="submit" name="submit" />
</form>
<div id="update_div">
</div>
My Javascript Code:
$("#submit").click(function() {
var food = $("#food").val();
var amount = $("#amount").val();
$.ajax({
url: 'search_value.php',
type: 'GET',
data: {"food":food,"amount":amount},
success: function(data)
{
$('#update_div').html(data);
}
});
});
My PHP Code:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=calotools', 'root', '');
$food = $GET_['food'];
$amount = $GET_['amount'];
$query="SELECT * FROM nahrungsmittel WHERE name = '$food'";
$user = $pdo->query($query)->fetch();
echo $user['name']."<br />";
echo $user['kcal'] / 100 * $amount;
?>
I do not really get a feedback by clicking the button. Maybe you guys can tell me why?
For GET request, there should not be data part, make it as a query string as below js code:
$("#submit").click(function() {
var food = $("#food").val();
var amount = $("#amount").val();
$.ajax({
url: 'search_value.php?food='+ food + '&amount='+amount,
type: 'GET',
datatype: "html",
success: function(data)
{
$('#update_div').html(data);
},
failure : function(ex)
{
console.log(ex);
}
});
});
And use $_GET instead of $GET_ in php
Are you running your code after the page has loaded? I've made that mistake several times, and if you're not, I suggest wrapping the whole thing in a $(function(){ /* Everything you have */ });
I prefer using post
in your php script replace $GET_ by $_POST
<?php
$pdo = new PDO('mysql:host=localhost;dbname=calotools', 'root', '');
$food = $_POST['food'];
$amount = $_POST['amount'];
$query="SELECT * FROM nahrungsmittel WHERE name = '$food'";
$user = $pdo->query($query)->fetch();
echo $user['name']."<br />";
echo $user['kcal'] / 100 * $amount;
?>
in your javascript code the result is found in data.responseText
here the new script
$("#submit").click(function() {
var food = $("#food").val();
var amount = $("#amount").val();
$.ajax({
url: 'search_value.php',
type: 'POST',
data: {"food":food,"amount":amount},
success: function(data)
{
$('#update_div').html(data.responseText);
}
});
});
Tested and your JavaScript code works. The issue may be in the PHP code.
Have you tried correcting the "$_GET" as suggested by others?

How to Modify PHP/Jquery/Ajax script to have more than one form field posst

I have an php/Ajax/Jquery script that inserts a form field into MySQL and updates the page without refreshing when you hit submit. I would like the script to submit four form fields, instead of just one.
I have already updated the database table add_delete_record with 3 additional fields: balance, account_number and monthly, plus the content field that was already there.
Below is probably overkill of code because I only need to modify a few lines, but I figured this would answer all the questions.
This is the php & html page:
<div class="content_wrapper">
<ul id="responds">
<?php
//include db configuration file
include_once("config.php");
//MySQL query
$Result = mysql_query("SELECT id,content FROM add_delete_record");
//get all records from add_delete_record table
while($row = mysql_fetch_array($Result))
{
echo '<li id="item_'.$row["id"].'">';
echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$row["id"].'">';
echo '<img src="images/icon_del.gif" border="0" />';
echo '</a></div>';
echo $row["content"].'</li>';
}
//close db connection
mysql_close($connecDB);
?>
</ul>
<div class="form_style">
<textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea>
<button id="FormSubmit">Add record</button>
</div>
</div>
This is the php it posts to:
<?php
//include db configuration file
include_once("config.php");
//check $_POST["content_txt"] is not empty
if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0)
{
//sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH
$contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
// Insert sanitize string in record
if(mysql_query("INSERT INTO add_delete_record(content) VALUES('".$contentToSave."')"))
{
//Record is successfully inserted, respond to ajax request
$my_id = mysql_insert_id(); //Get ID of last inserted record from MySQL
echo '<li id="item_'.$my_id.'">';
echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">';
echo '<img src="images/icon_del.gif" border="0" />';
echo '</a></div>';
echo $contentToSave.'</li>';
mysql_close($connecDB);
}else{
//output error
//header('HTTP/1.1 500 '.mysql_error());
header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
exit();
}
}
elseif(isset($_POST["recordToDelete"]) && strlen($_POST["recordToDelete"])>0 && is_numeric($_POST["recordToDelete"]))
{//do we have a delete request? $_POST["recordToDelete"]
//sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign.
$idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT);
//try deleting record using the record ID we received from POST
if(!mysql_query("DELETE FROM add_delete_record WHERE id=".$idToDelete))
{
//If mysql delete record was unsuccessful, output error
header('HTTP/1.1 500 Could not delete record!');
exit();
}
mysql_close($connecDB);
}else{
//Output error
header('HTTP/1.1 500 Error occurred, Could not process request!');
exit();
}
?>
This is the JQuery
$(document).ready(function() {
//##### Add record when Add Record Button is clicked #########
$("#FormSubmit").click(function (e) {
e.preventDefault();
if($("#contentText").val()==="") //simple validation
{
alert("Please enter some text!");
return false;
}
var myData = "content_txt="+ $("#contentText").val(); //post variables
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //post variables
success:function(response){
$("#responds").append(response);
$("#contentText").val(''); //empty text field after successful submission
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); //throw any errors
}
});
});
//##### Delete record when delete Button is clicked #########
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
var clickedID = this.id.split("-"); //Split string (Split works as PHP explode)
var DbNumberID = clickedID[1]; //and get number from array
var myData = 'recordToDelete='+ DbNumberID; //build a post data structure
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //post variables
success:function(response){
//on success, hide element user wants to delete.
$('#item_'+DbNumberID).fadeOut("slow");
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
});
});
});
This is not my script so I thought I should also give a link to credit the author of it:
http://www.sanwebe.com/2012/04/ajax-add-delete-sql-records-jquery-php
i'm no php expert, but this should get you through:
First change the form area on the main page:
<div class="form_style">
<textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea><br/>
<input type="text" id="balance" /><br/>
<input type="text" id="acctNum" /><br/>
<input type="text" id="monthly" /><br/>
<button id="FormSubmit">Add record</button>
</div>
then your myData looks like this:
var myData = {
content_txt: $("#contentText").val(),
balance: $("#balance").val(),
acctNum: $("#acctNum").val(),
monthly: $("#monthly").val()
};
and later in the ajax response:
$("#contentText").val(''); //empty text field after successful submission
$("#balance").val('');
$("#acctNum").val('');
$("#monthly").val('');
and finally the PHP:
//sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH
$content = filter_var($_POST['content_txt'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$balance = filter_var($_POST['balance'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$account = filter_var($_POST['acctNum'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$monthly = filter_var($_POST['monthly'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$qry= "INSERT INTO add_delete_record(content,balance,account,monthly) VALUES('".$content."','".$balance."','".$account."','".$monthly."')";
// Insert sanitize string in record
if(mysql_query("INSERT INTO add_delete_record(content,balance,account,monthly) VALUES('".$content."','".$balance."','".$account."','".$monthly."')"))
{
//Record is successfully inserted, respond to ajax request
$my_id = mysql_insert_id(); //Get ID of last inserted record from MySQL
echo '<li id="item_'.$my_id.'">';
echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">';
echo '<img src="images/icon_del.gif" border="0" />';
echo '</a></div>';
echo $content.'</li>';
mysql_close($connecDB);
}else{
//output error
//header('HTTP/1.1 500 '.mysql_error());
header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
exit();
}
var myData = {
content_txt: $("#contentText").val(),
other_var: $("#anotherField").val()
};
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //post variables
success:function(response){
$("#responds").append(response);
$("#contentText").val(''); //empty text field after successful submission
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); //throw any errors
}
});
This is an easier way to send several fields (notice the myData object). In PHP you can retrieve and save your new variable like this:
//check $_POST["content_txt"] is not empty
if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0 && !empty($_POST["other_var"])) // !empty() checks that the variable is set and not empty
{
//sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH
$contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$otherVarToSave = filter_var($_POST["other_var"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
// Insert sanitize string in record
if(mysql_query("INSERT INTO add_delete_record(content, other) VALUES('".$contentToSave."', '".$otherVarToSave."')"))
{
Something like this:
var myData = "content_txt="+ $("#contentText").val()+"&other_value"+ $("#foo").val(); //post variables
In the php file:
$other_value = $_POST['other_value'];
UPDATE:
balance, account_number and monthly
JS:
var myData = "content_txt="+ $("#contentText").val()+"&balance"+ $("#balance").val();
myData = myData + "&account_number="+$('#acnum').val()+"&monthly="+$('#month').val();
PHP:
$content = filter_var($_POST['content_txt'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$balance = filter_var($_POST['balance'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$account = filter_var($_POST['account_num'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$monthly = filter_var($_POST['monthly'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$qry= "INSERT INTO add_delete_record(content,balance,account,monthly) VALUES('".$content."','".$balance."','".$account."','".$monthly."')";
if(mysql_query($qry)){

Categories