Issam
Issam

Reputation: 45

Use Ajax to POST and GET in the same PHP file (JSON)

I'm trying to reach for a result passing by two steps :

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'`

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

Upvotes: 1

Views: 546

Answers (2)

Hugo sama
Hugo sama

Reputation: 909

Edited : Taken from here it seems you are sending a JSON format to the PHP so it can't parse it on $_POST, you need to get the complete body.

try this :

$data = json_decode(file_get_contents('php://input'), true);
print_r($data);

Upvotes: 0

Jay Blanchard
Jay Blanchard

Reputation: 34426

In order to get a form element in the $_POST array it must have a name attribute. Change your select element to have a name:

<select class="pam" name="id_espece">

In addition $.post doesn't have a success function as you have written it. The format should be this:

$.post ('/charta.php',
    {id_espece:$('select.pam').val()},
    function(data){  
          console.log(data);
          window.location = "http://localhost/charta.php";
    });

Upvotes: 1

Related Questions