PHP, Javascript Help Required - javascript

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",....)

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

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.

JQuery populating select box but after post options disappear

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']];

asynchronous iframe using jquery

So I'm creating a code portfolio based upon what's in my svn repo.
I'm currently set up like this:
PHP loops through my JSON and creates these little menus for each file in each project. Here's some (very poorly structured) code showing how I generate each of these:
<form action = "" method = 'post'><select name = "s2" id = "s2"> <?php
foreach($proj2->item_vers as $ver)
{
?>
<option value = <?php
$base_str = (string)$ver->revision;
$full_str = "\"".$base_str."\"";
echo($full_str); ?> > <?php
echo($base_str); ?> </option>
<?php
} ?> </select><input type = 'submit'/></form>
<a href = <?php
if (isset($_POST['2']))
{
$rev2 = $_POST['s2'];
}
else
$rev2 = "";
$full_url = "https://myrepo".
$proj2->name."?p=".$rev2;
$ret_url = "\"".$full_url."\"";
echo($ret_url); ?> > Code </a></td>
So I have a form, select, option. The select will post the selected version from the drop down. Then I have a hyperlink which forms the correct url based upon the posted version number. This hyperlink will need to be replaced with an iframe. For the sake of simplicity, lets say that each project has its own iframe which is updated with appropriate project file any time you click one of the submit buttons.
So like this:
I'm looking for the simplest way to set this up to work asynchronously.
My thoughts:
I've already set up an asynchronous comment system using jQuery. The difference was that I only had three little inputs and a button to submit the comment. This just seems like it will be much more complicated as the code I posted above will loop through about 100 times. I cant just hard code a different id to every single submit button and write 100 different .js scripts to operate when each individual button is clicked.
OK, so im going to simplify your form generation code to make this clearer. I am including the outer loop you dont show:
<div id="forms-holder">
<!--this is the outer loop-->
<?php foreach ($projects as $project):?>
<!-- remove any ids in the loop, they can not be duplicated-->
<form action="" class="projectform">
<!-- add name to data attribute for easy retrieval by js-->
<select name="s2" data-projectname="<?php echo $project->name;?>">
<?php foreach ($project->item_vers as $ver):?>
<option value="<?php echo'"'. $ver->revision .'"';?>"><?php echo $ver->revision;?></option>
<?php endforeach;?>
</select>
<input type = 'submit'/>
<form>
<?php endforeach;?>
</div>
<iframe src="" frameborder="0" id="myiframe"></iframe>
<script type="text/javascript">
$(function(){
//when any form is submitted
$('.projectform').submit(function(ev){
ev.preventDefault();
//grab revision and project name
var revision = $(this).find('select').val();
var projname = $(this).find('select').attr('data-projectname');
//generate the url
var iframeurl = "https://myrepo"+projname+"?p="+revision;
//set the iframes url
$('#myiframe').attr('src', iframeurl);
})
});
</script>

Categories

Resources