Add HTML code triggered by selection changed - javascript

I have a simple select into my HTML code (a dropdown menu).
HTML
<select name="razza" onchange="razzaChanged()">
<?php while ($row = gdrcd_query($result, 'fetch')){ ?>
<option value="<?php echo $row['id_razza']; ?>" <?php if(gdrcd_filter('get',$_POST['razza'])==$row['id_razza']){ echo 'SELECTED'; } ?>>
<?php echo gdrcd_filter('out',$row['nome_razza']); ?>
</option>
<?php } ?>
JavaScript
<script>
function razzaChanged()
{
alert("I am an alert box!");
}
</script>
When the selection of the dropdown is chosen, I have to add some information below the dropdown. The information I have to add is a bit complex and pretty formatted (I need to do some query to retrieve data and then add text and another dropdown after the info).
How can I achieve this? I can register via JavaScript that the selection changed but then I don't know how to go further.

You could use ajax methods. Get value from select using oninput/onchange, use that value as data in ajax request. If request is successful then show server's response in a container where ever you want.
HTML
<select name="razza" id="razza">
<option value="1">Some Option</option>
<option value="2">Another Option</option>
<!-- Use your loop here and remove these options -->
</select>
Javascript
$("#razza").on('input change',function(){
var value = $(this).val();
// Ajax Request
$.ajax({
type: 'post', // you can also use 'get'
url: '/link/to/your/server/file',
data: {
key: value // use key required by backend
},
success: function(response) {
$('#your-container-div-id').html(response);
}
});
});
Please note that I have used code without 'onchange' attribute, as this is better. Feel free to ask...

There are few ways to achieve this. One would be to use what jquery library offers.
Here are just some very rough steps of how one could do it:
In your razzaChanged() function establish which value is selected:
function razzaChanged()
{
var val = $('select[name="razza"] option:selected').val();
// step 2 here
}
Now use this value to fetch data from the server with the help of AJAX:
$.ajax({
type: "GET",
url: '/your-url-to-call',
data: 'your_value=' + val,
success: function(data) {
// step 3 here
}
});
Now having data from server (i.e. json format) build your new select dropdown, i.e.:
var newSelect = $('<select>').appendTo('body');
$(data).each(function() {
newSelect.append($("<option>").attr('value', this.some_property).text(this.some_text));
});
It's definitely not a ready-to-use code as you would have to make sure you return properly formatted data on server side or change the code accordingly. Also
make sure jquery library is loaded and the code is wrapped with its ready function (easy to find example on internet).
Hope this helps.

You will need to do an AJAX POST or GET request to retrieve data from your database and you will need to use document.createElement("elementtype"); to create an element to add to your page.
With jQuery, your AJAX would look something like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$.ajax({
type: "POST",//can be GET or POST
url: "yoururl",
statusCode: {
404: function() {
alert( "page not found" );
},
data: {key: value},//you can have multiple keys and values
success: function(res){
//add elements to the page
$('#yourelememntid').html(res.someattribute);
}
}).done(function() {
//AJAX request finished
});
</script>

Related

Ajax call to insert to database not working

I'm trying to do an Ajax call on button click to insert to a database through a PHP file. I want to use AJAX to achieve this, but it does not show the alert dialog on success nor does it insert the data to the database. Here is the code I have:
AjaxTest.html:
<button type="button" onclick="create()">Click me</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
function create () {
$.ajax({
url: "AjaxTestRegistration.php",
type: "POST",
data: {
'bid': 10,
'kid': 20
},
success: function (msg) {
alert("!");
}
});
}
</script>
AjaxTestRegistration.php:
<?php
include "connection.php";
include "Coupon.php";
$bid = $_GET['bid'];
$kid = $_GET['kid'];
Coupon::insertCoupon($bid, $kid);
?>
If I try to enter AjaxTestRegistration.php manually in the browser like this: ajaxtestregistration.php?kid=10&bid=5, the row gets inserted into the database.
wWhat could be the problem with this code? How to rectify that?
Your PHP handles GET requests.
$bid = $_GET['bid'];
But your ajax function tries to POST
type: "POST",
The easiest here is to get your data by $_POST in php.
I think you should try $__REQUEST method of php and also use $_POST method if you use post from ajax
$bid = $__REQUEST['bid'];
$kid = $__REQUEST['kid'];

Passing Select Option to POST request

I'm very new to web development and I'm trying to pass what the user has selected in a field called accesslevel_id to a POST request, so I can pass it to my database. I'm following the example in my book, but it doesn't seem to work as intended.
My script is the following:
<script>
$(document).ready(function () {
$('#accesslevel_id').on('change', function () {
alert($('#accesslevel_id').val());
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select class="form-control" id="accesslevel_id" onchange="accesslevel_id" title="">
<option>Facility</option>
<option>Division</option>
<option>Corporate</option>
<option>Market</option>
<option>Group</option>
</select>
When on the site and a user selects an option it currently displays None for my print function defined as accesslevel_id = request.POST.get('accesslevel_id'). The next step, which i'm not at yet is to convert the option name into numbers to store into the database. I'm looking for advice on how to accomplish this.
I think you need to post the value of option value when it changes right?
$(document).ready(function () {
$('#accesslevel_id').on('change', function () {
var accesslevel_id = $(this).val();
$.ajax({url: "action-page",
data:"accesslevel_id="+accesslevel_id,
type: "POST",
success: function(result){
alert(result);
}
});
});
});

Using ajax request variable to populate a dropdown

My limits in javascript are preventing me to solve a problem I am facing at present.
I am doing an ajax request for retrieving some database values.
I receive the data I need alright, but
I am unable to use that value "cityareax" to either populate an existing dropdown or to create a new one.
Here is the code:
<script type="text/javascript">
function autocomp_city() {
var min_length = 2; // min caracters to display the autocomplete
var keyword = $("#city_namex").val();
if (keyword.length >= min_length) {
$.ajax({
url: "city_ajax_refresh.php",
type: "POST",
data: {keyword:keyword},
success:function(data){
$("#city_list").show();
$("#city_list").html(data);
}
});
} else {
$("#city_list").hide();
}
}
// set_item : this function will be executed when we select an item - a city name
function set_item(cityname, statename, cityarea) {
$("#city_namex").val(cityname);
$("#statex").val(statename);
// hide proposition list
$("#city_list").hide();
$("#cityareax").val(cityarea);
}
</script>
Can somebody help me?
tx Roberto
and thanks for your interest. I found my own solution. The main problem was timing.
I was trying to use data that I received from Ajax in a script that was inactive, having been executed onload.
When I moved my variable processing code in the function that was working AFTER THE AJAX REQUEST, everything went fine. It was about a week that I was running in circles trying to find a solution ...
Roberto
Are you missing a return type?
$.ajax({
url: "city_ajax_refresh.php",
type: "POST",
data: {keyword:keyword},
datatype: "html",
success:function(data){
$("#city_list").show();
$("#city_list").html(data);
}
});
What's the php output?
Need to use echo in PHP instead of return.
<?php
$output = some_function();
echo $output;
?>

Pass a value to multiple PHP pages at once with JQuery

My inexperience has me here asking this question.
Can I pass a value to multiple PHP pages in JQuery?
Here is an example of what I am trying to do.
$(function() {
$("#account").change(function() {
$("#facilities").load("displayfacilities.php?q=" + $("#account").val());
$("#facilities").load("updatefacilities.php?f=" + $("#account").val());
});
});
When the user changes a selection within a drop down list, a unique ID will be sent over to displayfacilities.php. I also need that ID in updatefacilities.php which is called from displayfacilities.php.
Is this a bad idea, or is there a better way?
Try to make use of $_SESSION and example of the usage.
This object allows you to store and retrieve data and a usual use case is to share this data across multiple pages within a session.
ex.
$(function() {
$("#account").change(function() {
// store value in superglobal variable and retrieved
// by session_start() in php script, see usage examples above
<?php $_SESSION['some_key'] = *some_value* ?>
// the following value however needs to be sent to server
// either via AJAX or some request.
$("#account").val();
});
});
Hope this helps.
Check this out,
First call ajax, when the response is received, make the second ajax call.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#account").change(function() {
var dataString1 = "q="+$("#account").val();
$.ajax
({
url: "displayfacilities.php",
type : "POST",
cache : false,
data : dataString1,
success: function(result1)
{
alert("Response from PHP file 1");
var dataString2 = "f=" + $("#account").val();
$.ajax
({
url: "updatefacilities.php",
type : "POST",
cache : false,
data : dataString2,
success: function(result2)
{
alert("Response from PHP file 2");
}
}
});
});
});
});
</script>

How to use Ajax to update a second selectbox in jquery using the first selectbox's value?

First off, I'm using wordpress, and the goal is to choose a dropdown selectmenu item, structured in jquery, to choose a parent category. This choice then updates the second select menu with the sub-categories of the parent.
So far, I have this ajax:
<script>
$(function(){
$( "#categories" )
.selectmenu({
select: function getval() {
var parent = $("#categories").val();
$.ajax({
url: "ajax.php",
data: { parent : parent },
type: "POST",
success: success: function(response){
$(".sub_cat").html(response);
},
error: function() {
alert("Error, possible missing file.");
}
}); //End of ajax
alert(parent);
} //End of getval
}) //End selectMenu
.selectmenu( "menuWidget" )
.addClass( "overflow" );
$( "#sub_cats" )
.selectmenu()
.selectmenu( "menuWidget" )
.addClass( "overflow" );
var categories = $('#categories');
var subcats = $('#sub_cats');
});
</script>
This is the HTML that will be populated:
<fieldset>
<div class=sub_cat>
</div>
</fieldset>
And This is ajax.php:
<?php
$parent = $_POST['parent'];
$subcats = get_categories("child_of=$parent");
$parent = "<label for="sub_cats">Select a Sub-category</label>
<select name="sub_cats" id="sub_cats">
<option selected="selected">Pick a Sub-Category</option>" .
foreach($subcats as $subcat) {
"<option value=" echo $subcat->name ">" . echo $subcat->name . "</option>"
} .
"</select>"
?>
The menus come in as they should, the alerts come in and the parent category is always sent to the ajax when the choice is made. But the success alert is never touched and I have no idea what I'm supposed to put in the ajax.php file. My guess would be to use that file to get the sub-cats in php, and then send it in json format, but I don't know how.
Absolutely any help is appreciated, I've been struggling with this for a while.
I've tried the solutions from below but I never get any code or value back from ajax.php with any of their answers. Thats where it stops. I also don't know how to populate the next selectbox with the new item. Pretend Im a super ignorant programmer who doesn't know a thing about these structures and explain from that standpoint, that might help I hope.
In the ajax.php file ... do this ...
$parent = $_POST['parent'];
// Query the subcategories using parent ..
// then loop and create select box ...
Then the change the ajax success like below ... and fill the data to subcatogory div
success: function(response){
$(".subcat-div").html(response);
}
The simple way is in change event in your #categories
this must send a request to server and response in html format refreshes #sub_cats
Let us see:
//in your js
$(document).ready(function(){
$("#categories").change(function(){
//here we get corrent selected id
//form categories in corrent selected option
var id = $(this).val();
//simple ajax request $.post
$.post("ajax.php",{
id:id
},function(data){
$("#sub_cats").empty()
$("#sub_cats").append(data)
},"html")
});
}
//
On ajax.php your return must be in Html
... your query above end fetching result:
while($sub = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<option value='".$sub['id']."'>".$sub['name']."</option>";
}
Check it out.

Categories

Resources