i need help, i'm new to php and jquery
i created a two tier dependent dropdown list populated from mysql database,which uses two tables products and fieldo with pid as the foreign key.
//code for dropdown.php
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
</head><?php include "connectdb.php"; ?>
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "states.php",
data:'pid='+val,
success: function(data){
$("#state-list").html(data);
}
});
}
function showMsg()
{
$("#msgC").html($("SELECT name, email from fieldo where state = '#state-list option:selected'").text());
return false;
}
</script>
<body >
<form>
<label style="font-size:20px" >Products:</label>
<select name="product" id="product-list" class="demoInputBox" onChange="getState(this.value);">
<option value="">Select Products</option>
<?php
$sql="SELECT * FROM `Products` WHERE TYPE = 'BULK'";
$results=$dbhandle->query($sql);
while($rs=$results->fetch_assoc()) {
?>
<option value="<?php echo $rs["pid"]; ?>"><?php echo $rs["Name"]; ?></option>
<?php
}
?>
</select>
<label style="font-size:20px" >State:</label>
<select id="state-list" name="state" >
<option value="">Select State</option>
</select>
<button value="submit" onclick="return showMsg()">Submit</button>
</form>
Result: <span id="msgC"></span><br>
</body>
</html>
//code for states.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">//alert("sdfsd");</script>
<body>
<?php
require_once("connectdb.php");
//$db_handle = new DBController();
$query ="SELECT oid,state FROM fieldo WHERE pid = '".$_POST["pid"]."'";
$results = $dbhandle->query($query);
?>
<option>Select State</option>
<?php
while($rs=$results->fetch_assoc()) {
?>
<option value="<?php echo $rs["oid"]; ?>"><?php echo $rs["state"]; ?></option>
<?php
}
?>
</body>
</html>
this list is working correctly but i want to display the other columns of stated (email , name and contact) upon selection of the state.
its not working
Have you tried running the while loop without breaking the PHP script? It seems you are almost trying to run a for loop.
<?php
$sql="SELECT * FROM `Products` WHERE TYPE = 'BULK'";
$results=$dbhandle->query($sql);
while($rs=$results->fetch_assoc()) {
echo '<option value="' . $rs["pid"] . '">' . $rs["Name"] . '</option>';
}
?>
UPDATE
Okay, so I heard your comment, and I have used an ajax call to get the full display of the content; I was not really sure as to what you were trying to do with your showMsg() function. I was assuming you were wanting to create a new query request.
So I changed the function to create an Ajax call that would look something along these lines:
<script>
function showMsg()
{
var val;
val = $("#state-list").val();
$.ajax({
type: "POST",
url: "table.php",
data: "state_id="+val,
success: function(data){
$("#msgC").html(data);
}
});
}
</script>
And then table.php would be along these lines...
<?php
// check to see if state_id has been submitted
if(isset($_POST['state_id']))
{
$state_id = $_POST['state_id'];
}
// if it is not set, add something in place.
else
{
$state_id = "1";
}
// query goes here - ask for the ID
$query = "SELECT name, email from fieldo where state = " . $state_id;
$results = $dbhandle->query($query);
while($rs=$results->fetch_assoc()) {
//... create table with all content;
}
?>
PHP cannot react to what is happening in the browser. Once PHP has processed the page and the web server has sent it to the browser, JavaScript takes over.
This means that if a customer selects a new state, it will not automatically get PHP to populate the rest of the page with the matching email, name and contact. You need to change your approach a bit.
One approach is to use Ajax. It would work like so:
In jQuery, register an onChange event handler for the states dropdown.
When customer selects a new state, the event handler will be triggered. Within the handler, make an Ajax request that sends the PHP the selected state.
the PHP document that receives the request would query for the matching email, name and contact from the DB and send the results, perhaps as a JSON
Back in the jQuery handler, when data comes back from the PHP server (in the response callback), use that data to populate the page with the right email, name and contact.
An alternative, even simpler approach (if you don't have a lot of data) is to have PHP send all data at once in a multi-dimensional array when the page loads. This time when the user selects a new state, the jQuery event handler will look up the data under that state within the big array, and fill the form with the data.
Related
I am currently trying to display data returned from my database onto my php display page. I have been following along this tutorial:
https://www.phpzag.com/ajax-drop-down-selection-data-load-with-php-mysql/
At first I tried it to test against my data. But I found it to be working incorrectly. So I then decided to use the sample data provided in the tutorial on my system to see where things are going wrong. Thus my pages are as follows:
populatePage.php <---This acts as my "index.php" from tutorial
<?php
require_once('../../config/sessionHandler.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="src/populatePage.js"></script>
<title>Populate Page</title>
</head>
<body >
<div class="page-header">
<h3>
<select id="employee">
<option value="" selected="selected">Select Employee Name</option>
<?php
$sql = "SELECT id, employee_name, employee_salary, employee_age FROM employee LIMIT 10";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
while( $rows = mysqli_fetch_assoc($resultset) ) {
?>
<option value="<?php echo $rows["id"]; ?>"><?php echo $rows["employee_name"]; ?></option>
<?php } ?>
</select>
</h3>
</div>
<div id="display">
<div id="heading" class="row">
<h3>
</h3>
</div>
<div id="records" class="row">
<h3>
</h3>
</div>
</div>
</body>
</html>
populatePage.js <---My renamed version of getData.js from tutorial
$(document).ready(function(){
// code to get all records from table via select box
$("#employee").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'empid='+ id;
$.ajax({
url: 'popJax.php',
dataType: "json",
data: dataString,
cache: false,
success: function(employeeData) {
if(employeeData) {
$("#heading").show();
$("#no_records").hide();
$("#emp_name").text(employeeData.employee_name);
$("#emp_age").text(employeeData.employee_age);
$("#emp_salary").text(employeeData.employee_salary);
$("#records").show();
} else {
$("#heading").hide();
$("#records").hide();
$("#no_records").show();
}
}
});
})
});
popJax.php <--- This is my getEmployee.php from the tutorial
<?php
require_once('../../config/sessionHandler.php');
$_SESSION['PopulateWorking'] = true;
if($_REQUEST['empid'])
{
$sql = "SELECT id, employee_name, employee_salary, employee_age FROM employee WHERE id='".$_REQUEST['empid']."'";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$data = array();
while( $rows = mysqli_fetch_assoc($resultset) )
{
$data = $rows;
}
echo json_encode($data);
}
else
{
echo 0;
$_SESSION['Fail'] = true;
}
?>>
My sessionHandler is used to achieve the database connection and session verification.
I followed along with the tutorial. And thus far my system will:
-Retrieve the users from the table.
-Populate the drop down with them.
-Allow me to select a user.
-Display $_SESSION['PopulateWorking'] as 'true'
AND
-Properly read through employee data while I watch it in JS debugger.
But somewhere along these lines I am missing something. I have worked with AJAX, PHP, and SQL pretty frequently. But am by no means an expert. I am looking for where I am missing an integral step? I just want to try and display the data like he does in the tutorial. Because then I can fine tune and change everything around to make it work how I would like. But right now when I click a user nothing populates on the page like it does in his tutorial. Mine works right up until the actual important part. Displaying the selected data.
When compared next to his mine also does not display : "Please select employee name to view details", anywhere on the page? So I am thinking I am missing an entire DIV somewhere? Or not generating it? Or the script is not calling it properly?
I just can't seem to figure out where I am incorrectly utilizing the JSON data?
TL;DR: Why will my page not display the result data on my page like it does in this tutorial?
Im sorry for the waste of time. I did not have any of the div's that i was trying to reference in popJax.php
I needed to add
The user goes change the nm_peca, will select tipo_preco and then find the price in MySQL database to complete the textbox vlr_peca.
What do I need to do to get the value of products?
<?php>
$query = mysql_query("SELECT id, nm_peca, vlr_original,
vlr_paralelo, fabricante
FROM peca
ORDER BY nm_peca");
<select id="nm_peca" name="nm_peca"
title="Selecione um status."
class="form-control" size="1">
<option value="">Status</option>
<option value="N/A">N/A</option>
<option value="S">S - Substituir</option>
</select>
</div>
</div>
<select id="tipo_preco" name="tipo_preco"
class="form-control" size="1">
<option value="">Tipo</option>
<option value="Peça Original">Original</option>
<option value="Peça Paralela">Paralela</option>
</select>
</div>
</div>
<div class="col-md-1">
<div class="input-group btn-group">
<input type="text" value="????????" name="vlr_peca"
class="form-control" readonly>
</div>
</div>
Well your code is a little confusing because what you really want is not clear to me, maybe it doesn't help that it's in a different language. What is the $query for? You are not using this in the code, so you'll need to do this to access it:
$rows = array();
while ($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
print '<pre>'. print_r($rows, true) . '</pre>';
Then you'll need to use an ajax request OR setup javascript vars on the front end to make changes. I'm just going to go ahead and use the latter since it's more illustrative.
So I would add the cdn of jQuery which is https://code.jquery.com/jquery-2.1.4.min.js to the top of your file in a tag like:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
Then you'll need to add an input id to that input tag like <input id="dynamic-variable" type="text" value="????????" name="vlr_peca"> and then use something like:
<script type="text/javascript">
$(document).ready(function() {
$('#tipo_preco').change(function() {
if ($(this).val() == 'Peça Original') {
$('#dynamic-variable').val('$5,000,000,000.00');
} else if ($(this).val() == 'Peça Paralela') {
$('#dynamic-variable').val('$300 billion trillion dollars');
} else {
$('#dynamic-variable').val('Bro. Choose one.');
}
});
});
</script>
I'm not going to program this whole thing for you since I don't know what kind of data you are getting from your DB, but this should be good enough to get you started. You need to be able to access the data in the mysql query, and you may just want to use the <?= $db_variable ?> or <?php echo $db_variable?> in your javascript where I have the amount variables. This should be good enough to get you started. Read up on php mysql_query and jQuery
AJAX
If you were to do this via AJAX, you would need a second page that accesses the database, you'd have to $_GET or $_POST variables and then print back the amount.
So your JavaScript would be something like this:
$.get('/the/page.php?tipo_preco=' + $('#tipo_preco').val(), function(response) {
if (response != '') {
$('#dynamic-variable').val(response);
}
});
And your second page would be something like this:
<?php
// code that sets up the database
// .... //
// now your code
$selected_value = $_GET['tipo_preco'];
$result = mysql_query("SELECT price FROM table WHERE column_val = '" . mysql_real_escape_string($selected_value) . "'");
$row = mysql_fetch_assoc($result); // assuming you're only fetching one row
print $row['price'];
?>
I would suggest you just go with the first suggestion, it's faster, less moving parts.
I am having a bit of trouble figuring out how exactly to make a certain connection. It's a project I thought might be simple enough for me to do on my own without help, but I've hit a wall unfortunately. It's an 'exercise generator' that basically asks a few basic questions, and based on your answers, it outputs a recommended workout routine. I've constructed the MySQL database with plenty of exercises, have successfully connected the database, and have made the form.
What I am having trouble though, however, is storing those form results into variables, and based on those variables (if workout days is 3, for example, there would only be 3 groups of workouts printed instead of 5) output a routine into the same div as the form, effectively replacing it with the answer instead of placing it underneath the submitted form.
Index.php
<!DOCTYPE html>
<html>
<?php $page_title = "Workout Generator"; ?>
<link rel="stylesheet" type="text/css" href="style.css">
<head>
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" ></script>
</head>
<body>
<?php include("header.php"); ?>
<?php include("connect.php"); ?>
<div id="appWindow">
<h3>Please answer the following questions and click 'Submit' to generate your workout routine.</h3>
<form id="homeForm" method="post" >
<label for="name">Name: </label>
<input type="text" name="name"><br>
<label for="age">Age: </label>
<input type="number" name="age"><br>
<label for="workoutdays">How many days a week can you workout?</label>
<select name="workoutdays">>
<option value="1">3</option>
<option value="2">5</option>
</select><br>
<label for="workoutstyle">Do you prefer a gym, or bodyweight exercises?</label>
<select name="workoutstyle">>
<option value="1">Gym</option>
<option value="2">Bodyweight</option>
</select><br>
<button type="submit" name="submit">Submit</button>
<button type="reset" name="reset">Reset</button>
<div class="form_result"></div>
</form>
<?php
$age = $_POST['age'];
$workoutdays = $_POST['workoutdays'];
$workoutstyle = $_POST['workoutstyle'];
?>
</div>
<br><br><br>
<?php include("footer.php"); ?>
</body>
</html>
I don't necessarily want an answer giving me the exact code to enter, but would appreciate being pointed in the right direction to get that form pulling data from MySQL, and using AJAX to print in the same window without refreshing.
THANK YOU
First of all, you need to post your request. With $.ajax this
//Do this thing on page load
$(function() {
//handle submit
$("#homeForm").submit(function(e) {
//customize your submit
e.preventDefault();
$.ajax({
type: "POST",
url: youURL, //maybe an url pointing to index.php
data: yourData, //attach everything you want to pass
success: function(response) {
$("#appWindow").html(response);
}
});
});
});
code should help. You need to make sure you pass the necessary elements and you provide the correct url. On server side, generate the desired html and send back as response.
In the script file
$(document).ready(function(){
$(document).on('click','#submit_btn',function(){
var url = '/xyz.php'; //full path of the function where you have written the db queries.
var data = '';//any data that you would like to send to the function.
$.post(url,{data: data}, function(result){
var arr = JSON.parse(result);
});
});
});
in your php file once your database query has been executed and you get the result. for example
$result = //result of your mysql query.
echo json_encode($result);
exit;
OK, let me start off by saying im an amateur, so all your help is really appreciated.
OK, I have a form, called 'skills.php' and on this form, you enter the following fields 'Skills_ID, Employee_ID, First_name, Last_name and Skill'. I have used java so when you select employee_ID, the name fields change to what employee that is (linked to employee table).
HOWEVER, since i have added this function, i can not save my form data into my database. Maby i accidently deleted a line of code when implementing the java function. Can someone help me figure it out? below is my form 'Skill.php':
<html>
<?php
// Connecting to database
$pdo = new PDO("mysql:host=localhost;dbname=hrmwaitrose;charset=utf8", "root", "");
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="style.css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <!-- Online Jquery -->
<title>Skill</title>
</head>
<body>
<div id="content">
<h1 align="center">Add Employee Skill</h1>
<form action="insertskill.php" method="post">
<div>
<p>
Skill ID:
<input type="text" name="Training_ID">
</p>
<p>
Employee ID:
<select id="Employee_ID">
<option value="">Select one</option>
<?php
$st = $pdo->prepare("SELECT Employee_ID FROM Employee");
$st->execute();
$rows = $st->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
?><option value="<?php echo $row ['Employee_ID']; ?>"><?php echo $row ['Employee_ID']; ?></option><?php
}
?>
</select>
<p>
First name:
<input type="text" name="First_name" id="First_name">
</p>
<p>
Last name:
<input type="text" name="Last_name" id="Last_name">
</p>
<p>
<p>Skill: <select name="Skill">
<option value="">Select...</option>
<option value="Checkouts">Checkouts</option>
<option value="Fresh goods">Fresh goods</option>
<option value="Dry goods">Dry goods</option>
<option value="Fruit & Veg">Fruit & Veg</option>
<option value="Operations">Operations</option>
</select>
</p>
<input type="submit">
<INPUT Type="BUTTON" VALUE="Back" ONCLICK="window.location.href='index.html'">
</form>
</div>
<script type="text/javascript">
$(function() { // This code will be executed when DOM is ready
$('#Employee_ID').change(function() {
var $self = $(this); // jQuery object with the select inside
$.post("insertskill.php", { Employee_ID : $self.val()}, function(json) {
if (json && json.status) {
$('#First_name').val(json.name);
$('#Last_name').val(json.lastname);
}
})
});
})
</script>
</body>
</html>
And here is the code used when the submit button is pressed 'insertskill.php':
<?php
$pdo = new PDO("mysql:host=localhost;dbname=hrmwaitrose;charset=utf8", "root", "");
header("Content-Type:application/json; Charset=utf-8");
$st = $pdo->prepare("SELECT First_name, Last_name FROM Employee WHERE Employee_ID = :employee_id");
$st->execute(array ('employee_id' => $_POST['Employee_ID']));
$data = $st->fetch(PDO::FETCH_ASSOC);
echo json_encode(array ('status' => true, 'name' => $data ['First_name'], 'lastname' => $data ['Last_name']));
?>
Just by looking at this code imn pretty sure i might of accidently deleted the coding to insert it into database, HOWEVER i dont know how to fix it :( can someone help? much appreciated! Thanks in advance
in "insertskill.php" line 6:
$st = $pdo->prepare("SELECT First_name, Last_name FROM Employee WHERE Employee_ID = :employee_id");
You're performing a SELECT query (read), sounds to me more like you wanted an INSERT query (write).
An INSERT statement in your case would be something similar to:
$st = $pdo->prepare("INSERT INTO Employee (Training_Id,Employee_Id,First_Name,Last_Name,Skill) VALUES (:training_id,:employee_id,:first_name,:last_name,:skill)")
$st->execute(array(':training_id' => $training_id, ':employee_id' => ...));
First, watch out. Java is not JavaScript!
And you're right, you removed the INSERT lines. There are several articles on the web about how to do that. Here is one. Just google PDO Insert for more results.
You should put these INSERT commands in your insertskill.php file and create another one, maybe fetchName.php or something like that, with the code that you presented to return first and last name for an employee based on its id, and use that in your JavaScript $.change() function. It doesn't make sense for a file called insertskill.php to fetch data.
And your forgot to specify that you're expecting a JSON in your $.post() command. Do that instead:
$.post("insertskill.php", { Employee_ID : $self.val()}, function(json) {
if (json && json.status) {
$('#First_name').val(json.name);
$('#Last_name').val(json.lastname);
}
}, 'json'); // Here!
First thing to say is that you are NOT using Java. You are using JavaScript (actually ECMAScript which is VERY VERY different from Java.
Next, you are correct, that there is now no INSERT statement there at all, you will need to write one to insert whatever data you want to insert.
HOWEVER, you also need to somehow tell the difference between when insertskill.php is called for an Ajax request (to get the names for the form) and when it is called to insert the data. So on your Javascript (jQuery I guess) request, you could change the url to:
$.post("insertskill.php?ajax"
and then in insertskill.php do:
if(isset($_GET['ajax'])) {
header("Content-Type:application/json; Charset=utf-8");
$st = $pdo->prepare("SELECT First_name, Last_name FROM Employee WHERE Employee_ID = :employee_id");
$st->execute(array ('employee_id' => $_POST['Employee_ID']));
$data = $st->fetch(PDO::FETCH_ASSOC);
echo json_encode(array ('status' => true, 'name' => $data ['First_name'], 'lastname' => $data ['Last_name']));
}
else {
// Do the insert statement stuff...
}
I am a newbie as far as JQuery, AJAX & PHP are concerned and I am trying to build a form with chained selects that will provide initial data for a new mysql record.
I have downloaded the JQuery chained select remote plugin and for the life of me I cannot figure out how to get the data returned for the second select dropdown. The first dropdown is populated using another function and when the user selects a value from this dropdown, I want that value to be used as the search string for the second dropdown.
The code snippet for the main form is:
<?php
<head>
<script type="text/javascript" src="../js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="../js/jquery.chained.remote.js" charset="utf-8"></script>
</script>
<script type="text/javascript">
$('#series').remoteChained("#series", "../models/json.php");
</script>
</head>
<body>
<form action="" method="post">
<table border="1">
<tr>
<th>Season:</th>
<td><select name="season" id="mark">
<option value="">Select Season...</option>
<?php
$i = 0;
while ($i < count($showseason)){ // obtain seasons from getseason() function
?>
<option value="<?php echo $showseason[$i]; ?>">
<?php echo $showseason[$i]; ?> </option>
<?php
$i++;
} ?>
</select></td>
<th>Competition:</th><td><select name="competition" id="series">
<option value="">Competition type...</option>
</select></td>
The following is the code for the Mysql select (json.php)
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/helpers.inc.php';
include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/db_connect.php';
try
{
$result = $pdo->prepare("SELECT sideid, competition FROM pennantsides");
$result->execute();
echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
}
catch (PDOException $e)
{
$output = 'Error selecting records - Please contact your Site Administrator';
include $_SERVER['DOCUMENT_ROOT'] . '/views/output.html.php';
exit();
}
Isn't it $('#mark').remoteChained("#series", "../models/json.php"); you're trying to do ?
Also, what's the content of the json file when you launch it on your browser (or via whatever GET method you use) ?