JQuery populating select box but after post options disappear - javascript

I have an SVG map. When someone clicks on a state say, "Kansas" it displays a form and populates the state select box with the state that was clicked on say, it's Kansas. Code - This is working fine. This code is in the head.
var itemval= '<option value="'+data.name+'">'+ stateData[data.name].fullName+'</option>';
$("#SelItem").html(itemval);
When the form is submitted and it posts back to the same page, I'm using
<form method="POST" action="theform.php" onsubmit="return validateForm(this);">
When the page post back to the same page the select box is empty. The select box is there but with no option.
I've searched on Google I found the code below plus a few similar ways but they don't work. I've used this code in the head and under the select but no luck.
var selectedVal = $("#SelItem").val();
$("#SelItem").val(selectedVal);
**HTML**
<select id="SelItem"><option></option></select>
I've been working on this for hours but can't seem to find a solution.
Can someone tell me how to keep the select value after the form has been submitted and returns to the same page?

When the page loads you need to check for the presence of your posted value, and if it's there pass the php value to either the javascript code to populate the select option, or use it directly in the html creating the select options.
First off, you should give your select a name attribute in the html so the value is passed into the $_POST array in php:
<select id="SelItem" name="SelItem">
Here's one way you can populate it in javascript (note this code relies on the var stateData being in the same scope):
$(document).ready(function(){
<?php if (!empty($_POST['SelItem'])): ?>
var posted_state = '<?php echo $_POST['SelItem'];?>';
if (stateData[posted_state] !== undefined) {
var itemval= '<option value="'+posted_state+'" selected>'+ stateData[posted_state].fullName+'</option>';
$("#SelItem").html(itemval);
}
<?php endif; ?>
});
EDIT: An alternative to the above would be to put it in the html for the select tag:
<select id="SelItem" name="SelItem">
<?php if (!empty($_POST['SelItem'])): ?>
<option value="<?php echo $_POST['SelItem'];?>" selected>
<?php echo $_POST['SelItem']; // this would be better if you can replace it with fullname ?>
</option>
<?php else: ?>
<option></option>
<?php endif; ?>
</select>
Note this method has a couple issues as it's written. First off, the option text in this example won't be the state full name but the abbreviation. Next, you shouldn't trust the contents of $_POST because a malicious user can easily change it to a value you didn't intend it to be. It would be better to validate the value of $_POST['SelItem'] in your php code that handles the post to make sure it is actually one of the correct values before using it. That is why in the previous example I did the check if (stateData[posted_state] !== undefined) before attempting to add the value to your select.
EDIT:
To provide the state fullname from php you need an array of states defined on the php side also (I only see it in your javascript code which is client side).
So in php if you have something like:
$states = array(
'AK' => 'Alaska',
'AL' => 'Alabama',
// etc...
);
Then you can use the posted state abbreviation to get the fullname:
if (array_key_exists($_POST['SelItem'], $states))
$fullname = $states[$_POST['SelItem']];

Related

How to pass value of the table row into the variable in modal

I have a table from which I am successfully passing values into the textfields in modal. However, I need to create the select dropdown within modal, which will be based on value passed from the row.
Table
edit | ref. number |
.edit_record button | AAA01 |
js
$(document).ready(function () {
$('.edit_record').on('click', function() {
$('#edit_record_modal').modal('show');
$tr = $(this).closest('tr');
var data = $tr.children("td").map(function() {
return $(this).text();
}).get();
console.log(data);
$('#ref').val(data[1]);
});
});
modal
<div class="form-group">
<input id="ref" type="text" name="ref" class="form-control">
</div>
<div class="form-group">
<select name="selectDate" id="selectDate" onchange="">
<?php
$ref_list_result= mysqli_query($db_conn,"SELECT ref_no FROM record WHERE
caller_number= /*the value of row*/");
while ($row = mysqli_fetch_array($ref_list_result)) {
$ref_no = $row['ref_no'];
?>
<option value=<?php echo $ref_no ?>><?php echo $ref_no ?></option>
<?php } ?>
</select>
</div>
Is it possible to pass that value from #ref textfield into the php variable, so I can compare it against condition in SQL's WHERE clause? Perhaps, maybe there is a different way to do this?
Short Answer: You cant pass variables in PHP and JavaScript unless you are using an API to transfer data
Long Answer:
If you only know how PHP works, it is what is called a "Pre-templater" which means that in the server, or somewhere it is deployed, the server translates PHP codes into HTML and JavaScript depending on your echo. This means that by the moment the code you've written gets sent to the browser, it is all HTML, JS and CSS.
Alternative Approach: You could try building an API using PHP, and use AJAX to modify the dropdown. Search the following in google "PHP API" and "AJAX Call On PHP".

Is there a possibility of a solution in a select option which uses JavaScript and PHP together?

I have run into a problem between two different coding languages, JavaScript and PHP. Now as you can see from the picture below in the webpage i have a select list and a add list .
In the select list I am querying the database to get the values out like in the code below shown:
<select name="opt_lable" id="select";>
<?php foreach ($distinctResult as $post) {?>
<option value="<?php echo $post['label'];?>"><?php echo $post['label'];?></option>
<?php };?>
</select>
Now for the input form that I have Add list, I add the value from the database and this value appears into the select option and also when I add the value I am creating a totally new file as shown below in the code:
<?php
include "conn.php";
if(isset($_POST['AddList'])){
$addLabelList=mysqli_real_escape_string($conn,$_POST['add_list_for_label']);
if(empty($addLabelList)){
header("LOCATION:../admin-panel.php");
}else{
$list=fopen("../".$addLabelList.".php","w");
$OpenExtPhp="<?php \n";
$CloseExtPhp="?>\n";
$Header="include 'header.php' ;\n";
$SidePanel="include 'side-Panel.php' ; \n";
$PostWindow="include 'post-Window.php';\n";
$CreatList="include 'create-list.php';\n";
$Footer="include 'footer.php';\n";
fwrite($list,$OpenExtPhp);
fwrite($list,$Header);
fwrite($list,$SidePanel);
fwrite($list,$PostWindow);
fwrite($list,$CreatList);
fwrite($list,$Footer);
fwrite($list,$CloseExtPhp);
$query="INSERT INTO posts(label) VALUES('$addLabelList')";
mysqli_query($conn,$query);
header("LOCATION:../admin-panel.php");
}
}elseif (isset($_POST['CancelList'])) {
header("LOCATION:../admin-panel.php");
};
the last thing that I do is link the values of the option list to that individual value that I created during submission of the value - as shown in the last code below which is a javascript file :
var sel=document.getElementById("select");
sel.onchange=function(value){
if(this.value=="home"){
var w=window.location.href="admin-Panel.php";
}else if(this.value=="Netherlands"){
window.location.href="Netherlands.php";
};
}
Am I able to link each value that I create with the form addList to the page which will be created during that procces of submission? Thnx to anyone who can help me out with this
If I understand your question, you want to send the value of the selected item to the php file that processes the POST data. If that is the case, you have two options
You can set a hidden form input (input type="hidden" value="") with the selected item and get the value in the file that processes the POST data
You can use $.ajax({}) to post the form data. That would allow you add the select data as POST data to your form

Need help creating the php and/or javascript using a hyperlink to change the language on a webpage

I have previously used a dropdown selection box with options using a post method in order to change the language in a webpage that is saved on a separate file. I am now trying to create something similar but need help. Now I am trying to make the webpage for only 2 languages and when viewing the webpage on one language the option to switch to the other will appear. Essentially giving the viewer the option to change the session language to either English or Spanish only with showing the opposite language as a hyperlink on all pages. My language file is essentially as follows:
<?php
$lang = array(
'EN' => array(
'ABOUT' => 'About',
'HOME' => 'Home'
),
'SP' => array(
'ABOUT' => 'Acerca',
'HOME' => 'Casa'
)
)
?>
This PHP code that I have shown here is more extensive but this is how I set things up writing these lines of code on another file to be able to change the language. On my main page I have a short section of code before the html document is declared and that is as follows:
<?php
require("lang.php");
session_start();
$_SESSION['LANG'] = "EN";
if(#$_POST['lang-chooser']){
$_SESSION['LANG'] = $_POST['lang-chooser'];
}
?>
I am trying to make the portion of the page where I have the hyperlink to be located in the header or body of the document. The code I have currently for the option to choose a language is as follows:
<form method="post" action="" id="lang-form">
<select id="lang-chooser" class="lang-chooser" name="lang-chooser" onchange="window.lang(this);">
<option value="EN"<?php if($_SESSION['LANG'] == "EN") {?> selected="selected"<?php }?>>English</option>
<option value="SP"<?php if($_SESSION['LANG'] == "SP") {?> selected="selected"<?php }?>>Spanish</option>
</select>
</form>
Underneath my footer but still in the body portion I also have a little amount of script as follows:
<script type="text/javascript">
function lang(element){
var lang_name = element.value;
var e_form = document.getElementById("lang-form");
e_form.submit();
console.log(element);
}
window.lang = lang;
</script>
With all of these portions of code I was successfully able to change the language using the dropdown selection box while staying on the current page. The code I would use to have changeable text would be as follows:
<?php echo ($lang[$_SESSION['LANG']]['ABOUT']); ?>
Now I wish to have the option to change the session language on any page again but without the dropdown selection box. I wish to have it so that when the page is in English which it automatically should be when accessing the site there will be a hyperlink named Espanol which allows the viewer to change to Spanish and once the page is in Spanish the hyperlink will change to saying English which allows the viewer to change to English. From looking online I am lead to believe that I will still need the intro PHP code and javascript but will no longer need the "form" or "method" portion to change the session language. I believe all that I need now in replacement of the "form" and "posting-method" is as follows:
<?php echo($lang[$_SESSION['LANG']]['SPANISH']); ?>
I believe that my code is still lacking and this is why I still cant get it to work. Essentially I will need the hyperlink to change text according to the session and to also be used to change the session language from either Spanish or English. I am a little stumped here and would very much appreciate any kind of help. Thanks for taking the time to read this question.
You could replace your form with php if, else and get functions.
By using $_GET at the head of the page you can check if lang is set in the URL and set a session based on the result:
Edit
This section will replace everything after session_start(); in the second piece of php code you placed in the question.
<?php
if(!isset($_SESSION['LANG'])){
$_SESSION['LANG']='EN';
header('location: '.$_SERVER["REQUEST_URI"]);
}
if(isset($_GET['lang'])){
if($_GET['lang']=='sp'){
$_SESSION['LANG']='SP';
}else{
$_SESSION['LANG']='EN';
}
}
After you can check if the session is set then call out a href link to whichever language you want to change to.
This section will replace the html form
<?php
if(isset($_SESSION['LANG'])){
if($_SESSION['LANG']=='EN'){
echo 'Espanol';
}else{
echo 'English';
}
}else{
echo 'Espanol';
}
You don't need java to achieve this.
EDIT
If you want the URL not to show the ?lang= you can include another session and a header in the first section such as:
<?php
if(isset($_GET['lang'])){
if($_GET['lang']=='sp'){
$_SESSION['LANG']='SP';
header('location: '.$_SESSION['URI']);
}else{
$_SESSION['LANG']='EN';
header('location: '.$_SESSION['URI']);
}
}else{
$_SESSION['URI']=$_SERVER["REQUEST_URI"];
}
This will instantly redirect the user back to the page they were on, they shouldn't notice the refresh.
<?php
$allowed_langs = array('EN' => 'English', 'SP' => 'Espanol');
$site_lang = isset($_SESSION['LANG'])?$_SESSION['LANG']:'EN';
//Here you can set language according to link
if(isset($_GET['lang'] && in_array($_GET['lang'], $allowed_langs)){
$_SESSION['LANG'] = $_GET['lang'];
$site_lang = $_GET['lang'];
//Then you can refresh the page if you want to load new file or start
// including your language file after this language set.
}
//include your lang file
include_once( 'langs/' . $site_lang . '/text.php' );
?>
<ul>
<?php
foreach($allowed_langs as $langshort => $langlong){
$new_query_string = build_query_string($param, 'lang', $langshort);
$new_link = strtok($_SERVER["REQUEST_URI"],'?') . "?" . $new_query_string;
$class = ($_SESSION['LANG']==$langshort)?'selected':'';
?>
<li class="<?= $class ?>"><?= $langlong ?></li>
<?php } ?>
</ul>

Populating second dropdown on the same page

I am trying to populate a second dropdown based on first on the same page without having to call any external PHP script. I have been testing ajax but it is not working, it has to call another PHP script externally.
I have states, so when a state is clicked it populates the second dropdown with the locality for that state from the db the first dropdown is working properly but the second isn't working. This is my code, been trying ajax nothing works.
I want to echo the value from the db on the same page without calling any external PHP script. How can I pass the first dropdown value to the second dropdown PHP code below for query to the db? Not calling another PHP file externally, all on the same page?
//first dropdown//
<select name="state" class="select" >
<option selected>State</option>
<?php
$u = "SELECT * FROM state_id";
$sql = mysqli_query($con, $u);
while ( $row = mysqli_fetch_assoc($sql))
{
echo '<option>'.$row['name'].'</option>';
}
?>
</select>
</div>
</div>
<div class="col-md-2">
<div class="aa-single-advance-search">
<!-- second dropdown on the same page -->
<select name="locality" class="select2">
<option selected>Location</option>
<?php
//local area is the table i am getting localities based on state value in the first select menu//
$u = "SELECT name FROM local_area WHERE state_id='$id'";
$sql = mysqli_query($con, $u);
while ( $row = mysqli_fetch_assoc($sql))
{
echo '<option>'.$row['name'].'</option>';
}
?>
</select>
A common mistake (perhaps not one you are encountering, but fwiw) is to think the PHP code can somehow run the AJAX. Not true. Once the page is rendered, PHP cannot run. That's where javascript comes in, and that's why AJAX is started in js/jQuery.
Note that jQuery is a library that you reference/load on your page. Not only is it 30% less typing (that fact alone is a good enough reason to use it), but it is also automatically cross-browser. More importantly, jQuery makes AJAX easy.
Study this (working) example. Perhaps even reproduce the example on your server and monkey around with it a bit. Turn the example into your own solution.
Populate dropdown B based on selection in dropdown A
I did little work and it worked but what confused me was the relationship between the external php script and the second dropdown.

PHP, Javascript Help Required

I am new to this forum. I have been developing a interface and have got stuck with PHP and Javascript.
My Site has 3 Buttons
<button id="ProjectSource" class="testbutton" onClick="AddNewProject(this.id);">Project Source</button>
<button id="SelfCons" class="testbutton" onclick="AddNewProject(this.id)">Self Cons</button>
<button id="Currency" class="testbutton" onclick="AddNewProject(this.id)">Currency</button>
These buttons are sent to a Javascript function on the same page which will store the button ID in a variable, which is later used in another PHP.
Now I have an Select Box in the same page and I get the data from the database using PHP.
<select size="10" id="Database" onClick="ClearAdd()" >
<?php
while($row = mysql_fetch_assoc($get))
{
?>
<option value = "<?php echo($row['ProjectSource'])?>" >
<?php echo($row['ProjectSource']) ?>
</option>
<?php
}
?>
</select>
My First Problem is
If you see I am currently using $row['ProjectSource']), But what I need is the ID of the buttons which corresponds to the field name in the database.
My Second Problem is
The Select functions loads when the page loads, I want that to refresh when I click on any buttons.
Thanks in Advance for your help!
use mysql fetch query
For example:
while ($row = mysql_fetch_assoc($query)){
$id = $row['id'];
}
For your second Problem you should implement ajax. Either using javascript or jquery.
Regarding first problem it is not clear What are the field names and how button Id is implemented? It would be better if you post some code
Can you implement some kind of mapping of your fieldName to your buttonId using associative array? like array("fieldName1"=>"id1",....)

Categories

Resources