MultiformeIngegno
MultiformeIngegno

Reputation: 7059

Print $.post response

I have a simple web page with some option 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's richiesta.php (called from the $.post function):

<?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 fine. In Firebug I can see the request made from richiesta.php using the data gathered from POST is returned correctly.

enter image description here

I just can't find out how to print the response I see in Firebug on 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 I get [object Object], not the JSON.

Upvotes: 4

Views: 1005

Answers (2)

Priyank
Priyank

Reputation: 3868

Just use JSON.stringify.For More Details

$('#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 );
});

});

Upvotes: 0

jeroen
jeroen

Reputation: 91742

As you have specified that the returned data is json (using dataType: 'json'), jQuery has already parsed it so it is not a string anymore, it is an object.

If you want to see it as a json string in your #textfield, you would have to convert it to a string again:

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

Upvotes: 4

Related Questions