0

I want to post a value from a dropdown list to a php file with JSON_encode using $_POST Ajax.

I tried this script :

   jQuery(document).ready(function($) { 
      $('select.pam').change(function(){
          $.ajax({
        type: 'POST',
        url: '/charta.php',
        dataType:'json',
        data: { id_espece:$('select.pam').val()},
        success: function(output) {
                  alert(output);
              },
    });
          });
    });

and this is where I want to post it :

<?php   $id =  $_POST['id_espece'];
        $cars =  abv($id);
         print json_encode($cars);

But I get :

Notice: Undefined variable: cars in C:\wamp64\www\charta.php on line 39

to be sure that the JSON file is correct I replaced $_POST['id_espece'] with a default value and it works , but whene I attached it to the select box I get the error .

Issam
  • 45
  • 8
  • 2
    What is `abv()`, did you mean `abs()` – RiggsFolly Jul 12 '17 at 19:08
  • @RiggsFolly You can have JSON encodings of scalars. – Barmar Jul 12 '17 at 19:12
  • @Barmar Yes it does something but it does not create a valid JSONString, at least not in my test – RiggsFolly Jul 12 '17 at 19:12
  • [Have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there any errors reported? Are you running this on a web-server?](http://jayblanchard.net/basics_of_jquery_ajax.html) – Jay Blanchard Jul 12 '17 at 19:12
  • @RiggsFolly The JSON specification has been expanded to include JSON strings that represent scalars, not just objects and arrays. – Barmar Jul 12 '17 at 19:13
  • @RiggsFolly E.g. `JSON.parse("123")` returns `123`. – Barmar Jul 12 '17 at 19:14
  • @Barmar Yea maybe, but `$cars = '123'; print json_encode($cars);` just outputs `123` which I believe is not a valid JSONString and not therefore a javascript object – RiggsFolly Jul 12 '17 at 19:15
  • @RiggsFolly Right. Then that becomes the string `"123"` when read on the client, and it parses to the number `123`. So the right thing happens. – Barmar Jul 12 '17 at 19:16
  • @Barmar Even when `dataType:'json'`? – RiggsFolly Jul 12 '17 at 19:16
  • @RiggsFolly Yes. That just tells jQuery to automatically do `output = JSON.parse(xhr.responseText);` – Barmar Jul 12 '17 at 19:18
  • @Barmar Ok, thanks, another good day, I have reduced my ignorance level :) – RiggsFolly Jul 12 '17 at 19:19
  • Check your error log you should see `Fatal error: Uncaught Error: Call to undefined function abv()` – RiggsFolly Jul 12 '17 at 19:22
  • @RiggsFolly it's not an undifined function, it's a function I used to ceat the connexion to the database . Anyway it's not the problem because Like I said whene I replace $_POST with a default value I got My Json Output ... Thank you for tour answers – Issam Jul 12 '17 at 20:21

0 Answers0