How to get data contain white space using ajax - javascript

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>

Related

Add new selection with options from database

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 :)

Oop check if database table is empty

I have a selector wich gets information from the database. But when my database table is empty, the selector still shows up like this:
However, when my database is empty. I don't want to show the selector. but a message that says something like: Database is empty! Add something.
My code for the selector:
$results = $database->Selector();
echo "<form name='form' method='POST' id='selector'>";
echo "<select name='train_name' id='train_name' multiple='multiple'>";
// Loop trough the results and make an option of every train_name
foreach($results as $res){
echo "<option value=" . $res['train_name'] . ">" . $res['train_name'] . "</option>";
}
echo "</select>";
echo "<br />" . "<td>" . "<input type='submit' name='Add' value='Add to list'/>" . "</td>";
echo "</form>";
The function:
function selector() {
$sql = "SELECT train_name, train_id FROM train_information ORDER BY train_name";
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $sth->fetchAll();
}
EDIT:
Got this now:
$results = $database->Selector();
if(count($results) > 0) {
//Form etc here//
}else echo "nope";
It is working now! :D

Stuck in endless loop while creating buttons

I'm trying to create a website, where I can insert products with a button.
So for now I got one button which creates one div as a product box. When the button is clicked it becomes invisible, under this I can see the div now; and under the div, there's the next button which should be able to create one more divs (always the same way).
The problem is that I can't find any solution to do that. I always land in an endless loop.
If you're wondering about the mailer, the idea for the first step is, to send a mail as newsletter for every created product.
Here's my code:
<?php
echo "<form action='index.php' method='GET'>";
echo "<input type='submit' name='insert' id='insert' value='INSERT'>";
echo "</form>";
if ($_GET["insert"]) {
echo " <script language='JavaScript'> ";
echo "";
echo " ";
echo " document.getElementById('insert').style.visibility='hidden' ";
echo "";
echo "</script>";
echo " <div class='article'>";
echo "<h2>product</h2>";
echo "<p>";
echo "EXAMPLE";
echo "</p>";
echo "</div> ";
echo "<form action='index.php' method='GET'>";
echo "<input type='submit' name='ins ert' id='insert' value='INSERT'>";
echo "</form>";
//send mail
$message = "hello TEST!";
for ($i = 0; $i < $z; $i++) {
mail('' . $res[$i] . '', 'Newsletter', $message);
}
}
?>
You are hiding an "id=insert" item, and then creating a second "id=insert" item. So you get 2 identical id, which is not good.
You should "remove" the "id=insert" rather than "hide" it. jquery may help you on that.
(And so you may not need to remove the "id=insert" item, but rather "add" a new div "after" your last product).

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!

JavaScript dropdown menu does not work in IE8

I'm using an on change for a drop down menu to display information once a choice is chosen from the dropdown. This works fine in Firefox and Chrome but I have been hoodwinked into having to use ie8 and this on change does not seem to fire. Any help would be much appreciated. Its a mix of php and html the lower part is js which outputs info when chosen.
echo "<p><h2> To View a Route: </h2><br> Pick a routes name from the list and all its information can be viewed below the selection box.</p>";
echo "<p><FORM METHOD=\"post\" ACTION=\"controller.php\">";
echo "<select class=\"toggle-data\" name='selectallrouteinfo'>";
echo "<option value=\"\">Choose a Route </option>";
for ($i = 0; $i < sizeof($list1); $i++) { //going through each element of array and outputting route
if (is_string($list1)) {
echo "<option value=\"\" data-toggle = \"$id1\" >$list1</option>";
} else {
$space = " ";
$id = $list4[$i];
$id1 = "#" . $list4[$i];
echo "<option data-toggle = \"$id1\" value=\"$id\">" . $list1[$i] . $space . $id . "</option>";
$idHolder[$i] = $id; //array for holding ids so that it passing the correct id to my loops below
}
}
echo "</select></form></p>";
for ($k = 0; $k < sizeof($idHolder); $k++) { //my outer loop is going through the ids, fitting correct id to the div and dbm obj
echo "<div id=\"$idHolder[$k]\" style=\"display: none;\">
";
$allRouteInfo = $DBM1->getAllRouteData($idHolder[$k]);
for ($j = 0; $j < sizeof($allRouteInfo); $j++) { // my inner loop is going through each element of array and outpting all route info
if (is_string($allRouteInfo)) {
echo $allRouteInfo; //if theres no info, there is no array, it has returned a string
} else {
echo $allRouteInfo[$j]; //if there is arry, happy days
}
}
echo "</div>";
//below is a js/jquery script for outputting my choice in the select of route info
echo " <script>$('.toggle-data').on('change', function() { //jquery for printing my valuable info on change
var toggle = this.options[this.selectedIndex].getAttribute('data-toggle'),
toggle_class = 'unique_classname';
$('.'+toggle_class+', '+toggle).toggle().removeClass(toggle_class);
$(toggle).addClass(toggle_class);
}); </script>";
echo " </div>";

Categories