Ajax script breaking at callback - javascript

I have this script which works once but I can't seem to replicate it inside the same document.
The JQuery:
$("document").ready(function() {
//This first instance works
if($("#add-menu").length) {
$("#add-menu").change(function() {
var datum = 'shortname=' + $(this).val() + '&table=projects';
$.post('proj_query.php', datum, response);
function response(data) {
var jSON = $.parseJSON(data);
$("label:contains('Title:') + input:first").val(jSON.title);
$("label:contains('Medium:') + input:first").val(jSON.medium);
$("label:contains('Dimmensions:') + input:first").val(jSON.description);
$("label:contains('Work Blurb:') + textarea:first").val(jSON.blurb);
}
});
}
//This one doesn't work
if($("#id-blurb").length) {
$("#id-blurb a").click(function() {
if($("#edit-menu").val().length) {
var datum = 'shortname=' + $("#edit-menu").val() + '&table=projects';
$.post('proj_query.php', datum, responseB);
function responseB(data) {
var jSON = $.parseJSON(data);
$("#id-blurb textarea").val(jSON.blurb);
}
}
});
}
});
When I test by running alerts, I get alerts right up until I add the callback function (the one called 'responseB'). Then it stops generating them. So it seems it's finding the document, and it seems to be accepting the data, but that's about it. After that nothing happens.
proj_query.php looks like this:
<?php
require_once ('../functions/functions.php');
connectDB('../functions/login.php');
require_once("session.php");
if(isset($_POST['shortname'])) {
$shortname = $_POST['shortname'];
$table = $_POST['table'];
$query = "SELECT title, medium, description, blurb FROM $table WHERE shortname='$shortname'";
$result = mysql_query($query);
$results = mysql_fetch_array($result, MYSQL_ASSOC);
print_r(json_encode($results));
}
?>
The HTML is this (but you may not need that):
<div id="change" class="grid_4">
<h3>Edit a Project</h3>
<form method="post" action="index.php" name="editform" onsubmit="return validateEdit(this);">
<input type="hidden" name="edit" value="yes" />
<div class="field_container"><label>Project Name:</label>
<select id="edit-menu" name="shortname">
<option value="">Select a Project...</option>
<?php //For creating the dropdown menu
$query = "SELECT * FROM projects ORDER BY title ASC";
$result = mysql_query($query);
if (!$result) die ("Server says: <br/>Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for($i=0; $i<$rows; $i++) {
$results[] = mysql_fetch_array($result, MYSQL_ASSOC);
$option = $results[$i]['title'];
$value = $results[$i]['shortname'];
echo "<option value=\"$value\">" . $option . "</option>\n";
}
?>
</select>
</div>
<div class="field_container"><label>Title:</label><input type="text" name="title" maxlength="128"/></div>
<div class="field_container"><label>Date:</label><input type="date" name="date" /></div>
<div class="field_container"><label>Medium:</label><input type="text" name="medium" maxlength="256"/></div>
<div class="field_container"><label>Dimmensions:</label><input type="text" name="description" maxlength="64"/></div>
<div class="field_container"><label>Area:</label><input type="text" name="area" maxlength="16"/></div>
<div class="field_container"><label>Video Number:</label><input type="text" name="video" maxlength="64"/></div>
<div class="field_container"><label>New Shortname:</label><input type="text" name="new_shortname" maxlength="16"/></div>
<div class="field_container" id="id-blurb"><label><a title="Click for old content">Work Blurb:</a></label><textarea class="blurb" name="blurb" rows="5" ></textarea></div>
<input class="submit" type="submit" value="Edit Project" />
</form>
</div>
Banging my head on this one...

Related

adding multiple inputfield using javascript in php not working

i have a form in php in which i am trying to add multiple fields on button click, i did the following code:
function add_fields() {
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.innerHTML = '
<div class="form-group col-md-6">
<label for="inputPassword4">Item</label>
<?php
$sqlcodes = "SELECT * FROM inventory ORDER BY categoryname ASC";
$resultcodes = mysqli_query($con, $sqlcodes);
echo "<td><select class='form-control' name='item'>";
echo "<option>Select Item</option>";
if ($resultcodes->num_rows > 0) {
while($row = $resultcodes->fetch_assoc()) {
$group[$row['categoryname']][] = $row;
}
foreach ($group as $key => $values){
echo '<optgroup label="'.$key.'">';
foreach ($values as $value)
{
echo '<option value="'.$value['name'].'">'.$value['name'].'</option>';
}
echo '</optgroup>';
}
} else {}
echo "</select></td>";
?>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Weight</label>
<input name="weight" type="text" class="form-control" id="inputEmail4" placeholder="Weight">
</div>
';
objTo.appendChild(divtest)
}
<div id="room_fileds">
<div class="form-group col-md-6">
<label for="inputPassword4">Item</label>
<?php
$sqlcodes = "SELECT * FROM inventory ORDER BY categoryname ASC";
$resultcodes = mysqli_query($con, $sqlcodes);
echo "<td><select class='form-control' name='item'>";
echo "<option>Select Item</option>";
if ($resultcodes->num_rows > 0) {
while($row = $resultcodes->fetch_assoc()) {
$group[$row['categoryname']][] = $row;
}
foreach ($group as $key => $values){
echo '<optgroup label="'.$key.'">';
foreach ($values as $value)
{
echo '<option value="'.$value['name'].'">'.$value['name'].'</option>';
}
echo '</optgroup>';
}
} else {}
echo "</select></td>";
?>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Weight</label>
<input name="weight" type="text" class="form-control" id="inputEmail4" placeholder="Weight">
</div>
</div>
<input type="button" id="more_fields" onclick="add_fields()" value="Add More" />
however this is not working, i am getting the following error:
** Uncaught ReferenceError: add_fields is not defined
at HTMLInputElement.onclick **
can anyone please tell me what is wrong in here, thanks in advance
As per the comment previously about cloning content and appending that the following goes a step further and uses a content Template to store the content that you wish to add with each button click. This template could hold the generated select menu and would be invisible until added to the DOM. This means you do not have a huge, bloated function that gets called - only some quite simple code to find the template, create a clone and append to the designated parent node.
The below example has the PHP commented out so that the display here looks OK but would need the PHP code re-enabled to produce the actual results you need. None of the code within the template has an ID attribute so there is no need to worry about duplicating IDs.
const clonetemplate=(e)=>{
let parent=document.getElementById('room_fields');
let tmpl=document.querySelector('template#rfc').content.cloneNode( true );
parent.append( tmpl )
}
// Button click handler
document.querySelector('input#add').addEventListener('click',clonetemplate );
// pageload... display initial menu
clonetemplate();
#room_fields > div{margin:1rem;padding:1rem;border:1px solid grey;font-family:monospace;}
#room_fields > div label{display:block;width:80%;padding:0.25rem;margin:0.1rem auto;float:none;}
#room_fields > div select,
#room_fields > div input{float:right}
<div id="room_fields">
<!-- add content here -->
</div>
<input type="button" id='add' value="Add More" />
<!--
Generate the content once that will be repeated
and keep it within a content template until
needed.
-->
<template id='rfc'>
<div>
<div class='form-group col-md-6'>
<label>Item
<select class='form-control' name='item'>
<option>Select Item
<!-- Uncomment this PHP for live version
<?php
$sql = 'select * from `inventory` order by `categoryname` asc';
$res = $con->query( $sql );
$group=array();
while( $rs=$res->fetch_object() ){
$group[ $rs->categoryname ]=$rs;
}
foreach( $group as $key => $values ){
printf('<optgroup label="%s">',$key);
foreach( $values as $obj )printf( '<option>%s',$obj->name );
print('</optgroup>');
}
?>
-->
<option>Hello
<option>World
<option>No IDs
<option>Simples...
</select>
</label>
</div>
<div class='form-group col-md-6'>
<label>Weight
<input name='weight' type='text' class='form-control' placeholder='Weight' />
</label>
</div>
</div>
</template>
In the string that you define in the function add_fields and assign to divtest.innerHTML you have line breaks. You probably also get an error when loading the script saying that you have a syntax error. You should try to avoid line breaks in strings. An alternative solution could be to use backticks for your string. YOu can read about it here: Template literals (Template strings).
Here are two examples. The first fails with both syntax and reference error, the next works fine (but does not do anything).
function add_fields(){
var divtest = document.createElement("div");
divtest.innerHTML = '
test
';
}
<input type="button" id="more_fields1" onclick="add_fields()" value="Add More" />
function add_fields(){
var divtest = document.createElement("div");
divtest.innerHTML = `
test
`;
}
<input type="button" id="more_fields1" onclick="add_fields()" value="Add More" />

Genereting 'n' html inputs based on database variable

My intention is to create a form in HTML where the user could register some quality features of a product. The number of features to be registered varies according to the model, this info is registered on a table in SQL.
So far I manage to generate the inputs, but it is very fast, the user cannot fill all the inputs.
## query to get the product information from database ##
$query_list = "SELECT * FROM data_products";
$result_list = mysqli_query($conn, $query_list);
## get the number of rows
$query_data_rows = mysqli_query($conn, $query_list);
$data_rows = mysqli_fetch_array($query_data_rows);
?>
## here is the first form, where the user selects the product model,
## therefore it should query the number of raws (n) registered on the table
<div class="container">
<form action="" method="post" onsubmit="getdata()">
<select name="select1">
<option value=" "> </option>
<?php
while ($row = mysqli_fetch_array($result_list)) {
echo "<option value='" . $row['customer_Id'] . "'>" . $row['customer_Id'] . "</option>";
}
?>
</select>
<input type="submit" name="submit" value="Go"/>
</form>
</div>
## here my intention is to return the (n) number of input fields
## it correctly displays the number of input fields, but it is very fast
## I am missing something here
<?php
if(isset($_POST['select1'])){ ?>
<form id="form" action="" method="post">
<input type="submit">
</form>
<?php
}
?>
## I am almost zero skilled on Javascript,
## but browsing on the world web wide and reading the documentation of the language
## I got the code below.
<script>
function getdata() {
var no = <?php echo $data_rows['number'] ;?>;
for(var i=0;i<no;i++) {
var textfield = document.createElement("input");
textfield.type = "text";
textfield.value = "";
textfield.name = i+1 + "a"
textfield.placeholder = i+1
document.getElementById('form').appendChild(textfield);
}
}
</script> ```
Here what actually happening is that when you are submitting the form getdata() function is called till the it get submitted, after submission is done the content called by function disappears, in order to avoid this use return false statement at the end of the function.
<div class="container">
<form action="" id="form_id" method="post" onsubmit="return getdata()">
<select name="select1">
<option value=" "> </option>
<?php
//accesing the database table
$query_list = "SELECT * FROM `data_products`";
$result = mysqli_query($conn, $query_list);
//to get rows
$data_rows = mysqli_num_rows($result);
echo $data_rows;
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['srno'] . "'>" . $row['srno'] . "</option>";
}
?>
</select>
<input type="submit" name="submit" value="go"/>
</form></div>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST' ){
echo '<form id="form" action="" method="post">
<input type="submit">
</form>';
}
?>
<script>
function getdata() {
var no = <?php echo $data_rows;?>;
for(var i=0;i<no;i++) {
var btn = document.createElement("INPUT");
btn.type = "text";
btn.value = "";
btn.name = i+1 + "a"
btn.placeholder = i+1
document.getElementById('form').appendChild(btn);
}
return false;
}
</script>
This is working. Here I have made some changes in your code like replacing 'textfield' with 'btn', 'customerid' with 'srno' (for easy understanding) and avoid using php again and again.

Getting Ajax error 500 when trying to post items from Database

What I am trying to do is modify some attributes in my database. The way I want to do it, is to have a dropdown menu that is populated with options (in this case, student names) from the table I am calling, and then populating text fields with the information that pertains to that specific student, that can then be edited and then submitted to the database. So far, my drop down menu works. It fills itself with the appropriate attributes. My problem comes when I'm trying to populate the text fields with the other attributes. I opened up the console to see if I was getting any errors (because nothing was happening after I selected a student) and it said there was an error 500 with my POST.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php
# Perform database query
$query = "SELECT * FROM student";
$result = $conn->query($query) or die('Query 1 failed: ' . mysql_error());
?>
<label for="studentSelect">Student Name: </label>
<select id="studentSelect">
<option value="0">Please select</option>
<?php
while ($row = $result->fetch_assoc())
{
echo '<option value="' . $row['studentID'] . '" > "' . $row['studentFirstName'] . '" "' . $row['studentLastName'] . '"</option>';
}
?>
</select>
<div>
<label for="element_5_1">First Name</label>
<input id="element_5_1" name="element_5_1" class="element text large" type="text">
</div>
<div>
<span class="floatLeft">
<label for="element_5_3">Last Name</label>
<input id="element_5_3" name="element_5_3" class="element text medium" style="width:14em" type="text">
</span>
<span style="float:left">
<label for="element_5_4">Major</label>
<input id="element_5_4" name="element_5_4" class="element text medium" style="width:4em" type="text">
</select>
</span>
<span style="float:left">
<label for="element_5_5">Credits Earned</label>
<input id="element_5_5" name="element_5_5" class="element text medium" style="width:6em" type="text">
</span>
</div>
<script type="text/javascript">
function makeAjaxRequest(studentFirstName)
{
$.ajax({
type: "POST",
data: { studentFirstName: studentFirstName },
dataType: "json",
url: "process_ajax.php",
success: function(json)
{
insertResults(json);
},
failure: function (errMsg)
{
alert(errMsg);
}
});
}
$("#studentSelect").on("change", function()
{
var id = $(this).val();
if (id === "0")
{
clearForm();
}
else
{
makeAjaxRequest(id);
}
});
function insertResults(json)
{
$("#element_5_1").val(json["studentFirstName"]);
$("#element_5_3").val(json["studentLastName"]);
$("#element_5_4").val(json["major"]);
$("#element_5_5").val(json["creditsEarned"]);
}
function clearForm()
{
$("#element_5_1, #element_5_3, #element_5_4, #element_5_5").val("");
}
</script>
I then have a separate ajax processing file
<?php
$host = "********.mysql.database.azure.com";
$username = "************";
$password = "*******";
$db_name = "**********";
//Establishes the connection
$conn = mysqli_init();
mysqli_real_connect($conn, $host, $username, $password, $db_name, 3306);
if (mysqli_connect_errno($conn)) {
die('Failed to connect to MySQL: '.mysqli_connect_error());
$studentName = $_POST['studentFirstName'];
$query = "SELECT * FROM student";
$result = mysql_query($query) or die('Query 2 failed: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
if ($studentName == $row['studentFirstName']){
echo json_encode($row);
}
}
?>
I hope I've given enough information for someone to be able to spot my errors. Thank you!
Parse error line 22.
<?php
$host = "********.mysql.database.azure.com";
$username = "************";
$password = "*******";
$db_name = "**********";
//Establishes the connection
$conn = mysqli_init();
mysqli_real_connect($conn, $host, $username, $password, $db_name, 3306);
if (mysqli_connect_errno($conn)){
die('Failed to connect to MySQL: '.mysqli_connect_error());
$studentName = $_POST['studentFirstName'];
$query = "SELECT * FROM student";
$result = mysql_query($query) or die('Query 2 failed: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
if ($studentName == $row['studentFirstName']){
echo json_encode($row);
}
}
}
?>
You have to change also your javascript
function insertResults(json)
{
$("#element_5_1").val(json.studentFirstName);
$("#element_5_3").val(json.studentLastName);
$("#element_5_4").val(json.major);
$("#element_5_5").val(json.creditsEarned);
}
After 4 hours of trial and error, this is the code I came up with that works in populating the input fields. I'm pretty sure your error was the fact that your
<option value="' . $row['studentID'] . '" > "' . $row['studentFirstName'] . '" "' . $row['studentLastName'] . '"</option>
should have been
<option value="' . $row['studentID'] . '" name="studentFirstName"> "' . $row['studentFirstName'] . '" "' . $row['studentLastName'] . '"</option>
anyways onto my code:
config.php
<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = ""; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
?>
index.php
<?php
include("config.php");
$sql = "SELECT * FROM messaging";
$result = $conn->query($sql);
$conn->close();
?>
<!Doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<label for="studentSelect">Student Name: </label>
<select id="studentSelect">
<option value="0">Please select</option>
<?php while ($row = $result->fetch_assoc()) { ?>
<option value="<?php echo $row['msg_id']; ?>" name="studentFirstName" id="studentFirstName">"<?php echo $row['msg_from'] ?>" "<?php echo $row['msg_to'] ?>"</option>
<?php } ?>
</select>
<div>
<span class="floatLeft">
<label>First Name</label>
<input id="populate_first_name" class="element text large" type="text">
</span>
<span class="floatLeft">
<label>Last Name</label>
<input id="populate_last_name" class="element text medium" style="width:14em" type="text">
</span>
<span style="float:left">
<label>Major</label>
<input id="populate_major" class="element text medium" style="width:4em" type="text">
</select>
</span>
<span style="float:left">
<label>Credits Earned</label>
<input id="populate_credits_earned" class="element text medium" style="width:6em" type="text">
</span>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#studentSelect").change(function(){
var studentFirstName = $(this).val();
$.ajax({
url: 'process_ajax.php',
type: 'post',
data: {studentFirstName:studentFirstName},
dataType: 'json',
success:function(response) {
var len = response.length;
for( var i = 0; i<len; i++) {
var studentFirstName = response[i]['studentFirstName'];
var studentLastName = response[i]['studentLastName'];
var major = response[i]['major'];
var creditsEarned = response[i]['creditsEarned'];
$("#populate_first_name").val(studentFirstName);
$("#populate_last_name").val(studentLastName);
$("#populate_major").val(major);
$("#populate_credits_earned").val(creditsEarned);
}
}
});
});
});
</script>
</body>
</html>
process_ajax.php
<?php
include("config.php");
$studentName = $_POST['studentFirstName']; // department id
$sql = "SELECT * FROM student";
$result = mysqli_query($con,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ) {
if ($row['msg_id'] == $studentName) {
$studentFirstName = $row['studentFirstName'];
$studentLastName = $row['studentLastName'];
$major = $row['major'];
$creditsEarned = $row['creditsEarned'];
$users_arr[] = array("studentFirstName" => $studentFirstName, "studentLastName" => $studentLastName, "major" => $major, "creditsEarned" => $creditsEarned);
}
}
// encoding array to json format
echo json_encode($users_arr);
?>
Try it out and lemme know if it works

PHP + MYSQL instant search with radio button filtering

I have with the help of this guide https://www.youtube.com/watch?v=_AqM9U3mi9A created a working search form that displays instant search results (without having to press submit button) with PHP and MYSQL.
Then I wanted to filter the search results depending on what radio button is pressed. Now I also got this to work (partly with the help of this guide https://www.youtube.com/watch?v=DVS4qoB98U8) but ONLY when pressing submit on my search form. It does not work with instant search results for some reason, and that is my problem.
index.php (form):
<form class="form-custom" role="search" action="index.php" method="POST">
<div class="form-group">
<label for="all" class="radio-btn">
<input id="all" class="radio-custom" type="radio" name="searchfilter" value="all" checked="checked"> ALL
</label>
<label for="sports" class="radio-btn">
<input id="sports" class="radio-custom" type="radio" name="searchfilter" value="sports"> SPORTS
</label>
<label for="e-sports" class="radio-btn">
<input id="e-sports" class="radio-custom" type="radio" name="searchfilter" value="e-sports"> E-SPORTS
</label>
<label for="show-business" class="radio-btn">
<input id="show-business" class="radio-custom" type="radio" name="searchfilter" value="show-business"> SHOW BUSINESS
</label>
</div>
<div class="form-group">
<input type="text" name="search" autocomplete="off" class="form-control form-control-custom" placeholder="Search..." onkeyup="searchq();">
<button type="submit" name="submit" value="" class="btn btn-default btn-form-custom">Submit</button>
</div>
</form>
<div class="test" id="output">
<!-- this is where instant search results are supposed to appear -->
</div>
index.php (jquery - requiered for instant search results to work):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php",{searchVal: searchTxt}, function(output){
$("#output").html(output);
});
}
</script>
search.php (PHP code):
<?php
include_once("connect.php");
$output = '';
if (isset($_POST['searchVal']) && isset($_POST['searchfilter']) && trim($_POST['searchVal']) != '' && strlen('searchVal') > 3 ){
$searchq = $_POST['searchVal'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
if($_POST['searchfilter'] == "all") {
$sqlCommand = "(SELECT * FROM sports WHERE Title LIKE '%$searchq%') UNION (SELECT * FROM e_sports WHERE Title LIKE '%$searchq%') UNION (SELECT * FROM show_business WHERE Title LIKE '%$searchq%')";
} else if($_POST['searchfilter'] == "sports") {
$sqlCommand = "SELECT * FROM sports WHERE Title LIKE '%$searchq%'";
} else if($_POST['searchfilter'] == "e-sports") {
$sqlCommand = "SELECT * FROM e_sports WHERE Title LIKE '%$searchq%'";
} else if($_POST['searchfilter'] == "show-business") {
$sqlCommand = "SELECT * FROM show_business WHERE Title LIKE '%$searchq%'";
}
$query = mysql_query($sqlCommand) or die(mysql_error());
$count = mysql_num_rows($query);
if($count == 0){
$output .= '<p class="p-nof">No results found</p>';
}else{
$output .= '<ul ="dropdown">';
$output .= '<p>Search results: '.$count.'</p>';
while($row = mysql_fetch_array($query)){
$title = $row['Title'];
$url = $row['url'];
$id = $row['id'];
$output .= '<a class="searchresult" href="'.$url.'"><li> '.$title.'</li></a>';
}
$output .= '</ul>';
}
}
echo($output);
?>
Thanks in advance for any help!
EDIT:
I changed the javascript to the following:
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
var searchFilter = $("input[name='searchfilter']").val();
$.post("search.php",{searchVal: searchTxt, searchfilterVal: searchFilter}, function(output){
$("#output").html(output);
});
}
</script>
With this change the instant search results are working like before but the radio button filtering is not working. It seems that it's only using the data from the first radio input and ignoring the rest. When I click the other radio buttons it continues to use the data from the one listed first in the form. It does not change as I click.
I still need help with this! Thanks in advance!
Adjust your JS to post the value of searchFilter
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
var searchFilter = $("input[name='searchfilter']").val();
$.post("search.php",{searchVal: searchTxt, searchFilter: searchfilter}, function(output){
$("#output").html(output);
});
}
</script>

Populate a text box based on a dynamic drop down box in php

I am trying to input a value (Rating) from the database when an item is selected. I need to also be able to update that rating and then put that value into another table.
My problem is that I'm trying to figure out how to make the value in the text box be related to the selection made in the drop down. I've found coding to make another option box but cannot figure out how to make that a text box.
REWORDING: Originally when I posted the question I thought it was possible to do this without JQuery and was trying to copy the for loop and run a while loop to populate the text box. I now know that isn't possible and would like to figure out how to run a script to populate a text box on change for the drop down box. The problem being the function has to be connected to the database as well as the drop down.
1. pull the data for the drop down (from the JOURNAL table). 2. Select a journal from that drop down 3. Inside the JOURNAL table a JournalRating has been assigned to every journal pull that value and place inside a textbox.
What I've tried to do is
<?php
include 'dbc.php';
connect();
//insert form values into database
$sql = "SELECT JournalName, JournalID, Rating, JournalActive from JOURNAL where JournalActive = 1;";
//Can take out JournalActive if we do not want it
$result = mysqli_query($conn, $sql);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
echo "there was an issue";
}
$sql2 = "SELECT FName, LName, FacultyID from FACULTY where FacultyActive = 1;";
//Can take out JournalActive if we do not want it
$result2 = mysqli_query($conn, $sql2);
if (!$result2) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
echo "there was an issue";
}
//array to hold all of the data
$journals = array();
//print out all of the first names in the database
$rownumber = 0;
while ($row = mysqli_fetch_assoc($result)) {
$journals[$rownumber][0] = $row['JournalName'];
$journals[$rownumber][1] = $row['JournalID'];
$journals[$rownumber][2] = $row['JournalRating'];
$journals[$rownumber][3] = $row['JournalActive'];
$rownumber++;
}
$faculty = array();
//print out all of the first names in the database
$rownum = 0;
while ($row = mysqli_fetch_assoc($result2)) {
$faculty[$rownum][0] = $row['FName'];
$faculty[$rownum][1] = $row['LName'];
$faculty[$rownum][2] = $row['FacultyID'];
$rownum++;
}
?>
<!DOCTYPE html>
<head>
<link href="styles.css" rel="stylesheet">
<h1> Miami University </h1>
<h4> Information Systems and Analytics Department </h4>
<script>
(function($){
$(function(){
$("#JournalID").on('change', function() {
$("#JournalRating").val($(this).find("option:selected").data('Rating'));
});
});
})(jQuery);
</script>
</head>
<body>
<div class="StyleDiv" >
<!-- coding for journal -->
<form id="form1" name="form1" method="post" action="RR2.php">
<label for="FacultyID">Faculty Name</label>
<select multiple="multiple" name="FacultyID[]" id="FacultyID">
<?php
for($i = 0; $i < sizeof($faculty); $i++) {
print "<option value=\"" . $faculty[$i][2] . "\">" . $faculty[$i][0] .' '. $faculty[$i][1] . "</option>\r\n";
}
?>
</select>
<br class="clear" />
<br class="clear" />
<label for="JournalID">Journal Name</label>
<select name="JournalID" id="JournalID">
<?php
for($i = 0; $i < sizeof($journals); $i++) {
print "<option value=\"" . $journals[$i][1] . "\" data-rating=\"" . $journals[$i][2] . "\">" . $journals[$i][0] . "</option>\r\n";
}
?>
</select>
<br class="clear"/>
<label for="JournalRating">Journal Rating</label><input type="text" name="JournalRating" id="JournalRating" />
<br class="clear" />
<!-- coding for publication -->
<label for="Title">Publication Title</label><input type="text" name="PubID" id="PubID" />
<br class="clear" />
<label for="Year">Year</label><input type="text" name="Year" id="Year" />
<br class="clear" />
<label for="Volume">Volume</label><input type="text" name="Volume" id="Volume" />
<br class="clear" />
<label for="Issue">Issue</label><input type="text" name="Issue" id="Issue" />
<br class="clear" />
<label for="Comments">Comments</label><textarea name="Comments" id="Comments" cols="45" rows="5"></textarea>
<br class="clear" />
<input type="submit" name="Submit" id="Submit" value="Submit" />
<br class="clear" />
</br>
</br>
</div>
</form>
<?php
//Post Parameters
$JournalID = $_POST['JournalID'];
//for($i = 0; $i < sizeof($journals); $i++) {
//if ($JournalID = $journals[$i][1]) {
//$JournalName = $journals[$i][0];
//}
//}
$Year = $_POST['Year'];
$Comments = $_POST['Comments'];
$Volume = $_POST['Volume'];
$Issue = $_POST['Issue'];
$Title = $_POST['Title'];
$JournalRating = $_POST['JournalRating'];
$FacultyMemID = $_POST['FacultyID'];
//Query
//INSERT
$stmt = $conn->prepare(" INSERT INTO PUBLICATION ( JournalID, Year, Comments, Volume, Issue, Title, JournalRating ) VALUES ( ?, ?, ?, ?, ?, ?, ? )");
$stmt->bind_param('sssssss', $JournalID, $Year, $Comments, $Volume, $Issue, $Title, $JournalRating);
$stmt->execute();
$pubID = $stmt->insert_id;
$facmemid = 0;
$stmt = $conn->prepare(" INSERT INTO FACULTYPUBLICATIONS ( FacultyID, PubID ) VALUES ( ?, ? )");
$stmt->bind_param('ii', $facmemid, $pubID);
//for ($_POST['FacultyID'] as $FacultyMemID) {
for($i = 0; $i < sizeof($FacultyMemID); $i++) {
$facmemid = $FacultyMemID[$i];
$stmt->execute();
}
mysqli_close($conn);
?>
</body>
</html>
Add the rating to your HTML using a data attribute:
<select name="JournalID" id="JournalID">
<?php
for($i = 0; $i < sizeof($journals); $i++) {
print "<option value=\"" . $journals[$i][1] . "\" data-rating=\"" . $journals[$i][2] . "\">" . $journals[$i][0] . "</option>\r\n";
}
?>
</select>
Then you can access this using jQuery .data():
(function($) {
$(function() {
$("#JournalID").on('change', function() {
$("#JournalRating").val($(this).find("option:selected").data('rating'));
});
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="JournalID">
<option>Select a journal</option>
<option value="1" data-rating="3">Journal #1</option>
<option value="2" data-rating="2">Journal #2</option>
<option value="3" data-rating="5">Journal #3</option>
</select>
<br>
Rating: <input id="JournalRating">

Categories