Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return JSON data from an AJAX call

Tags:

jquery

ajax

I have a JSON object I am returning from the database. It is formatted correctly. I am trying to access the data in it with an AJAX call. Here is my AJAX.

$.ajax({
        url: '<?php echo site_url('find_representatives/find_rep_by_address/get_coordinates'); ?>', 
        dataType: 'json',
        data: '',
        success: function(data, status, xhr) {
             alert(data);
        },
        error: function(xhr, status, error) {
             alert(status);
        }
});

I have '' in my data because I am looking for all of the data. I tried putting 'id' there (there is an ID in my JSON object, but the function stopped working when I did that. When I alert 'data' I get an object, but where I alert 'data.id' I get 'undefined.' What am I doing wrong? This is my first AJAX call. The URL is valid. I checked.

like image 941
sehummel Avatar asked Oct 20 '25 16:10

sehummel


1 Answers

data: '{}', 

This sends an empty data object to the server and works around some issues where sending empty data (not including the data at all) causes issues.

One other thing I have seen is not setting:

contentType: "application/json",

One easy way to "debug" data visually is to include json2.js and do (in the success function):

alert(JSON.stringify(data));
like image 144
Mark Schultheiss Avatar answered Oct 23 '25 06:10

Mark Schultheiss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!