I'm trying to reach for a result passing by two steps :
- The first step I want to POST a value in PHP file from HTML(dropdown list):
this what I tried :
<select class="pam" >
<option value=""></option>
<?php
$conn_string = "host=localhost port=5432 dbname=pame user=postgres password=";
$conn = pg_connect($conn_string);
$sql = pg_query($conn, "SELECT * FROM espece order by nom_com ASC ");
while($ligne_liste=pg_fetch_array($sql)) {
echo '<option value="'.$ligne_liste['id_espece'].'">'.$ligne_liste['nom_com']."</option>\n";
}
echo '</select>';
?>
The JS code I used :
jQuery(document).ready(function($) {
$('select.pam').change(function(){
$.post ('/charta.php',
{id_espece:$('select.pam').val()},
success: function(){
alert('success');
window.location = "http://localhost/charta.php";
}
);
});
});
My PHP file :
<?php
$user_id = isset($_POST["id_espece"])?$_POST["id_espece"]:"";
$user=conn ($user_id) // conn is a function who return an array from database
$js = json_decode( $user, true );
?>
<?php
echo json_encode($js); ?>
the problem here is I get "NULL" for the value of $_POST ('id_espece') even though the value selected from the dropdown list; but When I replace the success function with :
function(res){ $('#txt').html(res); }
It returnes the result i want (JSON output) in the <div id="txt"></div>
but not in the PHP file when it return an error that `
'undefined index : id_espece'`
The seccond step I want to GET the output of the same PHP file to HTML (div):
If we supposed that PHP file works and sent a JSON form I tried to GET the result in JS file like this :
$(document).ready(function(){ $.ajax({ url: "http://localhost/charta.php", method: "GET", success: function(data) { console.log(data); var region = []; var sup = []; for(var i in data) { region.push("region " + data[i].nom_reg_12); sup.push(data[i].aq); } var chartdata = { labels: region, datasets : [ { label: 'Superficie(m²)', backgroundColor: 'rgba(77, 214, 104, 0.75)', borderColor: 'rgba(77, 214, 104, 0.75)', hoverBackgroundColor: 'rgba(77, 214, 104, 1)', hoverBorderColor: 'rgba(77, 214, 104, 1)', data: sup } ] }; var ctx = $("#mycanvas"); var barGraph = new Chart(ctx, { type: 'bar', data: chartdata }); }, error: function(data) { console.log(data); } }); });
to be sure that the second step work fine , I replaced $_POST(['id_espece'])
with a default value and the PHP file return a JSON format not empty , so I think that the problem is in the first step , I don't know where is the problem exactly