jquery php get two different arrays of data in success function - php

I have a drop down menu for 'Countries'. Onchange of the dropdown ,i want to change the values of two other drop down menus.
While i do it for a single dropdown,it works just fine.But i seem to get confused when it comes to changing the data for both the dropdown menus.
This is what i am doing.
$.post(
base_url+'hostel_admin/functions/functions.php',
{country_code:country_code}
).done(function(data){
$("#continent").html(data.continents);
$("#continent").html(data.cities);
});
In functions.php
if($_SERVER['REQUEST_METHOD']=='POST' && (isset($_POST['country_code'])))
{
change_continents($continent_id);
change_cities($country_code);
}
function change_continents($code)
{
$sql = "select id as Code,name as Name from hostel_continent";
$result = mysql_query($sql);
$output['continents'] = "<option value='0'>Select One</option>";
while($row = mysql_fetch_assoc($result))
{
$data = $row['Name'];
$val = $row['Code'];
if($val==$code)
{
$output .= "<option value='$val' selected='selected'>$data</option>";
}
else{
$output .= "<option value='$val'>$data</option>";
}
}
echo $output;
}
function change_cities($country_code)
{
$sql = "select ID,Name,District from hostel_city where CountryCode='$country_code'";
$result = mysql_query($sql);
$output['cities'] = "<option value='0'>Select One</option>";
while($row = mysql_fetch_assoc($result))
{
$data = $row['Name'];
$val = $row['District'];
$city_id = $row['ID'];
$output .= "<option value='$city_id' selected='selected'>$data.' / '.$val</option>";
}
echo $output;
}
I am able to do it for a single dropdown,can someone tell where exactly and what is going wrong?.
Thanks in advance.

First thing is first, separate your data. You are using PHP to echo html, that is the normal use case, but here I think json might help more.
So first to something like this on the php side:
$ajaxResponse = [];
Then for each of the data you can do this:
#in the change_continents function
$ajaxResponse["continents"][] = $row;
........
#in the change_cities
$ajaxResponse["cities"][] = $row;
Then do the output after each call
echo json_encode($ajaxResponse);
On the javascript side, you will now need to actually create the the html you are going to push to the objects.
First do not do $('').html() twice on the same selector, the second one will overwrite the first one. You will need tow selectors.
Then you will need to do something like this:
$.post(
base_url+'hostel_admin/functions/functions.php',
{country_code:country_code}
).done(function(data){
var continents = '<select {select options}>';
if(typeof(data)=='string')data=JSON.decode(data);
for( key in data.continents)
continents+='"<option value="'+data.continents.Code+'" selected='selected'>"'+data.continents.Name+'" </option>"; '
continents+="</select>"
$("#continent").html(continents);
var countries = '<select {select options}>';
for( key in data.countries)
continents+='"<option value="'+data.countries[key].Code+'" selected='selected'>"'+data.countries[key].Name+'" </option>"; '
continents+="</select>
$("#countries").html(data.cities);
});
The code above might not be fully functional, but should lead you in the right direction.
The best way would be to make the functions on the php side return the data you need, and then format it in another function, so if you need json you can output json, if you need html you can output html.
Second, on the javascript side, you could use "underscore" and it's templateing engine to do the hard work for you.
Hope this helps.

Related

echo selected in html select option if value exists in array

I have been searching for days and trying everything, but i can't seem to get this working.
Question :
I have a user profile where a user can select some hobbies from a dropdown menu. This user can also edit his profile. On this edit page I would like to display a dropdown where the previously selected hobbies are selected and the rest of the available hobbies option are displayed for selection.
This is the basic code I have so far ( minus all the code that didnt work ). I hope someone can help he out.
$existing_hobby_values = array("Football", "Tennis", "Volleyball");
$sql = "select hobby from hobbies ORDER BY id ASC";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
echo "<select multiple>";
while($row = mysqli_fetch_assoc($result)) {
$interesse = $row['hobby'];
//if{$interesse = in_array($existing_hobby_values) echo "selected" inside option }
echo "<option value='$interesse'>$interesse</option>";
}
echo "</select>";
}
By the way...I know I should start using PDO instead of Mysqli, but because this project has a deadline I have to finish this before starting with learning PDO.
You can try something like
while ($row = mysqli_fetch_assoc($result)) {
$interesse = $row['hobby'];
echo '<option ';
if (in_array($interesse, $existing_hobby_values)) {
echo 'selected ';
}
echo "value='$interesse'>$interesse</option>";
}
And you should definitely do something about your tabulation.
change
echo "<option value='$interesse'>$interesse</option>";
to
echo "<option value='$interesse' ".( in_array($intresse,$existing_hobby_values) ? "SELECTED ": "" ) .">$interesse</option>";
though to be fair, #rept1d's answer should work just fine as well.

Get the selected value of a <select> tag in php

Is there a way to find out what is the value of the <option> in a <select> tag?
I have a form that contains a tag, with several options. Then, I want to insert the selected value on the database.
Is this doable with PHP? Or do i need JS/Jquery?
EDIT: this is what i have tried:
This creates the variable and stores the value of the option.
$query=mysql_query("Select cargo from utilizadores where nome<>'admin'");
echo '<select name="icargo[]">';
while ($row = mysql_fetch_array($query, MYSQL_ASSOC))
{
foreach ($row as $cargo){
echo '<option value="$cargo" name="icargo[]">'.$cargo.'</option>';
}
}
echo '</select>';
I send the variable this way, and then i try to receive it with a foreach:
$countcargo = 0;
foreach ($_POST["icargo"] as $cargoo){
$cargoarray[$countcargo] = $cargo;
$countcargo++;
}

PHP echo out data into HTML drop drop down menu

I have a HTML etc.. tags now what I want to achieve is upon a selection of ie. i want to load the related info from database to in a new tag with as many tags.
I am using PHP to do achieve this now at this point if for example i choose option1 then the query behind it retrieves relevant information and stores it in a array, and if I select option2 exactly the same is done.
The next step I made is to create a loop to display the results from array() but I am struggling to come up with the right solution to echo retrieved data into etc. As its not my strongest side.
Hope you understand what I am trying to achieve the below code will clear thing out.
HTML:
<select id="workshop" name="workshop" onchange="return test();">
<option value="">Please select a Workshop</option>
<option value="Forex">Forex</option>
<option value="BinaryOptions">Binary Options</option>
</select>
PHP:
$form = Array();
if(isset($_POST['workshop'])){
$form['workshop'] = $_POST['workshop'];
$form['forex'] = $_POST['Forex'];
$form['binary'] = $_POST['Binary'];
//Retrieve Binary Workshops
if($form['workshop'] == 'Forex'){
$sql2 = "SELECT id, course, location FROM courses WHERE course LIKE '%Forex%' OR course LIKE '&forex%'";
$query2 = mysqli_query($link, $sql2);
while($result2 = mysqli_fetch_assoc($query2)){
//The problem I am having is here :/
echo "<select id='Forex' name='Forex' style='display: none'>";
echo "<option value='oko'>.$result[1].</option>";
echo "</select>";
print_r($result2);echo '</br>';
}
}else{
$sql = "SELECT id, course, location FROM courses WHERE course LIKE '%Binary%' OR course LIKE '%binary%'";
$query = mysqli_query($link, $sql);
while($result = mysqli_fetch_assoc($query)){
print_r($result);echo '</br>';
}
}
}
Try this code:
$query2 = mysqli_query($link, $sql2);
echo "<select id='Forex' name='Forex' style='display: none'>";
while($result2 = mysqli_fetch_assoc($query2)){
echo "<option value='oko'>{$result['course']}</option>";
}
echo "</select>";
echo '</br>';
From the top in your php:
// not seeing uses of the $form I removed it from my answer
if(isset($_POST['workshop'])){
$workshop = $_POST['workshop'];
$lowerWorkshop = strtolower($workshop);
// neither of $_POST['Forex'] nor $_POST['Binary'] are defined in your POST. you could as well remove those lines?
//Retrieve Binary Workshops HERE we can define the sql in a single line:
$sql = "SELECT id, course, location FROM courses WHERE course LIKE '%$workshop%' OR course LIKE '&$lowerWorkhop%'";
$query = mysqli_query($link, $sql); // here no need to have two results
// Here lets build our select first, we'll echo it later.
$select = '<select id="$workshop" name="$workshop" style="display: none">';
while($result = mysqli_fetch_assoc($query)){
$select.= '<option value="' . $result['id'] . '">' . $result['course'] . '</option>';
// here I replaced the outer containing quotes around the html by single quotes.
// since you use _fetch_assoc the resulting array will have stroing keys.
// to retrieve them, you have to use quotes around the key, hence the change
}
$select.= '</select>';
}
echo $vSelect;
this will output a select containing one option for each row returned by either of the queries. by the way this particular exemple won't echo anything on screen (since your select display's set to none). but see the source code to retrieve the exemple.

Using a mysql data base to populate a second drop down box automatically based off of first drop down box

I need to have a selection box display options that are based off of the selection from the drop down box right above it. Once the user selects the Car Make, then I want the Car Models of the car make to be options to be selected.
I have been able to get the car makes options to be displayed from my mysql data base, but now I need the car models of only that make. My data base has two collumns, one for the Make and one for the Model.
The top section of PHP is the way i get the make, and the bottom is my attempt to get the model, but it displays hundreds of models, instead of just the few I want. I heard that AJAX or javascript can automatically upload the results, which would be nice. Any help is great. thanks!
</div>
<?php
mysql_connect('localhost', '*****', '******');
mysql_select_db('*************');
$sql = "SELECT Make FROM CarMakes";
$result = mysql_query($sql);
echo "<select name='carmake3'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['Make'] . "'>" . $row['Make'] . "</option>";
}
echo "</select>";
?>
<?php
mysql_connect('localhost', '******', '**********');
mysql_select_db('*************');
$sql = "SELECT Model FROM myTable";
$result = mysql_query($sql);
echo "<select class='modelbox' name='carmodel3'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['Model'] . "'>" . $row['Model'] . "</option>";
}
echo "</select>";
?>
<input type="text" maxlength="4" name="car3year" placeholder="year" class="WriteInBox"/>
<input type="text" maxlength="6" name="car3miles" placeholder="miles" class="WriteInBox"/>
</div>
$sql = "SELECT Model FROM myTable";
This clearly is giving you the results you are asking for. It will select all models.
Your sql should look like
$sql = "SELECT Model FROM myTable WHERE Make='Make'";
The where limits you to retrieve only models associated with the specific Make you have selected.
To do it with AJAX, are you using jQuery? Straight JavaScript with an Ajax call? Please provide more information for answering that part of your question.
This probably isn't the best way to do this, but when I have had to do things like this before, I usually use the php to populate some javascript variables in my header and then use javascript to create the selects. Also, I'm assuming that there is something in your database that maps certain models to certain makes of vehicles.
<script>
var makes = new Array();
var models = new Array();
<?php
$sql = "SELECT Make FROM CarMakes";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
?>
makes[] = <?php echo json_encode($row['Make']); ?>;
<?php
}
$sql = "SELECT Make FROM CarMakes";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
?>
models[] = <?php echo json_encode($row['Model']); ?>;
<?php
}
?>
</script>
From here, you can create the selects and populate the options of the first one with the elements of the makes array. Then add an onChange event to the first select to populate the second select.
EDIT For select creation:
<select id="make-select" onChange="updateModels()">
</select>
<select id="model-select">
</select>
<script>
$(function() {
$.each(makes, function (index, value) {
$(#make-select).append($('<option>') {
value: value,
text: value
});
});
}
</script>
Then just create a function that called updateModels that will update model-select based on the selected value of make-select. Again, you'll need somehting that associates models with makes in your database, and then you might have to make the makes variable an object instead of just an array.
var models = new Object()
<?php
$sql = "SELECT Model-Make, Model FROM CarMakes";
...
models.make = <?php echo json_encode($row['Model-Make']); ?>;
models.model = <?php echo json_encode($row['Model']); ?>;
...
?>

PHP dropdown populated by database to be use javascript

I have this php code that get items from the database and i have to use this drop-down in my JavaScript code to duplicate the same drop-down when a button is clicked
function dup(){
}
<?php
include('view/connect.php');
$sql="SELECT ss_code FROM ss WHERE sn_id = 1";
$result =mysql_query($sql);
$dropdown = "<select name='users'>";
while($row = mysql_fetch_assoc($result)) {
$b = $row['ss_code'];
$dropdown .= "\r\n<option value='{$b}'>{$b}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
?>
Put all your items in an array and then set a JavaScript variable to the value returned by encoding it as JSON.
var iarray = <?php echo json_encode($items); ?>;
Then iterate over the resultant array and create the pulldown from that.
What do you mean same drop down?If you want same dropdown without any change on a button click you can use jQuery .clone().

Categories