P. Lau
P. Lau

Reputation: 165

How To Output Json Data In AJAX

In native JS, I only know how to use AJAX to output result from PHP/mySql which is not Json Encode to the element "some_id"" like this:

<script>
function addItem(value) {
      xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function() {
          if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("some_id").innerHTML = xmlhttp.responseText;
                                                                }
                                                 }
      xmlhttp.open("GET","some_php.php?q="+value,true);
      xmlhttp.send();
                 }
</script>

But if the result of PHP/mySQL is Json Encoded, how do I output it to "some_id" in AJAX?

Upvotes: 1

Views: 537

Answers (3)

Danny Sofftie
Danny Sofftie

Reputation: 1051

Am assuming you have fetch your data from MySQL database. Lemme give an example with several fields.

yourdata.php

// after fetch data from MySQL
$data = new stdClass( );
$data -> email = $row['email'];
$data -> phone = $row['phone_number'];
$data -> age = $row['age'];
echo json_encode( $data );

Now in your file where you have Ajax,

var xhttp = new XMLHttpRequest( );
// the rest of your code here as you have implemented it
// where you get response.text , do this
var data = xhttp.responseText;
var myData = data.toString( );
var jsonObject = JSON.parse( myData );
// you can obtain each value from the json object
document.getElementById( 'divEmail' ).innerHTML = jsonObject.email;
document.getElementById( 'divPhone' ).innerHTML = jsonObject.phone;

The reason why you stringify data before parsing it in JavaScript, is because JavaScript tends not to understand json data encoded in PHP (my opinion), as doing this will give you an error in JavaScript

var myData = JSON.Parse( xhttp.responseText );

Am responding to this question as I travel, that's why you see a lot of comments in there, hope this helps.

Upvotes: 0

Chandrika Prasad Shah
Chandrika Prasad Shah

Reputation: 773

//some_php.php
$value = $_POST['value'];
echo json_encode($value);   //Convert data to json data


<script>
function addItem(value) {
    $.ajax({
        type: "POST",
        url: "some_php.php",
        dataType: 'json',
        data: {value: value},
        success: function(res) {
          console.log(res);   //res is in json, no need to convert it
        }
    });
}
</script>

Upvotes: 0

Blue
Blue

Reputation: 22911

Parse the json first with JSON.parse():

If your response looks like this:

{
    "response": "This is a test response"
}

Use something similar to this:

<script>
function addItem(value) {
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            //Convert from a string to a javascript object
            var json = JSON.parse(xmlhttp.responseText);
            document.getElementById("some_id").innerHTML = json.response;
        }
    }
    xmlhttp.open("GET","some_php.php?q="+value,true);
    xmlhttp.send();
}
</script>

Upvotes: 1

Related Questions