Print response $ .post

I have a simple web page with some parameter tags:

<!DOCTYPE HTML>
<html>
<head>
<title>Test</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<form>
<label>Seleziona l'ente</label>
<select name="data" id="data">
    <option value="PRO - 011142764">COMUNE DI AGLIE'</option>
    <option value="PRO - 011120674">COMUNE DI AGRATE CONTURBIA</option>
</select>
<input type="text" name="textfield" id="textfield" />
</form>

<script>
$('#data').change(function() {
    $.post("richiesta.php", { value: this.value });
    $('#textfield').val(this.value);
});
</script>
</body>
</html>

      

Here richiesta.php

(called from within a function $.post

):

<?php

function soldipubblici() {
    list($comparto, $ente) = explode("-", $_POST['value'], 2);

    $curl_parameters = array(
        'codicecomparto'    =>  trim($comparto),
        'codiceente'        =>  trim($ente),
    );

    $ch = curl_init();

    curl_setopt($ch,CURLOPT_URL,"http://soldipubblici.gov.it/it/ricerca");
    curl_setopt($ch,CURLOPT_POST,true);
    curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query( $curl_parameters ));
    curl_setopt($ch,CURLOPT_HTTPHEADER,array (
        "Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
        "Accept: application/json",
        "X-Requested-With: XMLHttpRequest",
    ));

    $output=curl_exec($ch);

    curl_close($ch);
}

echo soldipubblici();

?>

      

Everything works perfectly. In Firebug I can see that a request made from richiesta.php using data collected from POST is returning correctly.

enter image description here

I just can't figure out how to print the response I see in Firebug on the screen (or in the input tag). I tried something like:

$('#data').change(function() {
    $.ajax({
      url: 'richiesta.php',
      type: 'POST',
      dataType: 'json',
      data: {value: this.value},
    }).done(function ( data ) {
      $('#textfield').val(data);
    });
});

      

The request still works, but in #textfield

what I am receiving [object Object]

, not JSON.

+3


source to share


2 answers


As you pointed out that the returned data is json (using dataType: 'json'

), jQuery has already parsed it so that it is no longer a string, it is an object.

If you want to see it as a json string in #textfield

, you'll have to convert it to string again:



$('#textfield').val(JSON.stringify(data));

      

+3


source


Just use JSON.stringify . More information ...

$('#data').change(function() {
$.ajax({
  url: 'richiesta.php',
  type: 'POST',
  dataType: 'json',
  data: {value: this.value},
}).done(function ( data ) {
  var simpleData = JSON.stringify(data);
  $('#textfield').val(simpleData );
});

      



});

0


source







All Articles