0

the problem is that the console.log('res', res) shows that res.message is a valid string (IMO) but when shown in an alert, it shows undefined. I also tried using typeof res.message and it also returns undefined.. why is that?

this is my code:

var myData = $('#myform').serializeArray();

$.ajax({
  url: '/test/test1',
  type: 'POST',
  data: myData,
  success: function(res) {
    if (res.status) {
      window.location.reload();
    } else {
      console.log('failed', res);
      // the content of res is like so:
      // {"status":"1", "message":"approval for \"Nominations\" was successful."}
      alert(res.message);
    }
  },
  error: function(err) {
    console.log('error', err.responseText);
  }
});
dapidmini
  • 1,490
  • 2
  • 23
  • 46
  • Please update your question with a [mcve] demonstrating the problem, something one can copy and paste locally to see the problem occur. – T.J. Crowder Nov 14 '19 at 10:20
  • 1
    This doesn't make any sense. If your `res.status` is "1" then it wouldn't go into the `else` part of your if-else to begin with, it would do the `window.location.reload()` bit. – TKoL Nov 14 '19 at 10:21
  • 2
    By far the most likely explanation is that `res` is a **string**, because the response doesn't have the correct `Content-Type` to tell jQuery to parse it as JSON. To solve, either 1. Update the server code to include the correct `Content-Type` with the response (`application/json`), or 2. (very much a second-best solution) Add a `dataType: "json"` option to the `ajax` call. – T.J. Crowder Nov 14 '19 at 10:22
  • Unless `res` isn't actually an object, but is in fact a JSON string, in which case `res.status` and `res.message` with both be undefined. – TKoL Nov 14 '19 at 10:22
  • @CertainPerformance - There may well be a duplicate for this, but [*that* one](https://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) seems like a **real** stretch, and jumping to a conclusion. – T.J. Crowder Nov 14 '19 at 10:26
  • @T.J.Crowder The problem is almost certainly, like you said, that the `res` is a JSON string and not an object, so trying to access properties on it doesn't work, so it seems to apply, though a more specific post can probably be found https://stackoverflow.com/questions/16935711/parsing-jquery-ajax-response – CertainPerformance Nov 14 '19 at 10:31
  • @CertainPerformance - Yup, that's an appropriate one, and a **very** good find. (I wish I could upvote dupehunting.) The other frankly wasn't, IMHO. – T.J. Crowder Nov 14 '19 at 10:46

0 Answers0