0

I am trying to have a link perform a really simple, request, but I can't seem to figure out why what I returned is "undefined".

Currently the link does a manual page request, but it's such a simple subscription thing, I want it to not refresh the page (hence the preventDefault). But if the JS doesn't work or it's blocked, the link should do a normal page request (best of both worlds?).

Here is the JS that captures the click on a link

  $('#subscribe-link').click(function(e)
  {
    e.preventDefault();
    var type = $(this).data('sub');
    $.post('/includes/ajax/subscribe-article.php', { 'type':type },
    function(data)
    {
      alert(data.result);
      if (data.result == 'subscribed')
      {
        alert('subscribe');
      }
      else if (data.result == 'unsubscribed')
      {
        alert('unsubscribe');
      }
    });
  });

And here is the PHP that feeds it:

if($_POST && isset($_SESSION['user_id']) && $_SESSION['user_id'] != 0)
{
  if (isset($_POST['type']))
  {
    if ($_POST['type'] == 'subscribe')
    {
      echo json_encode(array("result" => "subscribed"));
      return;
    }

    if ($_POST['type'] == 'unsubscribe')
    {
      echo json_encode(array("result" => "unsubscribed"));
      return;
    }
  }
}

Now, I've checked what "data" returns by itself which is this:

{"result":"unsubscribed"}

Which is correct, I'm not sure what I'm missing this time.

2 Answers 2

2

As the variable data contains the JSON representation of your expected result, it is plainly a String. Yet you try and access information contained in that string as an object. For this to work, you first need to create an object from the string by decoding the returned JSON:

var myData = JSON.parse(data);
alert(myData.result);
...
Sign up to request clarification or add additional context in comments.

2 Comments

dataType: "json" might also help
Ah interesting thanks, I was previously using this exact same method, but returning numbers instead of text, so I guess it's picked up differently.
0

You need to parse the result as JSON. IE, data_array=JSON.parse(data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.