Add new selection with options from database - javascript

I have a function to add a new selection using button in the table with ID="maTable"
<button type="button" onclick ="addNew()"> Add More Agent</button>
Using JS :
function Addnew(){
var table=document.getElementById("maTable");
var row=table.insertRow([table.rows.length]-1);
var len=(table.rows.length);
var newid="agentID"+len;
var newida="agentGroup"+len;
var cell1=row.insertCell;
var cell2=row.insertCell;
var cell3=row.insertCell;
var new_optionAgent =
"<select class=\"opsi\"id="'+newida+'">"
+"<option selected=\"selected\"disabled=\"disabled\">Agent<\/option>"
+"<option value=\"agentA\">Agent A<\/option>"
+"<option value=\"agentB\">Agent B<\/option>"
+"<option value=\"agentC\">Agent C<\/option>"
+"<option value=\"agentD\">Agent D<\/option>"
+"<\/select>"
cell1.innerHTML="Choose Agent" +" "+len;
cell2.innerHTML=":";
cell3.innerHTML= new_optionAgent;
}
With this I can get a button that will generate a new selection with 4 options (it works). But now come the problem when I want to change the option with the list from database. Im using php and postgres database. I made the code for the one that isn't generated from the "AddNew" button yet :
<?php
$que=pg_query("SELECT agentname FROM Agent");
echo "<select name=\"agentname1\"class=\"opsi\" id=\"agentGroup1\" required>";
echo "<option value=\"\" selected=\"selected\"disabled='disabled'>Agent</option>";
While($row=pg_fetch_array($que))
{
echo '<option value="'.$row['agentname'].'"> '.$row['agentname'].'</option>';
}
echo "</select>";
?>
Now I want to make the "AddNew" button that generate a selection with option list from database. I have combined the php code with variable "new_optionAgent" by adding "\" to some symbols. but it doesnt work.
I combine like this
var new_optionAgent =
'<\?php
\$que=pg_query(\"SELECT agentname FROM Agent\")\;
echo \'<select name=\\\"agentname1\\\"class=\\\"opsi\\\" id=\\\"agentGroup1\\\" required>\'\;
echo \'<option value=\\\"\\\" selected=\\\"selected\\\"disabled=\\\'disabled\\\'>Agent</option>\'\;
While(\$row=pg_fetch_array(\$que))
{
echo \'<option value=\"\'\.$row[\'agentname\']\.\'\"> \'\.$row[\'agentname\']\.\'</option>\'\;
}
echo \"<\/select>\"\;
\?>'
this combination is seems very wrong, Any help? Thank you

This is not working because the escaped backslashes is used by PHP for escaping the double quotes. So you will need to add another set of backslases and escape those, or use a single quote string in PHP:
<?php
$que=pg_query("SELECT agentname FROM Agent");
echo '<select name=\"agentname1\"class=\"opsi\" id=\"agentGroup1\" required>';
echo '<option value=\"\" selected=\"selected\"disabled=\'disabled\'>Agent</option>';
While($row=pg_fetch_array($que))
{
echo '<option value="'.$row['agentname'].'"> '.$row['agentname'].'</option>';
}
echo "</select>";
?>
Edit
You can't inline PHP inside a Javascript variable like that. Try this:
<?php
$que=pg_query("SELECT agentname FROM Agent");
$whateverYouWannaCallThisString = '';
$whateverYouWannaCallThisString .= '<select name=\"agentname1\"class=\"opsi\" id=\"agentGroup1\" required>';
$whateverYouWannaCallThisString .= '<option value=\"\" selected=\"selected\"disabled=\'disabled\'>Agent</option>';
While($row=pg_fetch_array($que))
{
$whateverYouWannaCallThisString .= '<option value="'.$row['agentname'].'"> '.$row['agentname'].'</option>';
}
$whateverYouWannaCallThisString .= "</select>";
?>
<script type="text/javascript">
var new_optionAgent = "<?php echo $whateverYouWannaCallThisString; ?>";
</script>
More info on escaping
The whole reason you are escaping characters is because you are using characters that surrounds the string itself. E.g: If you are defining a string with double quotes " like this: var myString = "Yolo" and you want to have double quotes " in that string like this: var myString = "Dude, wheres "my" car" then you need to escape the double quotes " thats inside that string like this: var myString = "Dude, wheres \"my\" car".
The same applies to PHP
//Edit :
I edited the variable :
var new_optionAgent =
<?php echo json_encode($whateverYouWannaCallThisString); ?>;
and it works :)

Related

Make cell a clickable link in Bootstrap using URL stored as string in database

I have a mysql database table called "names" as per below :
All columns (other than id) are stored as varchar
There is a full .php URL stored in Column "Full Name" for each record but I am getting a stackoverflow code error when using the URL in table below.
id
First Name
Surname
Full Name
Profile
1
John
Smith
John Smith
.PHP URL stored as a text string
2
Jane
Doe
Jane Done
.PHP URL stored as a text string
3
Prakash
Singh
Prakash Singh
.PHP URL stored as a text string
I have some mysql and php that returns the records for the first four columns and puts them into a bootstrap table :
<?php
// Include config file
require_once "conn.php";
// Attempt select query execution
$sql = "SELECT * FROM names";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '<table class="table table-dark table-hover table-bordered table-striped">';
echo "<thead>";
echo "<tr>";
echo "<th>#</th>";
echo '<th>First Name</th>';
echo "<th>Surname</th>";
echo '<th>Full Name</th>';
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['First Name'] . "</td>";
echo "<td>" . $row['Surname'] . "</td>";
echo "<td>" . $row['Full Name'] . "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo '<div class="alert alert-danger"><em>No records were found.</em></div>';
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close connection
mysqli_close($link);
?>
What I would like to do:
Make all cell's in Column "Full Name" to be independently clickable.
Onclick, I would like to take the user to the respective profile URL of the record id without opening a new page.
Attempts:
I added a class to the td for Full Name for an onclick event :
echo "<td class='clickme'>" . $row['First Name'] . "</td>";
This made only the first row of the table clickable.
I added some javascript for the class :
var myMap = document.getElementById("clickme");
myMap.onclick = function() {
var myVar = window.location.replace("https://www.stackoverflow.com");
};
This partially worked, the page refreshes and redirects to the URL provided. However, as each record has it's own URL (stored in the database) I'd like to retrieve the specific URL rather than input an absolute URL here.
Thanks alot in advance for any help rendered!
I never worked with php but in plane html js. you can pass your url through data attibute.
<td class='clickme' data-url="your_cell_url"> First Name </td>
and then in js file
var myMap = document.getElementById("clickme");
myMap.onclick = function() {
var url = this.dataset.url
var myVar = window.location.replace(url);
};
i think it may helps
Try:
echo "<td>" . $row['First Name'] . "</td>";
or if you're using get method for profile page it will look something like this:
echo "<td>" . $row['First Name'] . "</td>";

How to get data contain white space using ajax

I've a problem when i try to get data with white space. When there is white space, it only get the first word.
Data on database contain white space
When selected the dropdown, this alert will appear and it display nothing. If there is no white space, it will display the data.
Alert
This is my ajax function
function tampiltugas(namatema)
{
url = urlumum+"Pengetahuan/Tema1/get_daftar_nilai.php?namatema=" + namatema;
getAjax();
alert(url + " ");
ajaxRequest.open("GET",url);
ajaxRequest.onreadystatechange=function()
{
document.getElementById('tabelTugas').innerHTML = ajaxRequest.responseText;
}
ajaxRequest.send(namatema);
}
This one is dropdown using onchange to call the ajax function
<?php
echo "<center><div style='display:none;' id='formtugas'>";
echo "<select id='mapel' name='mapel' class='form-control11' onchange='tampiltugas(this.value);' required>";
$query1 = mysqli_query($dbh,"SELECT KodeTema, NamaTema FROM tema WHERE KodeKelas='1'");
echo "<option selected disabled>Pilih Tema</option>";
while ($ambiltema = mysqli_fetch_array($query1))
{
echo "<option value=".$ambiltema['NamaTema'].">".$ambiltema['NamaTema']."</option>";
}
echo "</select>";
echo "</div>";
?>
You need quotes around the values.
echo "<option value='".$ambiltema['NamaTema']."'>".$ambiltema['NamaTema']."</option>";
Otherwise the HTML looks like:
<option value=info with spaces>info with spaces</option>

Displaying JSON data created using PHP and MySQL

I have a form on an HTML page which posts a user input to a PHP which executes a SQL statement to get information from a database and output it in JSON. Here is my PHP code to get the JSON data:
<?php
header('Content-type:application/json');
$con = mysqli_connect('localhost','root','','dbname');
if(isset($_POST['submit']))
{
$artist = $_POST['artist'];
$select = mysqli_query($con, "SELECT * FROM tblname WHERE artistName = ". $artist);
$rows = array();
while($row = mysqli_fetch_array($select))
{
$rows[] = $row;
}
echo json_encode($rows);
};
?>
When I submit the form on the HTML page, it goes to the PHP page and I get this result:
[{"0":"6","id":"6","1":"OASIS","artistName":"OASIS","2":"SOME MIGHT SAY","songTitle":"SOME MIGHT SAY","3":"1995-05-06","dateNo1":"1995-05-06"}]
(Code and JSON result have been simplified for this question)
Instead of going to this page, I'd like the data to be displayed nicely on the HTML page so that a user does not see this array. I'm not sure how to do this, any help?
Thank you!
If you want the output formatted nicely, why are you encoding in JSON? JSON, although human-readable, isn't intended to be rendered on-screen as an end product.
I'd recommend looping through the $rows array and building a simple HTML table. You could, of course, wrap the data in any markup you like and even add CSS to style it as you see fit. Here's an example to get you started:
echo "<table>";
foreach($rows as $row) {
foreach($row as $key => $value) {
echo "<tr>";
echo "<td>";
echo $key;
echo "</td>";
echo "<td>";
echo $value;
echo "</td>";
echo "</tr>";
}
}
echo "</table>";
If you only want some of the data rendered, you can simply echo those values:
foreach($rows as $row) {
{
echo "Artist:" . $row['artistName'];
echo "<br>";
echo "Song Title:" . $row['songTitle'];
echo "<br>";
echo "Date:" . $row['dateNo1'];
}
There are two ways to solve this problem :
Perform AJAX call from Javascript to PHP Page and parse the success response in to the HTML.
Simply echo the values in PHP Page or add HTML itself in PHP Page as suggested by Tim.

Assigning and getting value from same ID name

I'm using x-editable http://vitalets.github.io/x-editable/index.html a jquery inplace editor. Currently I have a working code like below:
<?php
$num_rows = 1;
// store the record of the "tblstudent" table into $row
while ($row = mysqli_fetch_array($result)) {
echo "<script type=\"text/javascript\">
$.fn.editable.defaults.mode = \"popup\";
$('#username$num_rows').editable();
</script> "; //assign num to element
// Print out the contents of the entry
echo '<tr>';
echo '<td><a href="#" id="username' . $num_rows . '" data-type="text" data-pk="' . $row['id'] . '" data-url="post.php" data-title="Edit website">';
echo htmlspecialchars($row['website'], ENT_QUOTES, 'UTF-8');
echo '</a></td>';
echo '</tr>';
$num_rows++;
}
?>
Which result in the following:
but as you can see I use $num_rows in assigning element ID and getting the ID with javascript. I prefer not to use loop to assign uniq ID to element or include the javascript in php tag. Is there any elegant solution than this?
Thanks in advance.
Keep the id as username or infact add class='username' instead of id.
<script type="text/javascript">
$.fn.editable.defaults.mode = "popup";
$('.username').click(function(){
$(this).editable();
})
</script>

PHP Counter not working, can't update MySQL Database

I'm editing some PHP/Javascript codes that control a MySQL Database, and there is an issue where I cannot update old database entries. There are two php files--update.php and success.php.
In the update.php, there is a counter, $c, that is a variable for the rows in order to tell them apart. In success.php, it takes, I presume, the number that $c is (named 'count'), and results into the value for $i. The code is below--
Update.php:
<?php
$c = 0;
while ($row=mysql_fetch_row($result))
{
echo"<tr>";
echo "<td><div class='required'><input type=\"text\" name=\"".$c."ID\" onchange=\"turnWhite(this)\" size=\"7\" value= \"" .$row[3]."\"></div></td>";
echo "<td><select name='".$c."Dataset1' onchange=\"return CheckData(".$c.")\">
<option value='".$row[0]."'>".$row[0]."</option>";
$result1=mysql_query('SELECT Data FROM Database.Table2 ORDER BY Data');
while ($row1=mysql_fetch_row($result1))
{
echo '<option>' . $row[0]. '</option>';
}
echo "</select></td>";
echo "<td><select name='".$c."Dataset2' onchange=\"return CheckData(".$c."\">
<option value='".$row[1]."'>".$row[1]."</option>";
$result=mysql_query('SELECT Data FROM Database.Table2 ORDER BY Data');
while ($row1=mysql_fetch_row($result1))
{
echo '<option>' . $row[0]. '</option>';
}
echo "<td><input type=\"text\" id=\"".$c."Dataset_column2\" name=\"".$c."Dataset_column1\" size=\"30\" value= \"" .$row[2]."\"></td>;
echo "<td><input type=\"text\" name=\"".$c."Dataset_column3\" size=\"30\" value= \"" .$row[3]."\"></td>;
echo "<td><div id='centerbutton'><input type='button' value='Update' onclick='validate(".$c."); return false;' /></div></td>";
$rows = "where 1=1 and `COLUMN2` ='" .$row[2]."' and `COLUMN3` ='".$row[3]."'";
echo "<input type=\"hidden\" name=\"where".$c."\" value=\"".$rows."\">";
$c++;
Success.php:
$previous_URL = $_SERVER['HTTP_REFERER'];
$empty = "";
if(strpos($previous_URL,'update.php') !== false)
{
$i = $_GET['count'];
if ($_FILES[$i."file"]["error"] > 0)
{
}
else
{
}
if (file_exists("C:/Web_content/Upload/" . $_FILES[$i."file"]["name"]))
{
echo "A file of this name already exists.
Please rename your file and upload it again.";
}
if ($stmt = $mysqli->prepare("UPDATE `table` SET `COLUMN2` = ?,
`COLUMN3` = ? ". $_POST['where'.$i] ))
I left some extra code out. My question is, what is it echoing, and how exactly does the $c counter work in update.php. And also in the success.php, what is the $i variable resulting into when it $_GET['count']. I keep getting the error code "A file of this name already exists.
Please rename your file and upload it again" but I'm not even uploading a file (in another column that I left out). Is it a problem in the update or success page? Why isn't up letting me update old database entries in MySQL through these codes?
Also, on a separate issue (but same php codes), sometimes when I try to update my new data, it would give me an error code saying that "A file exists" but under that it'd say "Notice: Undefined index: where170 in C:\Web_content\success.php" on the line where $_POST['where'.$i] is.
And then all my data would turn into NULL (so everything would be gone. But I backed my data up so I simply just import back my data when this happens).
Thank you in advance!

Categories