Nick
Nick

Reputation: 169

Convert json result to PHP

In my example I have 2 pages. What I basically want is to pass some data (or not like in this example) with JSON to PHP. In PHP I query a select statement and pass that data back to my index page.

Now that all goes well, but then I want the returned data showed in different div's.

My index page:

function toonProfiel(){
  $.ajax({
  type: "GET",
  url: "./query/getmijnprofiel.php",
  dataType: 'json',
  success: function ( response ) {
    alert( response.a);
  }
  });
}

In this example 'a' get's alerted! All is working fine!

My getmijnprofielphp page:

<?php

session_start ();

require '../php/connect.php';

$id = $_SESSION['id'];

if ($stmt = $mysqli->prepare("SELECT a, b FROM leden WHERE userid=?")) {

    /* bind parameters for markers */
    $stmt->bind_param("i", $id);

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($a, $b);

    /* fetch value */
    $stmt->fetch();

    $response = array(
      'a' => $a,
      'b' => $b,
    );

    echo json_encode( $response );

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();

?>

But what I want is the following:

<div class="diva">
  <label>a:</label>
  <span><?php if ($a!= "") { echo $a; } ?></span>
</div>

I know the returned data isn't a PHP variable so this doesn't work, but how can I show the returned variable 'a' in my div?

Upvotes: 0

Views: 107

Answers (2)

klickagent.ch
klickagent.ch

Reputation: 559

<div class="diva">
  <label>a:</label>
  <span id="response"></span>
</div>

you need to add the data you receive to the dom using javascript as well:

document.getElementById('response').innerHTML = response.a;

Upvotes: 0

Sumit Gupta
Sumit Gupta

Reputation: 2192

change your success message as

$(".diva span").html(response.a);

This will change HTML at runtime using jQuery. I also suggest to put some ID on span and use that instead of generic class.

Upvotes: 2

Related Questions