1

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?

1
  • If it's JSON encoded - decode first. Use JSON.parse for it Commented Jun 12, 2017 at 3:12

3 Answers 3

1

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>
Sign up to request clarification or add additional context in comments.

Comments

0
//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>

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.