I'm trying to pass the value of the dropdown menu to the PHP variable $anno, so the print_r() function at the end can use the realtive $coefficiente variable (which depends on $anno).
<select name="anno">
<option>1940</option>
<option>1941</option>
<option>1942</option>
</select>
<?php
$importo = "100";
$anno = $_POST["anno"];
if ( $anno == "1940" ) { $coefficiente = "10"; } ;
if ( $anno == "1941" ) { $coefficiente = "20"; } ;
if ( $anno == "1942" ) { $coefficiente = "30"; } ;
print_r(($importo*$coefficiente)/1936.27); echo '€';
?>
Can this be "AJAXified"?
At this time when I choose the dropdown option, the print_r function isn't updated. Do I need a submit button?
If you want to calculate your formula in the same page, don't use PHP use Javascript
<select name="anno">
<option>1940</option>
<option>1941</option>
<option>1942</option>
</select>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// We bind our AJAX handler to the onChange event of the select element
$("select[name='anno']").on('change', function(e) {
var importo = "100";
var anno = $(this).val();
var coef = "";
if (anno == 1940) { coef = 10; }
if (anno == 1941) { coef = 20; }
if (anno == 1942) { coef = 30; }
alert(importo*coef/1936.27 + "€");
})
});
For PHP handling, use AJAX (warning I couldn't test this!)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// We bind our AJAX handler to the onChange event of the select element
$("select[name='anno']").on('change', function(e) {
$.ajax({
type: "POST",
url : "your_php_script.php",
data: { anno: $(this).val() },
})
.done(function(data) {
alert(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert("Something went wrong!\n" + errorThrown);
});
})
});
Related
sorry for my english but i will try my best to ask my question correctly.
As layout i'm using this = https://codepen.io/Sool/pen/vvodgj with minor changes to support url hash.
Isotope JS Code:
$(document).ready(function($) {
var $grid = $('.grid').isotope({
// options
itemSelector: '.grid-item',
layoutMode: 'fitRows',
});
var filterFns = {
// show if number is greater than 50
numberGreaterThan50: function() {
var number = $(this).find('.number').text();
return parseInt(number, 10) > 50;
},
// show if name ends with -ium
ium: function() {
var name = $(this).find('.name').text();
return name.match(/ium$/);
}
};
function getHashFilter() {
// get filter=filterName
var matches = location.hash.match(/filter=([^&]+)/i);
var hashFilter = matches && matches[1];
return hashFilter && decodeURIComponent(hashFilter);
}
// change is-checked class on buttons
var $buttonGroup = $('.filters');
$buttonGroup.on('click', 'li', function(event) {
$buttonGroup.find('.is-checked').removeClass('is-checked');
var $button = $(event.currentTarget);
$button.addClass('is-checked');
var filterValue = $button.attr('data-filter');
// set filter in hash
location.hash = 'filter=' + encodeURIComponent(filterValue);
$grid.isotope({ filter: filterValue });
});
var isIsotopeInit = false;
function onHashchange() {
var hashFilter = getHashFilter();
if (!hashFilter && isIsotopeInit) {
return;
}
isIsotopeInit = true;
// filter isotope
$grid.isotope({
itemSelector: '.element-item',
layoutMode: 'fitRows',
// use filterFns
filter: filterFns[hashFilter] || hashFilter
});
// set selected class on button
if (hashFilter) {
$buttonGroup.find('.is-checked').removeClass('is-checked');
$buttonGroup.find('[data-filter="' + hashFilter + '"]').addClass('is-checked');
}
}
$(window).on('hashchange', onHashchange);
// trigger event handler to init Isotope
onHashchange();
})
AJAX Code:
$(document).ready(function() {
var limit = 7;
var start = 4;
var action = 'inactive';
function load_country_data(limit, start) {
$.ajax({
url: "fetch.php",
method: "POST",
data: { limit: limit, start: start },
cache: false,
success: function(data) {
$('#load_data').append(data);
if (data == '') {
$('#load_data_message').html("<button type='button'>All images loaded</button>");
action = 'active';
} else {
$('#load_data_message').html("<button type='button'>Loading images.....</button>");
action = "inactive";
}
}
});
}
if (action == 'inactive') {
action = 'active';
load_country_data(limit, start);
}
$(window).scroll(function() {
if ($(window).scrollTop() + $(document).height() > $("#load_data").height() && action == 'inactive') {
action = 'active';
start = start + limit;
setTimeout(function() {
load_country_data(limit, start);
}, 1000);
}
});
});
PHP Code to fetch data:
<?php
if(isset($_POST["limit"], $_POST["start"]))
{
include "mysqli_connection.php";
$query = "SELECT * FROM gallery ORDER BY order ASC LIMIT ".$_POST["start"].", ".$_POST["limit"]."";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<div class="col-md-3 grid-item <?= htmlspecialchars($row["category"]) ?>" data-category="<?= htmlspecialchars($row["category"]) ?>">
<img data-src="/assets/images/gallery/<?= htmlspecialchars($row["image"]) ?>" data-srcset="/assets/images/gallery/<?= htmlspecialchars($row["image"]) ?>" class="img-fluid" alt="<?= htmlspecialchars($row["title"]) ?> Image" srcset="/assets/images/gallery/<?= htmlspecialchars($row["image"]) ?>" src="<?= htmlspecialchars($row["image"]) ?>">
</div>
<?php
}
mysqli_close($conn);
}
?>
The data is loaded from the database and everything seems to be fine. But at the same time, filtering stops working. How to make filtering work with ajax?
How to make sure that when you click on a certain category, data from a certain category is loaded? With ajax and working url hash, something like that domain.com/#filter=category1 or domain.com/#filter=category3.
I would be very grateful for any advice or help on this issue, thank you.
So I'm trying to pass 2 datas from AJAX to PHP so I can insert it in my database but there seems to be something wrong.
My computation of the score is right but it seems that no value is being passed to my php file, that's why it's not inserting anything to my db.
AJAX:
<script type = "text/javascript" language="javascript">
$(document).ready(function() {
$("#finishgs").click(function(){
var scoregs = 0;
var remarkgs = "F";
var radios = document.getElementsByClassName('grammar');
for (var x=0; x<radios.length; x++){
if (radios[x].checked) {
scoregs++;
}
else
scoregs = scoregs;
}
if (scoregs >= 12){
remarkgs = "P";
}
else{
remarkgs = "F";
}
});
});
$(document).ready(function() {
$("#GTScore").click(function(event) {
$.post(
"dbinsert.php",
{ scoregs:scoregs , remarkgs: remarkgs},
function(data){
$('#inputhere').html(data);
}
);
});
});
PHP:
if( $_REQUEST["scoregs"] || $_REQUEST["remarkgs"]) {
$scoregs = $_REQUEST['scoregs'];
$remarkgs = $_REQUEST['remarkgs'];
}
There is an extra closing bracket );, you should remove. Try this:
$(document).ready(function() {
$("#GTScore").click(function(event) {
event.preventDefault();//to prevent default submit
$.ajax({
type:'POST',
url: "dbinsert.php",
{
scoregs:scoregs ,
remarkgs: remarkgs
},
success: function(data){
$('#inputhere').html(data);
}
});
});
And in php, you need to echo the variable or success/fail message after you insert data into the database:
echo $scoregs;
echo $remarkgs;
I want to make the third drop down populated based on selection on second drop down refer value from first and second drop down.
jQuery
<script type="text/javascript">
$(document).ready(function() {
$("#parent_cat").change(function() {
$.get('loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
$("#sub_cat").html(data);
});
});
$("#sub_cat").change(function() {
$.get('loadsubelement.php?sub_cat=' + $(this).val() + $('#parent_cat').val(), function(data) {
$("#select_subelement").html(data);
});
});
});
</script>
loadsubelement.php
<?php
include('config.php');
$parent_cat = $_GET['parent_cat'];
$sub_cat = $_GET['sub_cat'];
$query = mysqli_query($connection, "SELECT * FROM maincategories WHERE categoryID = {$parent_cat}");
$query = mysqli_query($connection, "SELECT * FROM maincategories WHERE subcategoryID = {$sub_cat}");
echo '<option value="">Please select</option>';
while($row = mysqli_fetch_array($query)) {
echo '<option value="'.$row['subcategoryID'].'">' . $row['maincategory_name'] . "</option>";
}
?>
I think you have to change your query string like this:
$.get('loadsubelement.php?sub_cat=' + $(this).val() +
"&parent_cat" + $('#parent_cat').val()
You are missing this: "&parent_cat" in your second ajax call.
Or a better way of doing is to send the an object like this:
$("#sub_cat").change(function() {
var dataString = {
parent_cat : $('#parent_cat').val(),
sub_cat : $(this).val()
};
if($('#parent_cat').val() !== ""){ // check if value is selected or not i guessed default value as "".
alert("Please choose the parent value.");
$('#parent_cat').focus(); // apply focus on the element.
return false;
}else{
$.get('loadsubelement.php', dataString, function(data) {
$("#select_subelement").html(data);
});
}
});
jQuery(function($) {
jQuery("#office_id").change(function(){
var inputString=jQuery("#office_id").val();
$.post("?r=reports/summary/loademployees/", {office_id: ""+inputString+""}, function(data){
$('#employee_id').fadeIn();
$('#employee_id').html(data);
}
});
});
});
This is a program triggers when when u change a dropdown containing offices having id as office_id and load employees (another dropdown box having id employee_id) of that office.
I have a form that uses the jQuery UI autocomplete function on two elements, and also has the ability to clone itself using the SheepIt! plugin.
Both elements are text inputs. Once a a value is selected from the first autocomplete (continents), the values of the second autocomplete (countries) are populated with options dependent on the first selection.
My problem is, when clones are made, if the user selects an option from the first autocomplete (continent), it changes the first input values on all clones. This is not happening for the second input (country).
What am I missing?
Note: the #index# in the form id and name is not CFML. I am using PHP, and the hash tags are part of the SheepIt! clone plugin.
Javascript:
<script src="../../scripts/jquery-1.6.4.js"></script>
<script src="../../scripts/jqueryui/ui/jquery.ui.core.js"></script>
<script src="../../scripts/jquery.ui.widget.js"></script>
<script src="../../scripts/jquery.ui.position.js"></script>
<script src="../../scripts/jquery.ui.autocomplete.js"></script>
<script src="../../scripts/jquery.sheepIt.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function ord(chr) {
return chr.charCodeAt(0);
}
function chr(num) {
return String.fromCharCode(num);
}
function quote(str) {
return '"' + escape(str.replace('"', "'")) + '"';
}
String.prototype.titleCase = function () {
var chars = [" ", "-"];
var ths = String(this).toLowerCase();
for (j in chars){
var car = chars[j];
var str = "";
var words = ths.split(car);
for(i in words){
str += car + words[i].substr(0,1).toUpperCase() + words[i].substr(1);
}
ths = str.substr(1);
}
return ths;
}
function incrementTerm(term) {
for (var i = term.length - 1; i >= 0; i--){
var code = term.charCodeAt(i);
if (code < ord('Z'))
return term.substring(0, i) + chr(code + 1);
}
return '{}'
}
function parseLineSeperated(data){
data = data.split("\n");
data.pop(); // Trim blank element after ending newline
var out = []
for (i in data){
out.push(data[i].titleCase());
}
return out;
}
function loadcontinent(request, response) {
var startTerm = request.term.toUpperCase();
var endTerm = incrementTerm(startTerm);
$.ajax({
url: '/db/continent.php?startkey='+startTerm+'&endkey='+endTerm,
success: function(data) {
var items = parseLineSeperated(data);
response(items);
},
error: function(req, str, exc) {
alert(str);
}
});
}
function loadcountry(request, response) {
var startTerm = request.term.toUpperCase();
var endTerm = incrementTerm(startTerm);
var continent = $('.continent_autocomplete').val().toUpperCase();
$.ajax({
url: '/db/country.php?key=' + continent,
success: function(data) {
var items = parseLineSeperated(data);
response(items);
},
error: function(req, str, exc) {
alert(str);
}
});
}
$('#location_container_add').live('click', function() {
$("input.continent_autocomplete").autocomplete(continent_autocomplete);
$("input.continent_autocomplete").keyup(continent_autocomplete_keyup);
$("input.country_autocomplete").autocomplete(country_autocomplete);
$("input.country_autocomplete").keyup(country_autocomplete_keyup);
$('input.country_autocomplete').focus(country_autocomplete_focus);
});
var location_container = $('#location_container').sheepIt({
separator: '',
allowRemoveLast: true,
allowRemoveCurrent: false,
allowRemoveAll: false,
allowAdd: true,
allowAddN: false,
maxFormsCount: 10,
minFormsCount: 1,
iniFormsCount: 1
});
var continent_autocomplete = {
source: loadcontinent,
select: function(event, ui){
$("input.continent_autocomplete").val(ui.item.value);
}
}
var continent_autocomplete_keyup = function (event){
var code = (event.keyCode ? event.keyCode : event.which);
event.target.value = event.target.value.titleCase();
}
var country_autocomplete = {
source: loadcountry,
}
var country_autocomplete_keyup = function (event){
event.target.value = event.target.value.titleCase();
}
var country_autocomplete_focus = function(){
if ($(this).val().length == 0) {
$(this).autocomplete("search", " ");
}
}
$("input.continent_autocomplete").autocomplete(continent_autocomplete);
$("input.continent_autocomplete").keyup(continent_autocomplete_keyup);
$("input.country_autocomplete").autocomplete(country_autocomplete);
$("input.country_autocomplete").keyup(country_autocomplete_keyup);
$('input.country_autocomplete').focus(country_autocomplete_focus);
});
</script>
HTML:
<div id="location_container">
<div id="location_container_template" class="location_container">
<div id="continent_name">
<label> Continent Name:</label>
<input type="text" id="continent_name_#index#" name="continent_name_#index#" class="continent_autocomplete" />
</div>
<div id="country">
<label> Country:</label>
<input type="text" id="country_autocomplete_#index#" name="country_autocomplete_#index#" class="country_autocomplete" />
</div>
</div>
</div>
select: function(event, ui){
$("input.continent_autocomplete").val(ui.item.value);
}
That code says explicitly to set the value of every <input> with class "continent_autocomplete" to the selected value.
You probably want something like
$(this).val(ui.item.value);
but it depends on how your autocomplete code works.
This line: $("input.continent_autocomplete").val(ui.item.value); is updating all inputs with class continent_autocomplete.
UPDATE:
From jQueryUI Autocomplete Doc:select:
Triggered when an item is selected from the menu; ui.item refers to
the selected item. The default action of select is to replace the text
field's value with the value of the selected item. Canceling this
event prevents the value from being updated, but does not prevent the
menu from closing.
You shouldn't need the select bit at all, it looks like you're simply trying to achieve the default action.
I'm trying to pass a variable via jquery ajax call. I'm not exactly sure how to do it properly. I get the lon lat coordinates through another html5 script.
How do i get the coordinates on the other side? I tried $_GET(lat).
I'm also not sure if i'm able to use the location.coords.latitude in a different < script >.
$.ajax({
cache: false,
url: "mobile/nearby.php",
dataType: "html",
data: "lat="+location.coords.latitude+"&lon="+loc.coords.longitude+,
success: function (data2) {
$("#nearbysgeo").html(data2);
}
});
These scripts are above the jquery code
<script type="text/javascript">
google.setOnLoadCallback(function() {
$(function() {
navigator.geolocation.getCurrentPosition(displayCoordinates);
function displayCoordinates(location) {
var map = new GMap2(document.getElementById("location"));
map.setCenter(new GLatLng(location.coords.latitude, location.coords.longitude), 12);
map.setUIToDefault();
var point = new GLatLng(location.coords.latitude, location.coords.longitude);
var marker = new GMarker(point);
map.addOverlay(marker);
}
})
});
</script>
<script type="text/javascript" charset="utf-8">
function getLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
document.getElementById("output").innerHTML = "Your browser doesn't handle the GeoLocation API. Use Safari, Firefox 4 or Chrome";
}
}
function success(loc){
console.log(loc);
strout = "";
for(l in loc.coords){
//strout += l +" = " +loc.coords[l] + "<br>";
}
strout += '';
strout += '<center><img src="http://maps.google.com/maps/api/staticmap?center='+loc.coords.latitude+','+loc.coords.longitude+'&markers=color:blue%7Clabel:Y%7C'+loc.coords.latitude+','+ loc.coords.longitude+'&zoom=15&size=400x250&sensor=false¢er=currentPosition"></center>';
document.getElementById("output").innerHTML = strout;
document.forms['newPostForm'].lat.value = loc.coords.latitude;
document.forms['newPostForm'].lon.value = loc.coords.longitude;
document.getElementById("coords").innerHTML = '';
document.getElementById("coords").innerHTML = 'CURRENT: Lat:' + loc.coords.latitude + ' Lon:' + loc.coords.longitude;
}
function error(err){
document.getElementById("output").innerHTML = err.message;
}
function clearBlog() {
document.getElementById("listview").innerHTML = '';
}
</script>
ADDITIONAL INFO:
It works if I use this line. So i guess i can't use loc.coords.latitude this way.
data: "&lat=43&lon=-79.3",
Well i hacked it for now to get it working. I filled two hidden form elements on the page with lon and lat values. Then used 'document.forms['newPostForm'].lat.value' to create a line like this.
data: "&lat="+document.forms['newPostForm'].lat.value+"&lon="+document.forms['newPostForm'].lon.value,
Still would like an actual solution.
Here's some code from a project I'm working on. Very simple.
$.post("../postHandler.php", { post_action: "getRecentPosts", limit: "10" }, function(data){
$("#post-list").html(data);
You can switch out .post with .get with no other changes, like so:
$.get("../postHandler.php", { post_action: "getRecentPosts", limit: "10" }, function(data){
$("#post-list").html(data);
Data is passed in name value pairs like so.
{ post_action: "getRecentPosts", limit: "10" }
Rewrite:
$.get("mobile/nearby.php", { lat: location.coords.latitude, lon: loc.coords.longitude }, function(data2){
$("#nearbysgeo").html(data2);
});
$lat = preg_replace('#[^0-9\.]#', '', $_GET['lat']);
You probably can use location.coords.latitude if it is defined before.
jQuery.ajax(
{
url : 'mobile/nearby.php',
data : {
'action' : 'update',
'newname' : 'enteredText',
'oldname' : 'original_html',
'userid' : '10'
},
success : function(msg){
if(msg == 1)
{
alert('success');
}
}
});
this is the proper syntax of jQuery.Ajax(); function