hamed farhadi hamed farhadi -4 years ago 140
PHP Question

ajax response data is undefined

i have problem with ajax post submit
here is my script

function postad(actionurl) {
if (requestRunning) return false ;

if (! $("#editadform").valid()) {
return false ;

$('#ajxsave').show() ;
requestRunning = true ;
var postData = $('#editadform').serializeArray();
url : actionurl,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
$('#diverrors').html(data.errors) ;
$('#divalerts').html(data.alerts) ;

if (data.status=='success') { alert(data.status);
$('#siteid').val(data.siteid) ;
if ($('#adimager').val())
$('#divlmsg').html(data.alertimage) ;
$('#editadform').submit() ;

} else {

$('#ajxsave').hide() ;
error: function(jqXHR, textStatus, errorThrown)
$('#ajxsave').hide() ;
complete: function() {
requestRunning = false;

$('.btn').blur() // remove focus
return false ;

This works on
if (textStatus=='success') {

but when the action fails,
shows Undefined.

Using FireBug, I can see that the data is correctly returned. Why is data.status "Undefined" then?

Answer Source

If you don't specify the dataType field of an $.ajax() call in jQuery, it formats the response as plain text. A workaround to your code would be to either include dataType: "JSON" into your $.ajax() parameters, or alternatively, in your success function, parse the plain text response as a JSON object, by using the folllowing:

data = JSON.parse(data); // You can now access the different fields of your JSON object


yes i have not status field in action url, how to add data status field in php code?

When creating your PHP script that is intended to return the JSON data, you first need to build an array and then encode it as JSON.

So, suppose you have a PHP script that either succeeds and produces some data that you put into a $data variable, or fails, then the following style could be adopted:

    // ^^ Do your PHP processing here
    if($success) { // Your PHP script was successful?
        $response = array("status" => "success!", "response" => $data);
        echo json_encode($response);
    else {
        $reponse = array("status" => "fail", "message" => "something went wrong...");
        echo json_encode($response);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download