Creek Barbara
Creek Barbara

Reputation: 647

Ajax/JQuery: Can't read the data returned (undefined)

I'm trying to log the JSON data returned in the code below and it always returns as undefined in the console.

  $.ajax({
    url:"campcpcedit.php",
    method:"POST",
    data:{platform:platform, btnid:btnid, newcpc:newcpc},
    success:function(data){
      if (data.success) {
            myAlertTop();
            changeBid(_btn);
        }
        else {
            myAlertBottom();
            console.log(data.message);
        }
    }
  });

The JSON response is this:

{"success":false,"message":"Error"}

The code to generate it in campcpcedit.php:

  if($conn->query($upquery) === TRUE && $apiSuccess == "1") {
      echo json_encode(array('success' => true));
  }
  else{
      echo "Error: " . $upquery . "<br>" . $conn->error;
      echo json_encode(array('success' => false, 
                             'message' => "Error")
                 );
        }

The if (data.success) is working as the 2 functions myAlertTop() and myAlertBottom() are firing properly. I can't find what I'm doing wrong.

Upvotes: 0

Views: 70

Answers (2)

freefaller
freefaller

Reputation: 19953

I'm surprised to hear that the solution was to use the following...

console.log(jQuery.parseJSON(data).message);

I believe the reason it is failing is because your PHP is returning the following example string back to the client, which the client can't convert to an object (which the $.ajax will try and do by default).

Error: XXX<br>xxx{"success":false,"message":"Error"}

var jsonReturn = 'Error: XXX<br/>xxx{"success":false,"message":"Error"}';
console.log(jQuery.parseJSON(jsonReturn).message);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Instead, what I suggest is that you remove the first echo from your PHP, and instead add a new item to your array...

// echo "Error: " . $upquery . "<br>" . $conn->error;
echo json_encode(array('success' => false, 
                       'message' => "Error",
                       'error' => $upquery . "<br>" . $conn->error));

That should result in a properly formed JSON string which can be parsed, meaning that the data variable in success:function(data) is the object you're expecting...

{"success":false,"message":"Error","error":"XXX<br>xxx"}

var jsonReturn = '{"success":false,"message":"Error","error":"XXX<br/>xxx"}';
console.log(jQuery.parseJSON(jsonReturn).message);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Creek Barbara
Creek Barbara

Reputation: 647

The problem was that I have to parse the JSON response.

console.log(jQuery.parseJSON(data).message);

Upvotes: 0

Related Questions