Unsure how to approach json php mysql integration - php

Let's say for sake of argument I have:
<select id="lvl1">
</select>
<div id="lvl2">
<select id="lvl2a">
<select id="lvl2b">
<input text id="lvl2c">
</div>
<select id="lvl3">
</select>
in file1.php and I would like to populate <select id="lvl3"> with the results of a query which would essentially look like:
SELECT * FROM lvl1 WHERE fld_a = lvl2a AND fld_b = lvl2b AND fld_c = lvl2c
The snag is lvl2 is created dynamically in an external js file (file2.js) based on what the user chooses in lvl1. From everything I have seen it would seem I want to use JSON for this but how would I call a PHP function located in file3.php from an external js file, file2.js and return those results as an array to populate lvl3 in file1.php?
Hopefully I have explained myself well enough. Thank you in advance.

You're going to need to refactor how your markup is generated in order to get this to work. Here's how I would do it:
lvl1 is spit out from your PHP script when the page loads.
After the user chooses something in lvl1, you fire off an AJAX request back to the server with what they chose.
The server responds with the markup for lvl2 which you inject into the page.
If needed, do the same after the user selects something from lvl2 to fetch the content of lvl3.
Finally, submitting the form would relay all the selected data to your form processing script, where you will validate the responses and do whatever else it is that you're doing.
That should be enough to get you going.

Related

Keeping some selected options after submitting form

Thanks in advance for any suggestions on the following:
I've created a php-page to add works from composers to CDs in a database. It's a combination of two forms and looks like this:
1st form:
Composer : [drop down list] : Select
Some blank space
2nd form:
Title : [drop down list]
Track number : [empty varchar field]
Work : [drop down list]
some other fields
Process button
After selecting a name in the first block (posting to $_SERVER["PHP_SELF"]) I stay on the same page, that name is shown in the blank space in between and the drop down lists are populated with only CD titles and works of the selected composer.
I can then select from the lists and enter other data in the other fields. Hitting the process button posts the data from the second block to another page which will eventually send everything to a table in a MySQL database.
After that I send myself back to the first page with header("Location: the_first_page.php")
So far so good, but upon returning I would like the composer, title and work to be preselected. Now I'm sent to a blank page and have to start from scratch. I think I've seen some solution involving testing $_POST['something'] against <option value> in a drop down list but I can't seem to make that work.
My question is: Is there a way to send $_POST['Title'] and $_POST['Work'] back to the first page somehow? Or is it better to split the two forms over seperate pages?
All help is welcome.
You could use sessions or the post data itself. For using the post data itself, the page where you send the request should be the same and include the script that will process it if there's some data like this:
if (!empty($_POST)) {
include "save.php";
}
// More code...
?>
<select name = "a">
<option <?php if ($_POST['a'] == "test") echo "selected"; ?> value = "test">
<option <?php if ($_POST['a'] == "testb") echo "selected"; ?> value = "testb">
</select>
Of course there are many more ways, but this is just a simple one to get you started. Things to know: you might want to change the variable $_POST and clean it up before using it. In this case it should be fine, but in <input type = "text" value = "<?= $_POST['b']; ?> name = "b">` you have a serious security issue.
For sanitizing the input, you want to sanitize it respect to what you expect. But also, as an EXTRA meassure, you normally want to strip everything that looks like a <script>, onclick ="", ' DROP TABLE users and similar. It's not an easy subject, so I recommend you reading on it, mainly on the XSS attacks which is relevant to showing the text back to the user. While it might seem too much work for this "simple case", it is useful in many more situations.
Use session variables and put conditions for them ... see [ $_SESSION ].

Is there anyway i could dynamically fetch the value of an <option> and pass it to PHP without using AJAX?

I have two <select> one is category and the second is subcategory.
here is the first <select> for category.
<select name="category" size="10">
<?php foreach($categories->fetch(array('table' => 'categories')) as $category) { ?>
<option value="<?php echo $category['id']; ?>"><?php echo $category['name']; ?></option>
<?php } ?>
</select>
now the second <select> i.e subcategory should be hidden initially and when a user click on category <select> based on the value it should populate the value in subcategory.
One way of doing this is via AJAX by passing categoryId as POST Request and getting HTML as response.
however i would like to know if there is any other alternative so that it automatically pass the categoryId value to PHP and unhide the second <select> here is the code of second <select>
<select name="subcategory" size="10">
<?php foreach($categories->fetch(array('table' => 'subCategories', 'categoryId' => $categoryId)) as $subCategory) { ?>
<option value="1"><?php echo $subCategory['name']; ?></option>
<?php } ?>
</select>
the only thing i need here is $categoryId to be populated dynamically. is there any way of doing this?
thank you..
No, there is no way to do what you are suggesting. PHP is only run on the server, so by the time the page is rendered on the client the PHP has already been run.
Your best bet would be what you already suggested, running some AJAX after the first select is changed, sending back the category ID to the server and retrieving what you need to build the second select.
Is there a reason why you don't want to do it this way?
Sukumar has probably suggested the best and most intuitive solution to make it appear as if the data is being loaded dynamically to the user.
The other alternative would be to submit the form when the select box is changed. Once the form has been submitted PHP would pick up the ID from the POST array and then re-populate the sub-category select box. This is often used as a fallback in case the user doesn't have JavaScript enabled.
Structurally, there are three choices to solve this problem:
Use an ajax call to fetch the required data when a user selection is made as jbruno has described.
Submit the whole page to the server, let your PHP see the newly selected option and fill in the newly desired data in a returned page. This will cause the page to refresh so is less ideal than option 1.
Pre-populate the page with all possible data in a javascript data structure so you can use Javascript to just look up the desired category ID in a local data structure, modify the page and never have to talk to the server in order to update the page.
In my opinion, option 3) is the most desirable if the data set required for local lookup is not too large (say under 100k) and it's not too expensive on the server to collect all that data for inclusion in the original page and if the data doesn't change real-time or having data as of the page load time is OK.
If option 3) isn't feasible for any reason, then option 1) is next best. Option 2) is not as good a user experience so it should only be the last resort if you really can't implement options 1) or 3).
You asked more specifically about option 3. I don't really yet understand what the whole data you need looks like. If you really only have four total data types residential_plot, residential_apartment, office_space and showroom, then you can just make those be four keys on an object and store their data that way:
var data = {
"residential_plot": 1,
"residential_apartment": 2,
"office_space": 3,
"showroom": 4
};
The 1, 2, 3 and 4 are just whatever data you want to store for that type. It can be numbers, strings, arrays of data, other objects of data, anything.
To access this, you would do like this:
var id = data.residential_plot;
or
var index = "residential_plot";
var id = data[index];
If you wanted to store the notion of categories and sub-categories, you would need an extra level of objects:
var data = {
"residential": {"residential_plot": 1, "residential_apartment": 2},
"commercial": {"office_space": 3, "showroom": 4}
};
Then, you would access it like this:
var id = data.residential.residential_plot;
or like this:
var category = "residential";
var catType = "residential_plot";
var id = data[category][catType];

How do you set the default value of a drop down list that is being called via AJAX from another page?

For my code, my drop down lists are initiated on the original page, via
<select name =country id=country
onchange=showRecords(this.value,'country','province')>"
This function is taking the value, equating it to country, then querying MySQL, and setting the results where id=province, and creating cascading dropdown lists. This is obviously via Ajax.
So, when $_REQUEST['province'] is set, then the Province dropdown list gets populated with all provinces from the country to which it belongs, etc.; i.e.;
<?if(isset($province)){
echo "<script>showRecords('".$country."','country','province');</script>";}?>
However, for the life of me, I cannot figure out how I can set the default value equal to $_REQUEST['province']. I cannot use the traditional way:
if (($selected) == ($value)) {
$options.= " selected";
}
Because it is querying the AJAX page with one piece of information at a time.
Any ideas would be greatly appreciated.
Your code doesn't seem to make a lot of sense. The particular thing that worries me is that you say ajax is loading one item at a time?
Perhaps something like this. A country select tag like...
<select onchange="showRecords(this)">
As well as creating the javascript function showRecords() which will be called when someone chooses an option in the select tag.
<script>
function showRecords(calling_element) {
// do AJAX call here using calling_element.options[calling_element.selectedIndex].value as the selected country. this.value does not work for select tags.
}
</script>
the PHP page that receives this AJAXed request would reply with a JSON object containing all of the province values, or a delimited list.
once the Javascript showRecords function receives the responce from the PHP page, it would add each of these options to the correct select tag. Once finished, it would set the default value to whichever option it wants by something like the following:
target_element.selectedIndex = {desired list index here};
I have a lot of assumptions to your questions,
first is, if bydefault you have the select province like this
<select id="province">
<option value=""></option>
<option value="California">California</option>
<option value="Washington">Washingthon</option>
</select>
then you can use this script to default select
document.getElementById("province").value="Washington";
but if bydefault you have the select province like this
<select id="province"></select>
then you can use this script to default select
document.getElementById("province").innerHTML='<option value="Wahsington">Washington</option>';
so it depend on your code and your need. maybe if you have another case the problem should be solved in another way.
cmmiiw :)

Clearing a selected item from a dropdown using PHP

I used the code below to remove a selected item from drop down, but when I remove one, the other item pops up. For example, if these are my options: "guns, cars, money", as I select and delete guns, cars and money remains. However, if I select cars and delete it, the deleted guns options pops up again. It is frustrating.
<?php
$opts = array("guns","knives","ammo");
$selected = array($_POST['selectMenu']);
$revisedOpts = array_diff($opts,$selected);
?>
<form method="post">
<select name='selectMenu'><?php
foreach($revisedOpts as $v) {
echo "<option>".$v."</option>";
}
?></select>
<input onclick="array_diff()" name="Collect" type="submit" value="submit" />
</form>
PHP only acts when the page is loaded, and you load the same code over and over. In order for previously deleted options to stay deleted, you need some kind of data persistence (like a database). Otherwise, you can use javascript to manipulate the select options on the client side browser. Here is a good discussion
If you must bind the action to onclick() and receive the event on the server side, then you will need to use an AJAX call. The onclick calls a separate PHP script which deletes the option and returns some kind of success message.
you want to have a look at some js code to do this. look at something like that http://www.mredkj.com/tutorials/tutorial_mixed2b.html
use jquery
jquery auto suggestion

Problem with keeping selected value in form after reloading page

I'm trying to populate a second dropdown in a dynamic way based on a previs selected dropdown.
However, I've managed to write get the page to reload when I choose anything in the dropdownbox but the chosen value isnt passed after reloading.
I have register_globals turned off (and prefer to) and i'm using the GET function to submit the form. However when I try setting values in the URL I cant get it to work.
Example: dropdown.php?area=1 still gives me a value in the dropdownbox with the default value.
What am I doing wrong? Running on a LAMP server. Apache 2.2, php 5.3.
Note: I found the php code here on the web wwich is suppose to help me pass the GET variable and select the option in the selectbox.
This is my code:
<html>
<head>
<SCRIPT language=JavaScript>
function reload(form)
{
var val=form.area.options[form.area.options.selectedIndex].value;
self.location='dropdown.php?area=' + val ;
}
</script>
</head>
</body>
<? #$area=$HTTP_GET_VARS['area']; ?>
<form action="" method="get">
<select name="area" id="area" onchange="reload(this.form)">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</form>
</body>
</html>
Also, if this could be done with POST (or equivalent function) it would be even better.
Regards.
I think you're not specifying anywhere which one of the options should be selected on page load. Depending on the value of $area, you should add something like
<option selected>1</option>
You could easily do this with a couple of lines of PHP when rendering the option nodes:
<? if $area == 1
print '<option selected>1</option>';
?>
etc.
Alternatively, you could just populate the second combo using client-side javascript eliminating the need for a page reload. If you need to do some sensitive server-side processing to calculate the value of the second combo, do it in a background AJAX call using jQuery (examples here). Postbacks for this kind of thing are kind of undesirable and old-fashioned these days.
Regarding the GET issue, if submitting the form has any side effects (eg. a change in state in the user's account, deleting something, creating a new entity) then it should definitely be a POST. Discussion here for example.

Categories