Advice on how to pass a JS onchange event to PHP - php

I have three drop down menus that query a MYSQL database depending on what a user selects. One of the menus is dynamic and but I can't get it to return data - the other two work fine. I think i need to catch the JS onchange event and then pass it to PHP in order to run the query but I am going in circles at present.
Below is what i am trying to do. All the values are stored in the <head> section - I have added my query and select html and on change event below.
$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 ) ;
<select name="subcategory" id="subcategory onchange="javascript:
dropdownlist(this.options[this.selectedIndex].value)">
<option value="">Select Sub-Category</option>

Try this jQuery:
$(document).ready(function() {
$('#myelement').change(function() {
$.ajax(
serverUrl,
{
data: { /* Put your input data in here as a hash */ }
type: 'POST',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
/* Put your response handler in here */
}
}
);
});
});
I'll leave you to do the server bit - you'll need json_encode(). Have fun!

Related

display data on selecting values from Dropdown without page refresh or button click using php mysql

I have a drop down on php form, I want to populate guest names in it, which has been done, now I want to load data from table on the basis of value from this drop down and without page refresh/ button submission. How do I do this? I want simple code that could achieve it in one page rather than doing it through multiple pages. The examples I have seen so far are too complicated and when I merge them in my code, they no longer work.
Here is the function which im using onchange of dropdown:
$("#guestname").change(function()
{
var id = $(this).find(":selected").val();
var dataString = 'action='+ id;
$.ajax
({
url: 'billing.php',
data: dataString,
cache: false,
success: function(r)
{
$("#display").html(r);
}
});
})
Here is my billing.php code, it loads values on the basis of first selected value, if I again select value from drop down,it doesn't show the updated record.
<?php
include('config.php');
$action = $_REQUEST['action'];
$stmt=$dbcon->prepare('SELECT discount FROM table_name WHERE name=:name
ORDER BY name');
$stmt->execute(array(':name'=>$action));
}
?>
<div class="row">
<?php
if($stmt->rowCount() > 0){
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
?>
You can do it without page refresh but you gonna need another php file, let's name it query.php to get you the result.
On your current page
<select>
<option value='bob'>Bob
<option value='jane'>Jane
</select>
<div id='output'></div>
<script>
$('select').change(function(){
let name = $(this).val();
$.ajax({
url: 'query.php',
method: 'POST',
data: {username: name},
success: function(response){
$('#output').html(response);
}
});
})
In query.php
$username = $_POST['username'];
//query database to get your result
echo json_encode($result);

How to add select option dropdown dynamically

i have a problem with my dynamic select option. My problem is my select option didn't show anything, just show blank. I have tried many times and i am stuck
this is my html select option code
<select name="jumlahpesan" id="jumlahpesan" data-native-menu="false">
<option value="choose-one" data-placeholder="true">Choose one... </option>
</select>
and this is my ajax code to get value to fill in my select option
$.ajax({
url: host+'/skripsi3/phpmobile/cekjumlah.php',
data: { "id": getacara},
dataType: 'json',
success: function(data, status){
$.each(data, function(i,item){
$("#jumlahpesan").append('<option value="'+item.jumbros+'">"'+item.jumbros+'"</option>').trigger("create")
});
},
error: function(){
//output.text('There was an error loading the data.');
}
});
and for the last, this is my "cekjumlah.php"
<?php
session_start();
include "config.php";
$idacara=mysql_real_escape_string($_GET["id"]);
$arr = array();
$result=mysql_query("select jumlahpesan from acara where id_acara='$idacara'");
if (!empty($result))
{
while ($row=mysql_fetch_array($result))
{
$tempjum = $row['jumlahpesan'];
for($i=0;$i<$tempjum;$i++)
{
$fetchkategori[] = array
(
'jumbros' => $i,
);
}
}
}
mysql_close($con);
header('Content-Type:application/json');
echo json_encode($fetchkategori);
?>
i want to fill my select option from my looping in "cekjumlah.php" and call my php with my ajax. Thank you
this is my Ajax Response
[{"jumbros":0},{"jumbros":1},{"jumbros":2}]
I can't really help you with the PHP side of things, so if there is a problem there, I can't see it.
But you seem to be using .each() incorrectly, as each is meant to iterate over a jquery selection of elements and execute a funciton for each element, whereas your seem to be trying to use it as a foreach over data
I think you have to replace that $.each with
for item in data{
$("#jumlahpesan").append('<option value="'+item.jumbros+'">"'+item.jumbros+'"</option>').trigger("create")
}
(i'm assuming data is a JSON array, you may have to use JSON.parse(data) first judging by some of the comments on your post.

execute PHP code when selecting a combobox item

I have a static combobox in a php web page.I want when selecting an item from this combobox (example 'item 1') the php execute a SELECT statement to get the value of a field named 'item 1' from a table X in my database.
How that can be done ?
You will need to use AJAX to do this. Here is a simple example:
HTML
Just a simple select box, for the purposes of this example.
<select id='items'>
<option value='1'>Item 1</option>
<option value='2'>Item 2</option>
<option value='3'>Item 3</option>
</select>
JavaScript
I'm going to use jQuery here, you don't have to if you don't want to but it makes AJAX a whole lot easier.
The browser will listen for a change event on the select box and perform an AJAX request to the appropriate URL. When the server sends back data, the success function will be triggered. Read more about .ajax() in the jQuery documentation.
$(document).ready(function() {
$('#items').change(function() {
$.ajax({
type: 'GET',
url: 'pageWithPhpCode.php',
data: {
itemID: $(this).val()
},
dataType: 'json',
success: function(data) {
// do whatever here
console.log(data);
}
});
});
});
PHP
Here I'm retrieving the data, JSON encoding it, and sending it back to the client with the appropriate MIME type. I'm not sure how you connect to your MySQL database, but I'm using PDO here.
Keep in mind that mysql_* functions are deprecated.
<?php
if(isset($_GET['itemID'])) {
$db = new PDO();
// ... connect to your database, however you do it
$q = 'SELECT * FROM items WHERE id = :itemid;';
$stmt = $db->prepare($q);
$stmt->bindValue(':itemid', $_GET['itemID'], PDO::PARAM_INT);
$stmt->execute();
$output = $stmt->fetchAll(PDO::FETCH_ASSOC);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($output);
}

How to build a dynamic query based on dropdown option?

EDITED:
SQL
$valuefromjs = $_REQUEST['var'];
$result6 = "SELECT DISTINCT $valuefromjs FROM persons ORDER BY $valuefromjs ASC";
$result7 = mysql_query($result6);
$num = mysql_num_rows($result7);
$dataRanges[0] = array('dataRanges');
for ($i=1; $i<($num+1); $i++)
{
$dataRanges[$i] = array( (int) mysql_result($result7, $i-1) );
}
echo json_encode($dataRanges);
HTML
<select id="combo2" class="combo" data-index="2"></select>
jQuery
$('#1combo').on('change', function () {
var jsonVar = $.ajax({
url : "visits/comboquery.php?var="+$(this).val(),
dataType: "json",
async: false,
success: function(response) {
}
}).responseText;
for (var i=1; i<objVar.length;i++)
{
$('#combo2').html("<option value="+objVar[i]+">"+objVar[i]+"</option>");
}
});
QUESTION:
I have an array with query results. Now i need that results be the combo2 options, what is wrong?
To my understanding the choice from combo1 will define which query to run for building combo2.
The issue: your PHP for building the combo2 is parsed at the server side i.e. the PHP code is always finished executing by the time the page reaches the user's browser and your javascript begins to execute.
If you have a finite set of possible queries that can generate the seconds combo (which should be the case since combo1 has a finite number of options), you can create all of them, each with a different id, and maintain them hidden (css "display: none").
<select id="firstCombo2" class="combo2">
...
</select>
<select id="secondCombo2" class="combo2">
...
</select>
etc.
Now, when the user makes a selection from combo1, you can decide which one of the hidden combo2's you are going to display (css "display: block").
$('select#combo1).on("change", function(){
$('select.combo2').css('display','none'); //hide all combo2's
if($(this).val()=='Opt1'){
$('select#firstCombo2').css('display','block');
}else if($(this).val()=='Opt2'){
$('select#secondCombo2').css('display','block');
}
}
You should use AJAX in order to solve your problem.
on combo1 onChange call an AJAX call to your server and send selected value of combo1.
Then in your php code run query with value received from AJAX request and construct a new combo box with options in string and echo back that string. You can use that AJAX response to populate new combo2.

Send data in Ajax response

hey I am trying to populate one select dropdown on the basis of another one using ajax. I have one select populated with portfolios and the 2nd one is empty. when I select an option from the 1st select box. I call an ajax function in which I send the selected portfolio id, In the ajax method I find the groups for the selected id, how can I populate the 2nd select with the groups I found. My code is
The form which contains two selects
<form name="portfolios" action="{{ path('v2_pm_portfolio_switch') }}" method="post" >
<select id="portfolios" name="portfolio" style="width: 200px; height:25px;">
<option selected="selected" value="default">Select Portfolio</option>
{% for portfolio in portfolios %}
<option get-groups="{{ path('v2_pm_patents_getgroups') }}" value={{ portfolio.id }}>{{ portfolio.portfolioName }}</option>
{% endfor %}
</select><br/><br/>
<select id="portfolio-groups" name="portfolio-groups" style="width: 200px; height:25px;">
<option selected="selected" value="default">Select Portfolio Group</option>
</select><br/>
</form>
The JS
<script>
$(document).ready(function(){
$('#portfolios').change(function() {
var id = $("#portfolios").val();
var url = $('option:selected', this).attr("get-groups");
var data = {PID:id};
$.ajax({
type: "POST",
data: data,
url:url,
cache: false,
success: function(data) {
//want to populate the 2nd select box here
}
});
});
});
</script>
Controller method where I find the groups for the selected portfolio
public function getgroupsAction(Request $request){
if ($request->isXmlHttpRequest()) {
$id = $request->get("PID");
$em = $this->getDoctrine()->getEntityManager();
$portfolio_groups = $em->getRepository('MunichInnovationGroupPatentBundle:PmPatentgroups')
->getpatentgroups($id);
return $portfolio_groups;
}
}
Any idea how can i send the portfolio groups and populate the 2nd select
thanks in advance
Use getJson instead of ajax();
Json (JavaScript Object Notation) , is the most easiest way to send structured data between php and javascript.
I Assuming here that the controller respond directly to the ajax query and that $portfolio_groups is an associative array with "id" and "name" as keys or an object with this same properties.
In your PHP controller send json data:
public function getgroupsAction(Request $request){
if ($request->isXmlHttpRequest()) {
$id = $request->get("PID");
$em = $this->getDoctrine()->getEntityManager();
$portfolio_groups = $em->getRepository('MunichInnovationGroupPatentBundle:PmPatentgroups')
->getpatentgroups($id);
echo json_encode($portfolio_groups);
}
}
Then use getJson to retrieve data and iterate over it :
$.getJSON(url, data, function(result) {
var options = $("#portfolio-groups");
$.each(result, function(item) {
options.append($("<option />").val(item.id).text(item.name));
});
});
Have a look to the getjson documentation for more detail about it
Check out this XML tutorial (someone out there is going to flame me for linking to w3schools) it's a good start.
AJAX requests are, in VERY broad terms, calls which make a browser open a window that only it can see (not the user). A request is made to the server, the server returns a page, the script that made the request can view that page. This means that anything which can be expressed in text can be transmitted via AJAX, including XML (for which the X in AJAX stands for).
How is this helpful? Consider, if you are trying to populate a drop down list, you need to return a list of items to populate it with. You COULD make an ajax call to a page http://www.mysite.com/mypage.php?d=select1 (if you are unfamiliar with GET and POST requests, or are a little in the dark regarding the more utilitarian aspects of AJAX, another full tutorial is available here) and have it return a list of items as follows:
item1
item2
item3
...
And scan the text for line breaks. While this certainly would work for most cases, it's not ideal, and certainly won't be useful in all other cases where AJAX may be used. Instead consider formatting the return in your PHP (.NET, ASP, whatever) in XML:
<drop>
<item>item1</item>
<item>item2</item>
<item>item3</item>
</drop>
And use Javascripts built in parser (outlined here) to grab the data.
What I would do is to use the $.load() function.
To do this, your getgroupsAction should return the options html.
The JS:
<script>
$(document).ready(function(){
$('#portfolios').change(function() {
var id = $("#portfolios").val();
var url = $('option:selected', this).attr("get-groups");
var data = {PID:id};
// Perhaps you want your select to show "Loading" while loading the data?
$('#portfolio-groups').html('<option selected="selected" value="default">Loading...</option>');
$('#portfolio-groups').load(url, data);
});
});
</script>
I don't know how $portfolio_groups stores the data, but let's say you'd do something like this in your response:
<?php foreach($portfolio_groups as $p) : ?>
<option value="<?php echo $p->value ?>"><?php echo $p->name ?></option>
<?php endforeach ?>
This way, the select will be filled with the options outputted by getgroupsAction.
The easiest way would be to return json string from your controller and then process it in the 'success' call of the $.ajax.
Lets assume, that your $portfolio_groups variable is an array:
$portfolio_groups = array('1'=>'Portfolio 1', '2' => 'Portfolio 2');
then you can return it from controller as json string like this:
echo json_encode($portfolio_groups);
Then in your jQuery ajax call you can catch this string in the response (the 'success' setting of the $.ajax). Don't forget to add setting dataType: 'json'
Roughly, your $.ajax call will look like this:
$.ajax({
type: "POST",
data: data,
url:url,
cache: false,
dataType: 'json', // don't forget to add this setting
success: function(data) {
$.each(data, function(id, title){
var node = $('<option>').attr('value', id).html(title);
// this will simply add options to the existing list of options
// you might need to clear this list before adding new options
$('#portfolio-groups').append(node);
});
}
});
Of course, you will also need to add the checks if the data is not empty, etc.
Supposing that the function getgroupsAction stays in a flat php controller ( not inside a class ) you should tell the server to execute the function
so at the end of file being called by ajax you should barely call the function first ( probably you did it! )
For your patents group result set, you can generate the select by php or by javascript
In first case you should do this:
//php
$options = getgroupsAction($_REQUEST);
$return = "<select name =\"name\" id=\"id\"><option value=\"\"></option>";
foreach( $options as $option){
$return.= "<option value=\"$option\">$option</option>";
}
$return .= "</select>";
echo $return;
Then in Javascript:
// javascript
var data = {PID:id};
$.ajax({
type: "POST",
data: data,
url:url,
cache: false,
success: function(data) {
//inside data you have the select html code so just:
$('#divWhereToappend').append(data);
},
error: function(data) {
//ALWAYS print the error string when it returns error for a more easily debug
alert(data.responseText);
}
});

Categories