Script not posting information from dropdown to textbox - javascript

I am trying to get data from a dropdown and post it to a textbox. But by some reason I dont get any response also the Error message that needs to be shown in the textbox.
First of all, this is my dropdown:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM products";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control' id='product1' name='product1' onChange='getProduct1(this.value)' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["article_id"]. " | " . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
After selecting a item in the dropdown the scripts needs to paste . $row["name"]. into the following textbox:
<input type="text" class="form-control" id="product11" name="product11">
The jquery script that I am using to paste the name is the following script:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getProduct1(selectedItem) { // Do an Ajax request to retrieve the information
console.log("getProduct1 before ajax", jQuery('#product1').val());
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: {'product1' : jQuery('#product1').val()},
success: function(response){
// and put the price in text field
console.log("getProduct1 after ajax", jQuery('#product1').val());
jQuery('#product11').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
The script uses the following PHP script that connects with the database and retrieves the relevant information:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error) ;
}else {
$product1 = isset($_POST['produc1t'])?$_POST['product1']:'';
$product11 = isset($_POST['product11'])?$_POST['product11']:'';
$query = 'SELECT * FROM products WHERE id="' . mysqli_real_escape_string($conn, $product1) . '"';
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0) {
$result = mysqli_fetch_assoc($res) ;
echo $result['product11'];
}else{
$result = mysqli_fetch_assoc($res) ;
echo "Error";
}
}
?>
When I run the script by selecting an option in the dropdown, nothing is happening. Does anyone know what is wrong with my script?

I am not sure you should query the database again for a value you already retrieved. Something like this should work:
jQuery( document ).ready(function() {
jQuery( "#product1" ).change(function(){
var name = jQuery( "#product1 option:selected" ).text().split('|')[1];
jQuery("#product11").val(name);
});
});
You don't need the javascript/jQuery command in the HTML

Related

display result only if payload=1

I need help with the script. I want to show the result on page only when payload=1,if payload=0 do not display..
I've tried messing with mysql statements and I realized I need to change that in my script
this is my php:
<?php
$dbhost = "localhost";
$dbuser = "user";
$dbpass = "pass";
$dbname = "rooms";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br>';
$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 ORDER
BY id DESC LIMIT 1 ";
$retval = mysqli_query( $conn, $sql );
if(! $retval ) {
die('Could not get data: ' . mysqli_error());
}
while($row = mysqli_fetch_assoc($retval)) {
echo "ID: " . $row["id"]. "<br>";
echo "Topic: " . $row["topic"]. "<br>";
echo "Payload: " . $row["payload"]. "<br>";
echo "Timestamp: " . $row["DateTime_created"]. "<br>";
}
mysqli_free_result($retval);
echo "Fetched data successfully\n";
mysqli_close($conn);
my database is:
rooms
table:room1
ID
topic
payload
DateTime_created
and my index.html
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
sendRequest();
function sendRequest(){
$.ajax({
url: "vineri.php",
success:
function(data){
$('#listposts').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setInterval(sendRequest, 5000); // The interval set to 5 seconds
}
});
};
});
</script>
</head>
<body>
<div id="listposts"> </div>
</body>
How do I get the result to display only when the payload is 1 ?
Try this code. I have re-written it for you. I run and tested it and it works for me.
First create table and insert as follows..
create table room1(ID int primary key auto_increment, topic varchar(30), payload int(11), DateTime_created timestamp);
insert into room1(topic, payload) values ('nancy topic 1', 1);
insert into room1(topic, payload) values ('nancy topic 2', 0);
here is vineri.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "pass";
$dbname = "rooms";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 where payload='1' ORDER BY ID DESC LIMIT 1";
$retval = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($retval)){
echo "ID: " . $row["ID"]. "<br>";
echo "Topic: " . $row["topic"]. "<br>";
echo "Payload: " . $row["payload"]. "<br>";
echo "Timestamp: " . $row["DateTime_created"]. "<br>";
}
?>
index.html
<html><head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
// set for formality. though you can pass it to backend as a variable
var payload= 1;
var datasend = "payload="+ payload;
$.ajax({
type:'POST',
url:'vineri.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
$('#listposts').fadeIn('slow').prepend(msg);
}
});
});
</script>
</head>
<body>
<div id="listposts"> </div>
</body>
WARNING: ID and id may not be the same as its cap intensive. You can see that In my table creations and sql queries I used ID instead of id. so becareful of capital and small letter that you use
Updated content
Sorry for being late. I don not understand properly what you want. Here is just what I guessed you want
if you want to get last rows with last ID of 200 then
$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 where ID='200' ";
by using limit 1, only one rows will be retrieved.
if you want to get last rows with last id of 200 where payload is 0
$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 where ID='200' and payload='0' ";
Here is how I edited the code. you can test various sql queries that i commented
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "pass";
$dbname = "rooms";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 where payload='0'";
//if you want to get last rows with last id of 200 where payload is 0
//$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 where ID='200' and payload='0' ";
//if you want to get last rows with last ID of 200 then
$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 where ID='200' ";
$retval = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($retval)){
$ID = $row["ID"];
$topic = $row["topic"];
$payload = $row["payload"];
$DateTime_created = $row["DateTime_created"];
}
if($payload ==0){
// insert record here
// return payload to the screen
echo "success<br><br>";
echo "ID: " . $ID. "<br>";
echo "Topic: " . $topic. "<br>";
echo "Payload: " . $payload. "<br>";
echo "Timestamp: " . $DateTime_created. "<br>";
}else{
//cannot insert record
echo "failed";
}
?>

How to link my simple jQuery Input with PHP script and Store data into a MYSQL DB?

What I'm trying to do is very simple.
Have a simple input, that allows me to input a name+link, add it to a list and save it to a DB so it's saved.
In my HTML file I currently have:
<form id="form">
<input id="create-input" type="text" placeholder="To do">
<input id="create-link" type="text" placeholder="http://">
<button id="submit" type="button">Add Item</button>
</form>
In my JS file I have:
$(function(){
$('#submit').on('click', addListItem);
});
function addListItem() {
// Grab Input Data
var text = $('#create-input').val();
var link = $('#create-link').val();
// Creating To Do List
$('#todo').append('<li>' +text+' - '+link+ ' <button class="delete">Edit</button> <button class="delete">Delete</button> <button class="delete">Bukkaked!</button></li>');
$('#create-input').val('');
$('#create-link').val('http://');
}
In my PHP file (connecting to DB) I have:
<?php
$servername = "localhost";
$database = "bucketlist";
$username = "bucketuser";
$password = "125632";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "INSERT INTO bucketlist (item, link) VALUES ('Thom', 'www.google.com')";
// Check for Success
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
}
// Check for Fail
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Now I know I need to somehow pass the vars (text and link) through to the PHP file:
$sql = "INSERT INTO bucketlist (item, link) VALUES ('Thom', 'www.google.com')";
But I have no idea how.
Any tips?
Why do you need JQuery you can pass values using php only
here is a change in your code:-
<form id="form" method="post" action="process.php">
<input id="create-input" name="item" type="text" placeholder="To do">
<input id="create-link" name="link" type="text" placeholder="http://">
<button id="submit" type="button">Add Item</button>
</form>
<ul>
<?php include('conn.php');
$sql = "SELECT * FROM bucketlist";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<li>Item-'. $row["item"].' & Link-'. $row["link"].'</li>';
}
} else {
echo "<li>No List</li>";
}
?>
</ul>
conn.php
<?php
$servername = "localhost";
$database = "bucketlist";
$username = "bucketuser";
$password = "125632";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
process.php
<?php
include('conn.php');
$item = $_POST['item'];
$item = $_POST['link'];
$sql = "INSERT INTO bucketlist (item, link) VALUES ($item,$link)";
// Check for Success
if (mysqli_query($conn, $sql)) {
header('location:yourpage.php');
}
// Check for Fail
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Hope this helps.
Use ajax to post the values of the item and link in your html form to your PHP script.
Something like :
var myItem = $('#create-input').html();
var myLink = $('#create-link').html();
$.ajax({
type: 'POST',
url: 'https://yoururl/api/post.php',
data: {item:myItem,link:myLink},
success: SuccessCall,
error : FailureCall,
cache:false,
async:true,
dataType: 'html'
});
function SuccessCall(data,status){
alert("response from server is "+data);
}
function FailureCall(data,status){
alert("Server connection error");
}
Use the PHP script posted by SYB to retrieve the values of item and link that were sent from your html form.

Fetch data from database and send it to javascript function

I am selecting input values from the database and I want to send it to the javascript function addVal() so that I can retrieve this value. I do not want to use echo. It is not working right now and I don't know how I can make it work.
<h1>trial,</h1>
<div id ="val"> </div>
<?php
$name = $_POST['postname'];
$host = 'localhost';
$user = 'root';
$pass = 'root';
$db_name="big";
$conn = new mysqli($host, $user, $pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "connected";
$sql = "SELECT input FROM trial_db";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while( $row = $result->fetch_assoc()) {
$value = $row['input'];
addVal ($value);
}
}
?>
<script>
function addVal (value){
document.getElementById("val").innerHTML+= value ;
}
</script>
Calling js function from php will not work remove that code from php.
And change in js.
<script>
function addVal (){
var value = "<?php echo $value; ?>";
document.getElementById("val").innerHTML+= value ;
}
</script>
Will only work if js and php codes are in same php file.

Sending Variable from php file to jquery file

I am trying to pass a php variable located in a php file to a separate JavaScript file. I'm trying to pass the variables at the end of the php file in the input functions into the jQuery variables called $message and $username.
Here is where I'm at so far:
chat.php
<?php
//form data
$username = $_POST['username'];
$password = $_POST['password'];
//sql server connection credentials
$servername = "localhost";
$serverusername = "suser11";
$serverpassword = "suser11";
$databasename = "chat_database";
// Create connection
$conn = new mysqli($servername, $serverusername, $serverpassword, $databasename);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br /><br />";
$username = $conn->real_escape_string($username);
$password = $conn->real_escape_string($password);
$sql = "SELECT Salt FROM users WHERE Username='$username'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$salt = $row["Salt"];
}
$sql = "SELECT * FROM users WHERE Username='$username' AND Password=MD5('$password$salt')";
$result = $conn->query($sql);
if($result->num_rows === 0) {
$conn->close(); //close the db connection
header('Location: login.html'); //redirect to login.html
} else {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "UserID: " . $row["user_id"]. " - Name: " . $row["username"]. "<br />";
}
}
// Close the database connection
$conn->close();
?>
<textarea id="myChat" type="text" style="width:500px; height:500px;"></textarea>
<br/>
<br/>
<input id="myText" name="myText"/>
<input type="hidden" value="<?php echo $username; ?>"/>
<button id="add">
<b>Add to chat</b>
</button>
</body>
</html>
Here is my jquery file
$(document).ready(function() { //start 1
//alert("hello world, jQuery is working");
setInterval(function(){$("#myChat").load("chat.txt")},100); //update the textarea with the text file contents every 10th of a second
var $message = '';
var $username = '';
$('#add').click(function(){ // start 2
var $message = $('#myText').val();
var $username = $('$username').val();
//alert("Got the message");
$.ajax({ // start 3
type: "POST",
url:'myprocess.php',
data:{'xml': $xmlString},
dataType:'text/xml',
//success: function(r){ // start 4
//alert('Got it');
//}, // end 4
//error: function (xhr, desc, err) {
//console.log(xhr);
//console.log("Details: " + desc + "\nError: " + err);
//alert ("Error: " + err);
//}
}); // end 3
$('#myText').val(""); //clears value of text box on click of button with id=add
}); // end 2
//forming proper xml
$xmlString ='<?xml version="1.0" encoding="ISO-8859-1"?>';
$xmlString += '<message><user>' + username + '</user><text>' + $message + '</text></message>';
}); // end 1
In php you can pass like:
Just replace your code:
// output data of each row
while($row = $result->fetch_assoc()) {
echo "UserID: " . $row["user_id"]. " - Name: " . $row["username"]. "<br />";
}
with below code:
while($row = $result->fetch_assoc()) {
echo $row["user_id"]."||".$row["username"];
}
and in ajax:
$.ajax({
type: "POST",
url:'myprocess.php',
data:{'xml': $xmlString},
dataType:'text/xml',
success: function(data){
details = data.split("||");
username = details[0];
password = details[1];
}
});

Uncaught ReferenceError: getPrice is not defined

I am trying to run a script. The script needs to show me data from the database. In my script I am using 1 dropdown and 1 textbox. When I change the selected value (product) in my dropdown it needs to show the price of the selected value. The price needs to be shown in the textbox.
The script is not working. I tried to figure out what the problem is. I used developer console tool of my browser. The developer console tool gives me the error:
Uncaught ReferenceError: getPrice is not defined | onchange # (index):1
Can someone help me with this problem?
The pages that I am using for this script are the following pages:
index.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM forms";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control select2' id='product1' name='product1' onChange='getPrice(this.value)' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<body>
<!-- Your text input -->
<input id="product_name" type="text">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('.product1 option:selected').val();
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
</body>
</html>
get.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error)
{
die('Connection failed: ' . $conn->connect_error) ;
}
else
{
$product1 = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT) ;
$query = 'SELECT price FROM forms WHERE id=" . $product1 . " ' ;
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0)
{
$result = mysqli_fetch_assoc($res) ;
echo "<input type='text' value='";
echo json_encode($result['price']);
echo "'>";
}
else
{
echo "<input type='text' value='";
echo json_encode('no results') ;
echo "'>";
}
}
?>
First close <script> tag :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Your scripts tags should be before </html> and inside <body> tag :
<html>
<body>
<!-- Your text input -->
<input id="product_name" type="text">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('.product1 option:selected').val();
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
</body>
</html>
The PHP condition could be simple and you don't need any json encoding, e.g:
if (mysqli_num_rows($res) > 0)
{
$result = mysqli_fetch_assoc($res) ;
echo $result['price'];
}else{
echo 'no results';
}
Hope this helps.

Categories