Selecting values of select dropdown using javascript code - javascript

I have a form.php which adds username selected from dropdown select, and user payments received into database. After inserting values by going to add_form.php, it comes back to form.php. I have sent the username from add_form.php to form.php by using below code
$result=mysql_query($sql);
if($result==1){
echo '<script language="javascript">';
echo 'alert("Payment added successfully");';
echo 'window.open("form.php?name='.$name.'", "_self");';
echo '</script>';
}
Now problem is that, how can I use this get parameter to select the passed value into dropdown automatically? I want the end user of the application to select a name once and add multiple payments, i.e., selected name should be there even after payment is added into db

I am not sure what you want but if filling up the select with options dynamically (with some js variables) is what you want then you can try something like.
$("#id_something").empty();
$("#id_something").append('<option selected="selected" value='+somejsvariable+'>'+someotherjsvariable+'</option>');
Hope it helps.

Related

Don't know how to solve (Between Php and Javascript)

I don't know how to solve the variable $cat by following script.
"text" variable from Form to javascript and pass to php function to be $Categories_name and to be $cat.
I already test the $cat variable, it is not "String", it is "object", I don't understand.
But I need $cat to be "String".
when Test = "This is Cat" (3 words),
I test $cat by php str_word_count and the output is 1 (I need to correct answer 3);
I test $cat by php var_dump and no output (I need to correct answer "String").
<p id="CaTable"></p>
<script>
function CaFunction()
{
var text = document.getElementById("CategorySelect").value;
document.getElementById("CaTable").innerHTML = "<?php php_catable('" + text + "'); ?>";
}
</script>
<!-- Generate Table by php and MySQL-->
<?php
function php_catable($Categories_name)
{
$cat = $Categories_name;
.................
.................
$sql = "select * from table where xyz = '" .$cat. "'";
}
?>
You are confusing server side code and client side code. Your php code live on the server and can only be executed on the server. And your javascript is on your client's browser and does not know about the server (remember, php generate a text file, and only that text file is sent to the browser). if you want to use the php_catable() function from your client, you will need to do an AJAX call or to redesign your page to do a form submit (just like what Steve is proposing).
Your First Page:
Assuming CategorySelect is a dropdown select box, create a script for its onChange event and create a method="post"post form with a hidden input that goes to "generate_table.php".
<input type="hidden" name="ca_table" id="ca_table" />
You make ca_table a hidden input so php will pick up the value from it when this page gets submitted to a second page where you can generate your table using the php function.
<script language="javascript" type=text/javascript>
function CaFunction(){
documentGetElementById('ca_table').value = documentGetElementById('CategorySelect').value;
submit();
}
</script>
add this to your select dropdown:
onChange="CaFunction();"
Your Receiving Page:
So your receiving page "generate_table.php" would have
<?php
function php_catable($Categories_name)
{
$cat = $Categories_name;
.................
.................
$sql = "select * from table where xyz = '" .$cat. "'";
}
$category_name = $_POST['ca_table']; // cleaned up at least with suitable preg_replace etc
// and call your catable function
php_catable($category_name);
?>
So that way your result will have been posted back to the server as per comments about client side/server side by #Fluinc and answer by #litelite. To get it to do something which performs looking like innerHTML which changes a part of the page without submitting the whole page you will need AJAX, again as per #litelite's answer.
Might get marked down for being dependant on JavaScript but intended mostly to help clarify client v server.
If you want to avoid the JavaScript dependency of this script you could leave out the onChange altogether and add a submit button, then collect $_POST['CategorySelect']; assuming that is its name - ensure it has name="CategorySelect" for php as well as its Id for your css/javascript. Php gets its variable from the item's name.
To get something a bit like the effect of AJAX visually (though the page is still submitted) you could submit the page to itself using action="<?php echo $_SERVER['PHP_SELF']; ?>" on the form and have all the code on the one page. You can put the table generating code in the div where you want the table to appear - it would need a default state set, of course.
#litelite's comment regarding not using posted data directly in an sql query is also vital to prevent attack - make sure you clean it up before you use it!

Dropdown box getting values from mySQL shows blanbk entries

I'm using the template from this mySQL x AJAX tutorial (http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html) to create dependent dropdowns.
How the code should work:
Coach selects what activity group ($activity) he wants to browse from box one.
Box two the populates with a list of players($username) who are part of that activity.
It does the above, but the entries show up blank as opposed to printing the name - see screenshot attached. Below is the piece
<?php
if($_POST['activity'])
{
$activity=$_POST['activity'];
$sql=mysql_query("SELECT id AND username FROM player WHERE activity='$activity'");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$username=$row['username'];
$activity=$row['activity'];
echo '<option value="'.$username.'">'.$username.'</option>';
}
}
?>
I've messed around with the number of entries in the db, and the blank values change respectively (when changed to 5 people being in group, 5 blank spaces show, etc.)
It's really odd because of the fact it appears to be working, just not showing the names.
Any ideas?
Cheers.
Try fixing your query. You are ANDing the values id and username
SELECT id, username FROM player WHERE activity='$activity'
You forgot to isset your $_POST['activity'].

Why the JavaScript result always return first value?

here is my problem. I'm currently trying to customize joomla article content with some module. As i'm trying out hide some div before the user had click on the input. Lets say user click Test1 which is a radio button , then another field which i hide with div will shown up the content of Test1. All the detail is load from mysql database.
Here is my javascript code that i trying to show the value. But it alway show me first value although i click other value suck as Test2 or Test3.
Example:
<script type="text/javascript">
function showBox1(){
document.getElementById('hideBox1').style.display ="";
var test = document.getElementById('123').value;
confirm (test);
</script>
Here is my php code:
<?php
// Get default database object
$db =JFactory::getDBO();
// Get a new JDatabaseQuery object
$query = $db->getQuery(true);
// Build the query
$query->select($db->quoteName('campusid'));
$query->from($db->quoteName('campus'));
$query->where($db->quoteName('collegeid').'='. $db->quote('1'));
// Set the query for the DB oject to execute
$db->setQuery($query);
// Get the DB object to load the results as a list of objects
$results = $db->loadObjectList();
if($results){
foreach($results as $result)
{
echo "<label class='option block spacer-t10'>";
echo "<input type='radio' name='$result->campusid' id='123' value='$result->campusid' onClick='return showBox1()'><span class='radio'></span>";
echo $result->campusid;
echo '</label>';
}
}
else{ echo 'Error';}
?>
As an example the output for first div is 3 radio button, each radio button had it own value. When user click on either 1 of the radio button then it should pass the correct value to be shown up so that i can bring the value to the next div to select my database data. Is there any mistake i had made on my code that make me alway getting the first value although i click other radio button?
Each radio button is an element in its own right. The radio group is not a single element.
Every radio button has the same id, which is invalid and not allowed in HTML.
When you getElementById, the browser attempts to perform error recovery and gets the first element with that id (ignoring the others).
If you want to deal with a group of elements, then:
make them members of a class
getElementsByClassName
Loop over the result and test the checked property
When you find a true checked take the value of that element
Your radiobuttons have the same id 123. You are selecting the element from the DOM using this id. Make sure every radiobutton has a unique id.
You don't even need the Id if you pass the element to the function.
HTML:
onClick='return showBox1(this)'
JavaScript
function showBox1(element){
confirm (element.value);
}
First of all, all the radio buttons have the same id attributes: "123".
The document.getElementById() function expects, that a certain id is only present once on a page.
If you want to get the selected value for the elements with id "123", then you should select like this:
var test = document.querySelector("#123:checked")[0].value;
If this doesn't work, then try:
var test = document.querySelector("[id=\"123\"]:checked")[0].value;

Why onchange event taking me to new page?

I am trying to populate a text field with the value of the select field.
So based on the selection the text field should change.
In this case, I am selecting First Name and Last name of the person and in the
option value="I have person email here"
Now, I am using onchange event on select element which calls the findemail() function.
Problem is I am getting the correct emails return but
it redirect me to another page and show me the value there.
Can anyone please help me?
CODE
function findemail(e)
{
document.getElementById('man-email-add').innerHTML=document.write(e.value);
}
HTML (I am using PHP to get all the values)
<select id="manager_detail" onchange="findemail(this.options[this.selectedIndex]);">
<?php
foreach ($data['display']['userMangers'] as $manager){
echo $manEmail = $manager['Email'];
echo "<option value='$manEmail'>".$manager['First_Name'].' '.$manager['Last_Name'].' ('.$manager['Position'].')'.'</option>';
}
?>
</select>
Redirect to new page to show the value:
It's because you're using document.write() after the page has loaded, which doesn't look necessary here anyway:
document.getElementById('man-email-add').innerHTML= e.value;
Does it redirect to new page or reloads the same page showing the email? I believe it's doing the later as document.write(e.value); writes that value to the page. So replace document.write(e.value); with e.value;
If man-email-add is an input field, use document.getElementById('man-email-add').value=e.value;

Execute script when select option is changed

I have a html form which includes a dynamically created dorpdown list. The dropdown list contains the names of newsletters which are stored in my MySQL database. What I want the dropdown list to do is: When I select a newsletter an other php script will activate which will take the data from the newsletter in my DB and writes it to a .txt file. The codes I currently have is:
The dropdown list:
<?php
echo "<select id=\"NieuwsbriefSelect\" name=\"show\">";
echo "<option size =30 selected>Select</option>";
if(mysql_num_rows($sql_result))
{
while($row = mysql_fetch_assoc($sql_result))
{
echo "<option value=\"$row[Titel]\">$row[Titel]</option>";
}
}
else {
echo "<option>No Names Present</option>";
}
?>
And the write script:
<?php
$title = $_REQUEST["show"];
mysql_connect('localhost','root','root');
mysql_select_db('NAW') or die (mysql_error());
$strSQL = "SELECT Content from NAW.Mail where Titel = '$title' ";
$sql_result = mysql_query($strSQL);
$row = mysql_fetch_assoc($sql_result);
$file = 'nieuwsbrief.txt';
$current = $row["Content"];
file_put_contents($file, $current);
?>
I do not want the page to redirect to the write script but just to execute it (I hope you get this^^). Is this possible using the HTML onChange Event or do I have to use javascript? Any help would be great and if you have a question about my code just ask in the comments!
NOTE!
I know I shouldn't be using Mysql_* and That I am vulnerable to sql injection but that is not the point.
You need to define a onchange event on your SELECT option and inside this onchange event, you can redirect to another page with selected item OR do an AJAX call to another PHP script
Unfortunately what you are asking is not possible without JavaScript. PHP is a server side language and therefore cannot be run, without a call from the client-side browser. You're best bet would be to use ajax in conjunction with the JavaScript onchange event. When the change event occurs, fire an ajax call off to the server to run the script with the selected option. This is the only way to do what you're asking without a page reload or redirect.

Categories