Liam Dawe Liam Dawe - 1 month ago 10
Javascript Question

jquery ajax request returns undefined

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.

Answer

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);
...