ravisingh
ravisingh

Reputation: 272

Print a json file from php into javascript

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
$.getJSON('getfile.php', function(data) {
alert(data);
});
});

</script>
</body>
</html>

my php file-->getfile.php

<?php
$json='{"info":{"name":"ram","lname":"katara"}}';
$json = json_decode($json,true);
print_r($json);
?>

my output is-->

Array ( [info] => Array ( [name] => ram [lname] => katara ) )

How can i print this json data into my html page using javascript or ajax jquery.

Upvotes: 1

Views: 98

Answers (3)

meda
meda

Reputation: 45490

It is the opposite you would do normally, take PHP objects and encode them into JSON.

php

$data=array('info'=>array('name'=>'ram',
                         'lname'=>'katara'
           ));
$json = json_encode($data);
echo $json; //{"info":{"name":"ram","lname":"katara"}}

Js

<script type="text/javascript" language="javascript">
$(document).ready(function() {
  $.getJSON('getfile.php', function(json) {
     $('#print').html('<p>First Name: ' + json.info.name + '</p>');
     $('#print').append('<p>Last Name : ' + json.info.lname + '</p>');
  });
});
</script>

<div id="print"></div>

Upvotes: 1

MixedVeg
MixedVeg

Reputation: 319

Yes AJAX query is a way to ask for data from a php file on the server to a HTML file.

The simplest POST AJAX query structure is below (you can use GET also):

$.POST("getfile.php",function(data) { 
    if(!data) {
       alert("No data received"); }
    else {
       $("YourOutputDivfromHTML").innerHTML += ......; //what ever to display from the response
       // or alert();

});

In the php file you should:

echo json_encode($json);

Upvotes: 0

Ayub
Ayub

Reputation: 510

If i understood your question correctly, you want to put value of a php variable into javascript. For that, follow this:

Define your $json as global variable, at the top.

And in the Javascript:

<script> 

  var json = <?php echo $json; ?> ;   

</script>

Edit: You need to json_encode($json); instead of json_decode() ... this should output in correct format, then you can alert in Javascript however you like.

Upvotes: 0

Related Questions