JulianJ JulianJ - 1 month ago 6
Ajax Question

Getting JSON data with jquery ajax not working

I'm trying to understand how to fetch and display data with jquery ajax. I have a php page

(data.php)
that successfully retrieves data from a mysql database and encodes that data into a json array. Client side I have a page called
get.php
. I just can't figure out why my script will not fetch any data from
data.php
I get nothing in the firebug console.

data.php

echo json_encode($mydata);
which outputs:
[
{
"id":"236",
"title":"The Jungle Book"
},
{
"id":"235",
"title":"The Shallows"
},
{
"id":"232",
"title":"For Your Eyes Only"
},
{
"id":"231",
"title":"Ice Giants"
}
]


get.php

<script>
("button").click(function(){
{
$.ajax({
url: 'data.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
var title = data[1];

$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});
});
</script>

<h3>Output: </h3>
<button>Get Data</button>

<div id="output"></div>

Answer

You have few mistake like: you didn't specify jquery($) for button selector, you use multiple bracket { inside click function, inside ajax success you have assigned full object against id and title it should be id=data[0]['id'] and title=data[0]['title] and another mistake there no defined variable vname. php better json output you should use header('Content-Type: application/json'); in data.php.

Try this:
index.php

<h3>Output: </h3>
<button>Get Data</button>
<div id="output"></div>
<script   src="https://code.jquery.com/jquery-2.2.4.min.js"   integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="   crossorigin="anonymous"></script>
<script>
    $("button").click(function(){
        $.ajax({                                      
          url: 'data.php',                       
          data: "",                       
          dataType: 'json',                    
          success: function(data){
            //console.log(data);
            var id = data[0].id;             
            var title = data[1].title;           
            $('#output').html("<b>id: </b>"+id+"<b> name: </b>"+title);
          } 
        });
      }); 
</script>

data.php

<?php 
 header('Content-Type: application/json'); //use header to specify data type
 //echo json_encode($mydata); // un-comment this line
 echo '[{"id":"236", "title":"The Jungle Book"}, {"id":"235", "title":"The Shallows"}, {"id":"232", "title":"For Your Eyes Only"}, {"id":"231", "title":"Ice Giants"} ]'; // comment this line
?>
Comments