Convert JSON TO JAVASCRIPT and add data to HTML OR php Variable

In this tutorial learn how to convert JSON data using json.parse method to javascript, and How to convert to JSON to JavaScript and store to html, and also let's discuss with with JavaScript variable to store to PHP variable.

STEP 1.  JSON DATA to store javascript variable

var txt = '{"name":"Jack", "age":30, "city":"London"}'



STEP 2. Convert to text using JSON.parse() method.

  var obj = JSON.parse(txt);

STEP 3. Get value of JSON data example, here get value of name, age and city using var obj

  alert(obj.name + ", " + obj.age + ", " + obj.city);

STEP 4. Now add data to HTML div tag 

  document.getElementById("demo").innerHTML = obj.name + ", " + obj.age + ", " + obj.city;

EXAMPLE

<html>
<body>
  <h3>Convert JSON TO JAVASCRIPT and Store to HTML</h3>
  <p id="demo"></p>
<script>
  var txt = '{"name":"Jack", "age":30, "city":"London"}'
  var obj = JSON.parse(txt);
  document.getElementById("demo").innerHTML = obj.name + ", " + obj.age + ", " + obj.city;
</script>
<h3> Convert JSON TO JAVASCRIPT and Store PHP Variable</h3>
<?php echo "name =" . "<script>document.write(obj.name)</script>";
 ?>
 <?php echo ","."City =" . "<script>document.write(obj.city)</script>";
  ?>

</body>
</html>


No comments:

Post a Comment

how to call ssh from vs code

 To call SSH from VS Code, you can use the built-in Remote Development extension. This extension allows you to open a remote folder or works...