I have a form that uses a dropdown menu to select an option. After the option is selected I want to get a value form my DB to populate the next field with the correspondent value (in the scenario is to get the square footage of a rental property - but this value can be edited)
This is the field where i have the options:
<div>
<label class="control-label " for="local">Local</label>
<select class="select form-control" id="local" name="local" ><?php echo $lista_fraccoes;?></select>
</div>
after this i have the script to get the data:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$('#local').on('change', function(){
var .local = this.value;
$.ajax({
type: "POST",
url: "area_fraccao.php",
data:'local='+local,
success: function(result){
$("#area").value(result);
}
});
});
</script>
And after this i have the field that i want to populate:
<div class="form-group m-2 ">
<label class="control-label " for="area" type="value">Area</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fas fa-ruler-combined"></i>
</i>
</div>
<input class="form-control" id="area" name="area" placeholder="Em m2" type="value" value=""/>
</div>
In the area_fraccao.php file is where i get the correspondent value:
require_once 'config.php';
require_once 'functions.php';
$local = $_GET['local'];
$query_area = "SELECT * FROM TbFraccao WHERE PkFraccao=" . $local;
$result_area = mysqli_query($link, $query_area);
while ($row_area = mysqli_fetch_assoc($result_area)){
$area = $row_area['FraccaoArea'];
echo $area;
};
The solution I'm Using is presenting the following errors in web inspector
The code I'm using is updated matching the given suggestions.
Looking at your code, The code seems Ok. Please make sure that the query has no error by checking if running query was successful, check there is atleast one result and remove the semi-colon after while closing bracket.
if($result_area = mysqli_query($link, $query_area)){//the query is Ok
if(mysqli_num_rows($result_area)>0){//check there is atleast one result
while ($row_area = mysqli_fetch_assoc($result_area)){
$area = $row_area['FraccaoArea'];
echo $area;
}
}
}
else{//you have an error when writing your query
echo 'Wrong query';
}
if that does not help, the problem might be you did not sanitize the data during saving and there are characters from that data that interferes with the query. Show us how you did filtering before saving the data.
Set value of input elements using value method of jQuery
$("#area").value(result);
html() method is used to set innerHTML of elements
Related
I have the problem, that I can't access the value my textareas which are created in a while loop of php. I guess that they are not registered in the DOM. Same is for the button that is attached to it.
So I do know, that I have to access the button via jquery with the special event listener because of this dynamically creation. I get all the IDs that I need, but I am not able to get the value of the textarea, even that I can get its correct ID, as it somehow seems to be just empty.
As I can't post a php fiddle in here, here is an example of how it works.
include"connection.php";
$stuff="here is the query";
for ($n = 1; $n <= 13; $n++) {
$xy=$con->query($stuff);
while($row=mysqli_fetch_assoc($xy))
{
$value = $row['value'];
echo"<div id='$n' class='antworten'>$value<br>
<div id='notizcontainer$n' class='antwortcontainer'>Notizen:</div>
<div class='antwortcontainer' id='notizerstellen$n'>Notiz erstellen:<br>
<textarea id='notizfeld' class='textarea'></textarea><br>
<button id='absenden' class='notizabsenden'>Notiz absenden</button></div>
</div>";
}
}
jQuery:
$(document).on('click', '.notizabsenden', function(){ //do this bc its not registered and .click() is not working, also I need the click event on the button class to know on which button the event is going on
var parentid = $(this).parent().attr('id'); //get parentid of button
var notizid = $('#'+parentid).find('textarea').attr('id'); //find id of textarea of parent
var notiz = $('#'+notizid).val(); //this should give me the text of the textarea... but it returns empty/blank
console.log(notizcontainer); //this turns out correct
console.log(parentid); //this turns out correct
console.log(notiz); //this returns empty/blank as if the textarea has nothing in it... which it does
The issue is because the HTML in your PHP loop is re-using the same id for multiple elements when they have to be unique. To fix that problem, remove the id attributes from all repeated content.
To address the issue of accessing the textarea content, you need to use DOM traversal to find the textarea related to the button which was clicked. To do that you can use a combination of closest() and find(), like this:
$(document).on('click', '.notizabsenden', function(e) {
const $btn = $(e.currentTarget);
const notiz = $btn.closest('.notizerstellen').find('.notizfeld').val();
console.log(notiz);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<!-- generated by your PHP loop... -->
<div class="antworten">$value<br>
<div class="antwortcontainer">Notizen:</div>
<div class="notizerstellen">
Notiz erstellen:<br />
<textarea class="notizfeld textarea">Lorem ipsum</textarea><br />
<button class="notizabsenden">Notiz absenden</button>
</div>
</div>
<div class="antworten">$value<br>
<div class="antwortcontainer">Notizen:</div>
<div class="notizerstellen">
Notiz erstellen:<br />
<textarea class="notizfeld textarea">Dolor sit</textarea><br />
<button class="notizabsenden">Notiz absenden</button>
</div>
</div>
<div class="antworten">$value<br>
<div class="antwortcontainer">Notizen:</div>
<div class="notizerstellen">
Notiz erstellen:<br />
<textarea class="notizfeld textarea">Amet consectetur</textarea><br />
<button class="notizabsenden">Notiz absenden</button>
</div>
</div>
This has been answered before, however I'm asking again for two reasons: I can't find any resources that utilize PDO, and regardless of that, all of the ones I've found consist of code without any comments or explanations, which makes it hard to interpret and adapt them to my use case.
I need to be able to make a dropdown dynamically update itself based on the selection of the previous one, and if I change that selection, it should re-update itself without having to submit the form or reload the page.
I've updated the code with what I've learned and found so far, but it's still not working properly. Everything works up to the point where the second dropdown should begin loading values.
HTML:
<div class="form-group row">
<label class="col-sm-2 form-control-label" onchange="productorInfo(this.value);">Codigo Productor (*)</label>
<div class="col-sm-4">
<select name="vendedor_codigo">
<?php foreach ($dd_productor_result as $dd_productor_display) : ?>
<option value="<?= $dd_productor_display['vendedor_codigo']; ?>">
<?= $dd_productor_display['vendedor_codigo']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
<label class="col-sm-2 form-control-label">Nombre (*)</label>
<div class="col-sm-4">
<select id="ajax-vendedor" name="vendedor_nombre">
<?php foreach ($ajax_productor_result as $dd_productor_display) : ?>
<option placeholder="Seleccione codigo" value="<?= $dd_productor_display['vendedor_nombre']; ?>">
<?= $dd_productor_display['vendedor_nombre']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
Ajax script:
function productorInfo(id) {
$.ajax({
type: "GET",
url: "/controller/produccion/db_ajax_update.php",
data: "mainid =" + id,
success: function (result) {
$("#ajax-vendedor").html(result);
}
});
};
First dropdown PHP code:
$dd_productor = "SELECT vendedor_codigo FROM lista_productores";
$productor_stmt = $pdo->prepare($dd_productor);
$productor_stmt->execute();
$dd_productor_result = $productor_stmt->fetchAll();
Second dropdown (ajax call):
if(isset($_GET['mainid'])){
productorInfo($_GET['mainid']);
$prod_value = productorInfo($_GET['mainid']);
}
$ajax_productor = "SELECT vendedor_nombre FROM lista_productores WHERE vendedor_codigo = {$prod_value}";
$productor_stmt = $pdo->prepare($ajax_productor);
$productor_stmt->execute();
$ajax_productor_result = $productor_stmt->fetchAll();
The onchange call should be on the select element not on the label
<label class="col-sm-2 form-control-label">Codigo Productor (*)</label>
<select name="vendedor_codigo onchange="productorInfo(this.value)">
But also it occurs to me you may not quite understand the process. Your ajax call won't be fired when the page loads so this bit:
<select id="ajax-vendedor" name="vendedor_nombre">
<?php foreach ($ajax_productor_result as $dd_productor_display) : ?>
<option placeholder="Seleccione codigo" value="<?= $dd_productor_display['vendedor_nombre']; ?>">
<?= $dd_productor_display['vendedor_nombre']; ?>
</option>
i would think is giving you undefined variable warnings (unless you are setting $ajax_productor_result initially in some way)
Responses from ajax are usually drawn in .js via success: function
(result) {
$("#ajax-vendedor").html(result);
}
from the looks of this though - unless there is more code that what has been posted, you are passing the .html() function an array or database rows so it's never going to display anything.
so you need to
1)draw a select with no options in it on pageload (or default options if you have them)
2)return a response that the success function can make use e.g. a json string which jquery can the parse
3)format the data in jquery into the <options> and then user the .html() function to update the select
4)if you want this to happen when the page initially loads then add in a document ready call to the productorInfo(id) function - this would be relevant if you are setting the initial select value in some way (so it may not be relevant to you)
I have some data in an ajax request that I am sending to a php file as an endpoint.
The code is the following:
// some calculations above here, but to keep things minimal assume they produce the following
totalBeforeTip = 38.43;
tipTotal = 5.77;
totalWithTip = 44.48;
saleCount = "3";
console.log("List for the query String: " + totalBeforeTip
+ "\n Tips: " + tipTotal
+ " \n Totals+Tip: "+ totalWithTip
+ "\n Totals Sales: " + saleCount);
// Send get to php with q-string
$.ajax({
url:"summary.php",
type: "get",
data:{
TotalSales: saleCount,
TotalsNoTip:totalBeforeTip,
TotalTip: tipTotal,
TotalWithTip: totalWithTip
},
success: function(resp){
console.log(resp);
window.location.href = "summary.php";
},
error: function(err){
console.log(err);
}
});
And my php is the following:
<main>
<?php
$TotalSales = $_GET["TotalSales"];
$TotalTips = $_GET["TotalTip"];
$TotalBeforeTip = $_GET["TotalsNoTip"];
$TotalWithTip = $_GET["TotalWithTip"];
?>
<div class='container'>
<div class='row'>
<div class='col-md-6'>
<form> <!--Main form for user interaction-->
<div class='form-group bigger-group'>
<label>Sales: </label>
<input readonly value="<?php echo $TotalSales ?>" />
</div>
<div class='form-group'>
<label>Totals Before Tips:</label>
</div>
<div class='form-group'>
<label>Total Tip Cost:</label>
</div>
<div class='form-group'>
<label>Total Cost with Tip:</label>
</div>
</div>
<div class=col-md-6>
<h1>Cost ($)</h1>
<div class='form-group'>
<input readonly value="<?php echo $TotalBeforeTip ?>"/>
</div>
<div class='form-group'>
<input readonly value="<?php echo $TotalTips ?>"/>
</div>
<div class='form-group'>
<input readonly value="<?php echo $TotalWithTip ?>"/>
</div>
</div>
</div>
</main>
When I redirect my fields are blank but in the response in the console log they are filled. I tried to do a page redirect to the resp it doesn't do anything. After poking at it quite a bit I got it to work by adding the following line to success: function(resp){....}.
window.location = "summary.php?TotalSales="+saleCount+"&TotalsNoTip="+totalBeforeTip+"&TotalTip="+tipTotal+"&TotalWithTip="+totalWithTip;
For some reason this works, and the fields in the php have the proper data but I don't see how? Or why it is that the data I passed in with the .ajax method just evaporated?
I've been struggling with this for two days and it works but I don't understand why at all. Can anyone shed some light?
So with the combination of all the feedback I've received and some more googling I've learned that AJAX is for ACTION not CONTENT and the core purpose of AJAX is to perform background processing without holding main flow on a page. Some good examples are :
Loading new tweets on twitter
Giving a notification if you have a new email in your inbox
Validating form fields on blur
Since in my case I wanted to send the totalBeforeTip, tipTotal, totalWithTip, saleCount to my summary.php to load the content of the input fields based off that data. Using AJAX for it is a bad approach because this should be done in a synchronous process.
I used the following code to accomplish this outside of ajax
window.location = "summary.php?TotalSales="+saleCount+"&TotalsNoTip="+totalBeforeTip+"&TotalTip="+tipTotal+"&TotalWithTip="+totalWithTip;
All I needed was the queryString.
window.location = "summary.php?TotalSales="+saleCount+"&TotalsNoTip="+totalBeforeTip+"&TotalTip="+tipTotal+"&TotalWithTip="+totalWithTip;
You need to do like these because Ajax get the response on same page and from that page you will be send the response to another page and then you get the response using $_GET['variables'].
I have read through all the "dynamic multiple dropdown lists" questions here on stackoverflow but could not find what I am looking for.
It's a form for states and cities. User select a state, through ajax I request the cities for that specific state ID.
But, I need to have the two selects already created and displayed (maybe the city select grayed out). An example here PenskeAutomotive.
What I managed to do so far is to have only the state select and upon the execution of ajax, from the XMLHttp.ResponseText to create the city select. An example here Dorpdown list example - at bottom of page.
I need to have both selects displayed and then only update the city select with the new values of the XMLHttp.ResponseText.
Can anybody point me to some direction?
UPDATE:
Right after posting I found a question that I have not read before. Went into it and I may have found my direction. I am just trying that right now. It's jQuery/Ajax. Question
Not sure where you're having trouble, but to (hopefully) point you in the right direction:
You could have both of your <select> elements created on the page, with the City dropdown having the HTML disabled attribute, which will gray it out.
The disabled dropdown will have no options, aside from maybe one that says something like "select state."
You'll add an onchange event listener to your State dropdown which will perform the AJAX call, and I would recommend you get your response back in JSON format.
Then you can clear out the options of the next dropdown and create and append the new options from your server, then enable the dropdown.
If you want to provide what you've done so far, I'm sure we can help debug it.
I use this code in my site, maybe is usefull for you:
in head:
<script language="JavaScript" type="text/JavaScript">
$(document).ready(function(){
$("#select1").change(function(event){
var id = $("#select1").find(':selected').val();
$("#select2").load('../scripts/depto.php?id='+id);
});
});
</script>
<script language="JavaScript" type="text/JavaScript">
$(document).ready(function(){
$("#select2").change(function(event){
var id = $("#select2").find(':selected').val();
$("#select3").load('../scripts/municipios.php?id='+id);
});
});
</script>
and in select:
<div class='control-group'>
<label class='control-label' for='typeahead'>País </label>
<div class="controls">
<select name="IDPAIS" id="select1" required>
<?
$sql = $conn->prepare("SELECT * FROM lista_paises");
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo
'<option value="'.$row[id].'">'.$row[opcion].'</option>';
}
?>
</select>
</div>
</div>
<div class='control-group'>
<label class='control-label' for='typeahead'>Departamento </label>
<div class="controls">
<select name="departamento" id="select2" required></select>
</div>
</div>
<div class='control-group'>
<label class='control-label' for='typeahead'>Municipio / Ciudad</label>
<div class='controls'>
<select name="ciudad" id="select3" required></select>
</div>
</div>
in the lista_paises.php
<?
include('../include/config.php');
$query = $conn->prepare("SELECT * FROM PAISES);
$respuesta="[";
foreach ($aMunicipios as $muni) {
$respuesta .="{id:".$muni["id_municipio"].",nombre_municipio:'".$muni["municipio_nombre"]."'},";
}
$respuesta = substr($respuesta,0,strlen($respuesta)-1);
$respuesta.="]";
echo $respuesta;
}
?>
in depto.php
<?
include('../include/config.php');
$sql = $conn->prepare("SELECT * FROM lista_estados WHERE relacion = ".$_GET['id']);
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo
'<option value="'.$row[id].'">'.$row[opcion1].'</option>';
}
?>
in municipios.php(ciudad/city)
<?
include('../include/config.php');
$sql = $conn->prepare("SELECT * FROM MUNICIPIOS WHERE relacion1 = ".$_GET['id']);
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo
'<option value="'.$row[id].'">'.$row[opcion2].'</option>';
}
?>
maybe works for you
I expose my case, I pick through mysql data and fill a combo with php and smarty, then I have a button to add more data to this combo and bbdd. Everything works correctly but me when POST data collecting that data added to the combo did not pick it up
CODE:
HTML code with smarty which fill the combo, and the button to add the new data to the combo
<form action="algo.php" method="post">
<div class="form-field">
<label for="cliente_sector">Sector*</label>
<select name="cliente_sector" id="cliente_sector">
{section name=sector loop=$sectores}
<option value="{$sectores[sector].sector}">{$sectores[sector].sector}</option>
{/section}
</select>
<p>Sector del cliente</p>
<label onclick="javascript:anadir('divAnadir')">Nuevo sector</label>
</div>
<div id="divAnadir" style="display: none;">
Nuevo sector:<input type="text" id="nuevo_sector" name="nuevo_sector" value=""/>
<input onclick="javascript:nuevoSector()" type="button" value="Añadir nuevo sector "/>
</div>
</form>
javascript functions
function anadir(a){
if(document.getElementById(a).style.display=="none")
$("#divAnadir").css("display", "block");
else
$("#divAnadir").css("display", "none");
}
function nuevoSector(){
var datos = document.getElementById("nuevo_sector").value;
$.get("/ajax/altaNuevoSector.php?sector="+datos, datos, function(data){
if(data != 1) {
alert('Nuevo sector añadido');
$("#divAnadir").css("display", "none");
$("#cliente_sector").append('<option value=" " selected="selected">'+data+'</option>')
return true;
}else{
alert('Este sector ya existe, pruebe de nuevo.');
return false;
}
});
}
Php script to update bbdd and response to javascript:
<?php
session_start();
require_once('../includes/config.php');
if($_GET['sector']){
$sql = "INSERT INTO clientes_sectores(sector) VALUES ('".$_GET['sector']."')";
$consulta = $con->ejecutar($sql);
if(!is_numeric($consulta))
echo '1';
else
echo $_GET['sector'];
}
?>
All work fine the data is added to the bbdd and displays in the combo, the problem is that the combo is in a form, by post I try to pick the data, if value cliente_sector is the new one not let me pick it up, the $ _POST ['cliente_sector'] is emptied. How do I fix it?
When i do submit in my form the $_POST['clientes_sector'] if in the combo is selected the new value.
thanks
Finally I refresh the page with a js function. Thanks for all.