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.
Related
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.
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
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];
}
});
I am new with ajax somebody help me I want to create a form that include input field.
Whenever I click the button I will get the value of input field and it declared it as data in AJAX and the value from ajax it pass to PHP script. It will display a table.
My question is how to get the value of input field and declared it as data in AJAX. After click the table will declared in success in AJAX Script that will show a table.
Thank you in advance
UPDATE:
#J_D, Here's my html code for my form:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<table cellpadding="15px">
<tr>
<td>Transmittal #</td>
<td><input type="text" class="form-control" style="padding-left:5px;" name="transmittal_number_inquiry" id="transmittal_number_inquiry" class="transmittal_number_inquiry" onKeyPress="return isNumberKey(event)" required></td>
</tr>
</table>
<div style="float:right; padding-right:110px; padding-top:10px;">
Inquire
<?php /*?><input type="submit" class="btn btn-info" data-toggle="modal" id="btn-inquire-transmittal-number" name="btn-inquire-transmittal-number" data-backdrop="false" value="Inquire"><?php */?>
<?php /*?><button type="submit" class="btn btn-info" data-toggle="modal" id="btn-inquire-transmittal-number" name="btn-inquire-transmittal-number" data-backdrop="false">Inquire</button><?php */?>
</div>
</form>
Here's my AJAX Code:
$(document).ready(function(){
$('.btn-inquire-traensmittal-number').click(function(){
$inputtextval = $('#transmittal_number_inquiry').val();
$.ajax({
type: 'POST',
url: getTransmittalNum.php,
data: {'transmittal_number_inquiry' : $inputtextval},
success: function(res){
}
});
});
});
Here's the getTransmittalNum.php code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "etransmittal";
$selectedTransmittal = $_GET['q'];
$con = mysqli_connect($servername,$username,$password,$dbname);
if(!$con){
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['inquire-transmittal-number'])){
$query = "SELECT en.transid, en.transdate, CONCAT(userlist.lname, ', ', userlist.fname, ' ', userlist.mname) AS sender_name,
userlist.`department`, en.document_number, doctype.document_type, doctype.document_description, vendor.`vendor_name`, en.`remarks`,
en.status_id, stat.status_name, en.total_amount
FROM tbl_encode_transmittal en
LEFT JOIN tbl_vendor vendor ON vendor.`vendor_id` = en.vendor_id
LEFT JOIN tbl_doctype doctype ON doctype.`doc_id` = en.doctype_id
LEFT JOIN tbl_userlist userlist ON userlist.userid = en.sender_id
LEFT JOIN tbl_userlist userlist1 ON userlist1.userid = en.`receiver_id`
LEFT JOIN tbl_status stat ON stat.status_id = en.status_id
WHERE en.`transid` = '{$_POST['transmittal_number_inquiry']}'";
$result = mysqli_query($con, $query);
$rows = array();
if($result){
while($row = mysqli_fetch_assoc($result)){
$rows[] = $row;
}
}
else{
echo 'MYSQL Error: ' . mysqli_error();
}
$json = json_encode($rows);
echo $json;
mysqli_close($con);
}
?>
Try following code :
$(document).ready(function(){
$('#btn-inquire-transmittal-number').click(function(){
$inputtextval = $('#transmittal_number_inquiry').val();
$.ajax({
type: 'POST',
url: 'getTransmittalNum.php', // wrap code with quote
data: {'transmittal_number_inquiry' : $inputtextval},
dataType : 'json', // expecting result type json
success: function(res){
// once you got result,
// populate table here
}
});
});
});
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "etransmittal";
//$selectedTransmittal = $_GET['q']; //<---- u need this?????
$con = mysqli_connect($servername,$username,$password,$dbname);
if(!$con){
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['transmittal_number_inquiry'])){ // <-- check for existence
$query = "SELECT en.transid, en.transdate, CONCAT(userlist.lname, ', ', userlist.fname, ' ', userlist.mname) AS sender_name,
userlist.`department`, en.document_number, doctype.document_type, doctype.document_description, vendor.`vendor_name`, en.`remarks`,
en.status_id, stat.status_name, en.total_amount
FROM tbl_encode_transmittal en
LEFT JOIN tbl_vendor vendor ON vendor.`vendor_id` = en.vendor_id
LEFT JOIN tbl_doctype doctype ON doctype.`doc_id` = en.doctype_id
LEFT JOIN tbl_userlist userlist ON userlist.userid = en.sender_id
LEFT JOIN tbl_userlist userlist1 ON userlist1.userid = en.`receiver_id`
LEFT JOIN tbl_status stat ON stat.status_id = en.status_id
WHERE en.`transid` = '{$_POST['transmittal_number_inquiry']}'";
$result = mysqli_query($con, $query);
$rows = array();
if($result){
while($row = mysqli_fetch_assoc($result)){
$rows[] = $row;
}
}
else{
echo 'MYSQL Error: ' . mysqli_error();
}
$json = json_encode($rows);
echo $json;
mysqli_close($con);
}
?>
Basically, I want to retrieve a certain product after clicking on an element. I'm using AJAX to pass the variable, and PHP to display the SQL query. I will use the product id on a WHERE statement, to retrieve and display the correct product.
Here is part of my code so far:
<html>
<head>
<title>Left Frame</title>
<link href='http://fonts.googleapis.com/css?family=Indie+Flower' rel='stylesheet' type='text/css'>
<link href="stylesheets/main.css" rel="stylesheet" type="text/css">
<script src="javascripts/jquery-1.11.2.js">
</script>
</head>
<body>
<div class="container">
<div id="bottomHalf">
<img id="blank" src="assets/bottom_half.png" style= "z-index: 5" >
<img src="assets/frosen_food.png"
usemap="#Map2"
border="0"
id="frozen"
style="z-index: 0;
visibility:hidden;" >
<map name="Map2">
<area shape="rect" coords="7,95,126,146" alt="Hamburger Patties" href="#" id="hamburgerPatties">
</div>
</div>
<script language="javascript">
$("#hamburgerPatties").click(function(){
var hamburgerPatties = "1002";
$.ajax({
type:"GET",
url: "topRightFrame.php",
data: "variable1=" + encodeURIComponent(hamburgerPatties),
success: function(){
//display something if it succeeds
alert( hamburgerPatties );
}
});
});
</script>
</body>
</html>
Part of my PHP code:
<?php
$product_id =(int)$_GET['variable1'];
$servername = "************";
$username = "************";
$password = "*************";
$dbname = "poti";
$tableName = "products";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM $tableName ";
$result = $conn->query($sql);
// Display all products on the database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Product ID: " . $row["product_id"]. " - Product Name: " . $row["product_name"]. " Unit Price:" . $row["unit_price"]. "<br>";
}
} else {
echo "0 results";
}
// Display product I clicked on the other frame
if (isset($GET['variable1'])) {
$sql = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = $conn->query($sql);
if ($result) {
echo '<table>';
while ($row = $result->fetch_assoc())
{
echo '<tr>';
echo '<td>', "Product ID: " . $row["product_id"]. " - Product Name: " . $row["product_name"]. " Unit Price:" . $row["unit_price"]. "<br>";
echo '</tr>';
}
echo '</table>';
}
}
$conn->close();
?>
I'm able to display all the products. But starting from the ifsset statement, the code no long works. I get no error message or anything. How can I solve this? I'm pretty new to PHP.
EDIT: Ok, I managed to get the product I want when I hard code the product id. Now I need to get this variable using javascript.
You have syntax errors in your if statements.
When you're setting if, you should enclose the statement in braces:
instead of if something : do if(something): and then end it with endif; (when using colons :)
// Display product I clicked on the other frame
if (isset($GET['variable1'])):
$query = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = mysqli_query($conn, $query);
if ($result):
echo '<table>';
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>', $row['product_id'], '</td>'; // and others
echo '</tr>';
}
echo '</table>';
endif;
endif;
Or, use {} braces instead of colons :
// Display product I clicked on the other frame
if (isset($GET['variable1'])){
$query = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = mysqli_query($conn, $query);
if ($result){
echo '<table>';
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>', $row['product_id'], '</td>'; // and others
echo '</tr>';
}
echo '</table>';
}
}
You have syntax error in if block. use {} for if block also use echo instead of pure html tag(table). This error prevents successful state of ajax request. also don't forget to close table.
if ($result)
{
echo '<table>';
while ($row = $result->fetch_assoc())
{
echo '<tr>';
echo '<td>', $row['product_id'], '</td><td>'; // and others
echo '</tr>';
}
echo '</table>';
}
and the ajax code to display php result instead of test alert would be this:
<script language="javascript">
$("#hamburgerPatties").click(function(){
var hamburgerPatties = "1002";
$.ajax({
type:"GET",
url: "topRightFrame.php",
data: "variable1=" + encodeURIComponent(hamburgerPatties),
success: function(data){
alert(data);
}
});
});
</script>