0

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)
            }
        })
    })
3
  • Have you tried debugging your code? Why not add something like console.log(data) to see what data contains? Commented Mar 24, 2018 at 9:34
  • 4
    should be data.data.category Commented Mar 24, 2018 at 9:35
  • Thank you so much Brother Your answer is helpful Commented Mar 24, 2018 at 9:37

3 Answers 3

1

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

Comments

0

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)
            }

Comments

0

Make it even simpler:

jQuery('#show')
.click(function() {
    jQuery
    .getJSON('example.com/api/product/1')
    .done(function(data) {
        jQuery('#result').text(data.data.category);
    }
});

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.