Jquery OnChange fires but no data returned - php

I have posted this a few times looking for some help, I cant seem to work out why i dont get any data from my dynamic drop down but i do from the 2 static fields. I did get some answers but mainly saying that i need to sort out the security, which i hope to learn next before anything is live online, everything looks good in Firebug including the trace for the http request, i think its a problem with the query i am trying to run, i will post this again and see if anyone can help me out before i address the security flaws.
Thanks alot for helping me out.
first is html, the subcategory is the problem, all items are stored in a javascript array and works fine, just not the query
<select name="Category" id="Category"
onchange="javascript: dropdownlist(this.options[this.selectedIndex].value);">
<option value="">Select Category</option>
<select name="subcategory" id="subcategory">
<option value="">Select Sub-Category</option>
</select>
<script>
$(function() {
$('#subcategory').change(function() {
$('#subcategory').load('results.php', {value: $(this).val()});
});
});
</script>
$category=$_POST['Category'];
$subcategory=$_POST['Subcategory'];
$destination=$_POST['Destination'];
$result = mysql_query("SELECT * FROM travel WHERE Category='$category'
AND Subcategory='$subcategory' AND Destination='$destination'")
or die(mysql_error());
$row = mysql_fetch_assoc( $result ) ;
echo to table (not posted as is working ok)

Where to even start? Your field name is 'subcategory'. You pass 'value' to results.php and you're attempting to retrieve 'Subcategory' form the $_POST array. You need to line all these names up.
I'm not sure whether the PHP there is the code for results.php or for whatever script the form is posted to, or are they the same? Regardless, whatever results.php needs, you need to include in the data you pass to load. For example, since you currently use 'value', you'd retrieve that via $_POST['value'], not $_POST['Subcategory'].

You only pass to php data from "#subcategory" form, not from "#Category", and with another id than you use in php code. And and you don't have a code for "destination", so I don't know where it should be taken from. Also it's better to put your code in $(document).ready when using jquery. It should be like that:
$(document).ready(function() {
$('#subcategory').change(function() {
$('#subcategory').load('results.php', {Subcategory: $(this).val(), Category: $("#Category").val() });
});
});

Related

drop down changes from other drop down with calculation. Jscript / Ajax?

I have a Jscript Query.
I have done a bit of reading and found out that AJAX is just a side server for a lfash script that can be used on Linux with php. (please correct me if I have interperated that wrong)
I have no knowledge on how scripts work so this is new, I have tried a couple of different tries but no luck.
I have one drop down box (Box1) (populated from Database)
I have another box (Box2) for a calculation to insert into my database for other uses on ohter parts of hte site.
I need the Box2 to change the figure when someone changes Box1 dropdown before hitting the submit button.
I think because I have the calcualtion this is getting me stuck... Code is as below... Can someone please help me figure out (I think I need some form of Script to do this.) the answer...
Box1
<td><p>selection 1</p>
<select id="t1_type" name="t1_type">
<?php $result = mysql_query("SELECT * FROM `t2` ORDER BY t2_value");
while($valuerow = mysql_fetch_array($result)){
echo '<option value="'.$valuerow['t2_name'].'">'.$valuerow['t2_name'].'</option>'; } ?>
Box2
<input name="t1_value" id="t1_value" value="
<?php
$var1 = $row_value['t2_value'];
$var2 = $row_dropdown['t1_number'];
$total = round ($var2 * $var1);
echo "" . $total . "";
?>" />
I hope this is all the code you need, (Let me know if more required)
What it needs to do is show new calculation whenever someone changes the box1 option BEFORE the submit button is clicked, so it submits the correct calculation to the database for future use.
I think it would need pretty much "t2_value" from box2 to change when ever "t2_name changed from box1.
And once again the best link to learn about the solution. (Learnt about Joins now from my last question!! Almost a intermediate user. ;-) )
Edit :
I saw that your second box was a textbox I believe, if thats the problem then you should do something like this
<select id="t1_type" name="t1_type" onchange="change(this);">
<?php
$result = mysql_query("SELECT * FROM `t2` ORDER BY t2_value");
while($valuerow = mysql_fetch_array($result))
{
echo '<option value="'.$valuerow['t2_name'].'">'.$valuerow['t2_name'].'</option>';
}
?>
</select>
This defines your <select> box like you did in your question.
Add an onChange event into your first <select> and then create a function to handle to onChange event. An onChange event fires whenever the user changes the item in the <select> element.
Javascript :
( put this part of the code above the </head> )
<script language="javascript" type="text/javascript">
function change(element)
{
// do here whatever you want
// you can change the value of the <input> box with :
// document.getElementById(element.id).value = your_value
// If you want to see if this part works, then try adding this :
// alert("It works!");
// If you want to get the text of the item which has been selected in Box1 use :
// $("#t1_type option:selected").text();
}
</script>
Note: because PHP is server side, you can't update your Box2 dynamically without a page refresh, Javascript however is Client Side and CAN do this.
Note : the $("#t1_type option:selected").text(); code requires you to include the jQuery library into your script. Be sure to convert this variable to a float, int or double if you want to calculate with it, else the outcome will give NaN (Not a Number)
Tutorial on including jQuery Libary :
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
If you're new to JavaScript, you should try some tutorials. The ones at w3Schools.com helpt me alot, but some people say they're not always correct, but anyhow, read some stuff about Javascript to actually know what you are doing, instead of copypasting code :)

Unsure how to approach json php mysql integration

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.

Update database when a selection is made in a drop down menu

I have no idea where to begin, so if there is already an answer out there to a question like mine I would appreciate it! Basically the question says it all, Here is what I would like:
There is a drop down menu, simple drop down menu, nothing fancy. When a selection is made in that drop down menu, a php mysql query is ran where the database will be updated with that value. I have all the pieces, all I need is the code that would be able to kick it all off.
For instance when you hit submit on a form you would typically type out:
if (isset($_POST['submit']))
{
//grab information and insert into db
}
How would I do this for a drop down selection without having to click the submit button.
As has been said in the comments, you listen to the onchange event of the selectbox and either submit a form or use AJAX. This is not my point.
From a usability POV I recommend you reevaluate this proposition, if it really leads to a database update: Ever used the mouse wheel to scroll, while accidently having the focus on a selectbox? Jackpot! You just changed your DB settings without being aware of it.
So using onchange on a selectbox to kick off something, that is immediately visible is IMHO a good thing - you'll know, when you triggered it. Changing a DB setting with no feedback other than the select box changing value is IMHO a bad thing. Or an accident waiting to happen.
you should be looking for something like this
<form id="testform">
<select id="yourselect" name="yourselect" onChange="updateDb()">
<option value="somevalue">Please select</option>
<option value="somevalue1">Something</option>
</select>
</form>
you Javascript function will look like this
function updateDb() {
// I am using jquery for ajax
$.post("yourserverhandle.php", $("#testform").serialize());
}
and this is how your "yourserverhandle.php" looks like
<?php
$query = "update yourtable set something='".mysql_escape_string($_POST["yourselect"])."' where id='something'";
.... mysql connect, execute
?>
$("#DDL_ID").change(function(){
$.ajax({
url:'/some.php',
type:'POST',
data:{submit:$(this).val()},
success:function(data){
//do something here if the server return anything
},
error:function(){
console.log("something bad happened");
}
});
});
on the php side
if (isset($_POST['submit']))
{
//grab information and insert into db
}
P.S. always sanitize the input see mysql_real_escape_string

javascript and PHP variable passing

I have two select box and the second select box value is dependent on the first select box. So basically what I am trying to do is that after a user makes a selection on the first select box, it will then store this value of the first select box as a variable. Then it will query my database to populate the second select box, based on the first selected value. Question is, how do I pass in the var I have in the first select box to PHP? I've read other post and people said it's impossible, but if it is then how do people do this? AJAX?
If I understand correctly, then yes, using AJAX is really your only choice.
Indeed, you can, with AJAX, call something like 'getSelectionData.php?data=' + select1.value, which returns a JSON array of data based on the selection in the first select box. You then parse the data and enter it into the second select box.
Add a onchange event listener to the first select box:
document.getElementById("select1").addEventListener("change", function(ev){
var yourstoredvariable = this.value;
someFunctionThatCallsAjax(yourstoredvariable);
}, true);
I assume that you have a Country/City dropdowns, You can do it in two ways, the good AJAX way and the bad way (refresh page on change), I'm gonna describe the good way in jQuery, or at least what I see it good.
this is the client-side (i.e. client) code:
<select id="country">
<option value="1">Canada</option>
<option value="2">UK</option>
</select>
<select id="city" disabled="disabled"></select>
<script type="text/javascript">
$('#country').change(function(){
$('#city').load('/ajax-city.php', {id: $(this).val()});
});
</script>
This is the ajax-city.php code (server):
<?php
$countryId = $_REQUEST['id'];
$cities = array(); // Get it from db, using mysql_query or anything you want to use
foreach($cities as $city) {
echo "<option id=\"{$city['id']}\">{$city['name']}</option>";
}
PS. you would need to include jQuery in your html code, and of course put the two files in the same directory (or change the $.load path).
This particular code is not tested, I've just written it. But it usually works fine to me this way.
You will have an onchange event on the first <select> that will query the server using Ajax with the value of the selected <option> that will return the <option> elements with which to populate the 2nd <select> element.
Question is, how do I pass in the var I have in the first select box to PHP?
I see no problem here.
Just usual, an ordinary html form using GET method.
What's so big about it?
If I see correct you're using Jquery. So you can do this like this:
$('#idOfSelectBox1').change(function(){
jQuery.ajax({
type: "GET",
url:"yourdomain.com/script.php",
data:"selectBox:'"+$('#idOfSelectBox1').val()+"'",
success:function(result){
//do smth with the returned data
}
});
});
in the script.php do your magic and echo what you want to pass back to js

How to generate dynamic form using JavaScript/JQuery?

Suppose a form.php file, and there is "add" button, once it's clicked, a drop down list will show, to let you choose which type of input type you want. For example:
<select name="Type">
<option value="Text">Text</option>
<option value="MultipleChoice">MultipleChoice</option>
<option value="Checkbox">Checkbox</option>
</select>
My question is, I don't know how to implement the function that, once the type is chosen, suppose checkbox, then a checkbox will shown, and could let you input the label of each checkbox, you can do this one by one.
Also I want to make this process could happen iteratively. I'm not sure if I explain clearly, it's a little bit like the google form function. Any ideas? If providing some codes would be better. Thanks!
Here is plain vanilla old school HTML/JS
<select name="Type" onchange="showformelement(this.value)">
<option value="text">Text</option>
<option value="MultipleChoice">MultipleChoice</option>
<option value="Checkbox">Checkbox</option>
</select>
<script>
function showformelement(whichelement){
//use whichelement to embedd element in DOM
}
</script>
If you can use jQuery or similar toolkit it may be a much simpler job
I know what are you looking for, just let you know that it isn't a simple script, it will have way too many functions and will be little hard to build.
Just to start, if you search on the web for PHP and jQuery based form builders and similar other things, you will find many ready to use scripts. Well, if you don't want to search for one, the principle logic will look like following:
PS: I will explain how to develop using jQuery.
<select id="options">
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
</select>
<script>
$(document).ready(function(){
$('#options').change(function(){
var optSelected = $('#options option:selected').val()
if(optSelected == 1){
// Shows up and div with Checkboex for edit
}
if(optSelected == 2){
// Shows up and div with Combobox for edit
}
if(optSelected == 3){
// Shows up and div with Textbox for edit
}
})
})
</script>
After doing that, you will need to build the options of each type...
There is too much work... look, I didn't write here your script, I just explained you how to build...
This is a huge system...you will need to know a bit of JavaScript to make one of these...
Even simpler, without needing to do any casing or conditioning, (uses jQuery).
Example: http://jsfiddle.net/SMAfA/
$(function() {
$("#type").change(function() {
type = $("option:selected", this).text();
$("#target").append("<input type="+type+">");
})
})

Categories