user838437
user838437

Reputation: 1501

jQuery post not working, data not defined

Trying to execute this:

function getReport(name) {
    $.ajax({
        type: "POST",
        url: "reportAjax.php",
        data: "name="+ name,
        success: function(data){
            var json = $.parseJSON(data);                
        }
    }); 
    alert(data);
}

$(document).ready(function() {
    getReport('mobileDevicesBreakdown_30days');
});

I'm getting data is not defined

reportAjax.php is definitely available and always return something (even if the variables that are sent to it - currently name is incorrect or missing).

Upvotes: 0

Views: 4257

Answers (3)

Michael Laffargue
Michael Laffargue

Reputation: 10294

.ajax is an asynchronous method, so your alert(data) should be in the success part of the .ajax

Upvotes: 1

Josh Mein
Josh Mein

Reputation: 28645

If you are trying to alert the data it needs to be within your success call

function getReport(name) {
    $.ajax({
        type: "POST",
        url: "reportAjax.php",
        data: "name="+ name,
        success: function(data){
            var json = $.parseJSON(data);                
            alert(data);
        }
    }); 

}

Upvotes: 0

Richard Dalton
Richard Dalton

Reputation: 35793

Move alert(data); inside the success callback:

function getReport(name) {
    $.ajax({
        type: "POST",
        url: "reportAjax.php",
        data: "name="+ name,
        success: function(data){
            alert(data);
            var json = $.parseJSON(data);                
        }
    });     
}

Upvotes: 3

Related Questions