I want to extract JSON data from laravel using JQUERY but the result is always undefined.
this is the json code I've got:
{"data":{"id":1,"title":"glove hard","code":"0102","category":"glove"}}
and this is the js code:
$('#show').click(function(){
$.ajax({
url: 'example.com/api/product/1',
method: 'GET',
dataType: 'json',
success: function(data){
$('#result').text(data.category)
}
})
})
Use the $.parseJSON which parse the well formatted json string into js object. Your success callback will be
success: function(data){
var obj = $.parseJSON(data);
$('#result').text(obj.data.category)
}
Since your code return JSON data is
{"data":{"id":1,"title":"glove hard","code":"0102","category":"glove"}}
The ajax success function parameter is called data and the first key in the json result is named data, to access the value of category, your code should be
$('#show').click(function(){
$.ajax({
url: 'example.com/api/product/1',
method: 'GET',
dataType: 'json',
success: function(data){
//Call the first wrapper key first.
$('#result').text(data.data.category)
}
})
})
Make it even simpler:
jQuery('#show')
.click(function() {
jQuery
.getJSON('example.com/api/product/1')
.done(function(data) {
jQuery('#result').text(data.data.category);
}
});