0

I'm having problems sending a JSON jQuery array via Ajax to a PHP script. What is the problem here:

var tee = $('#voting_image img').attr('id');
var vote = 1;
var thing = {tee: tee, vote: vote};
var encoded = $.toJSON(thing);

$.ajax({
    url:             '/vote_save.php',
    type:            'POST',
    dataType:        'json',
    data:            'vote='+encoded,
    success: function(data)
    {
        var back = $.evalJSON(data).name;
        $('#voting_hint_name').html(back);
        $('#voting_buttons').html('<div id="voting_buttons"><a href="#" id="vote_yes">PRINT IT</a><a href="#" id="vote_no">DON\'T PRINT IT</a></div>');
    },
    error:function ()
    {
        $('#voting_buttons').html('<div id="voting_buttons"><a href="#" id="vote_yes">PRINT IT</a><a href="#" id="vote_no">DON\'T PRINT IT</a></div>');
        alert("There was a problem, your vote was not saved, please try again!");
    }
});

This is the PHP

if (isset($_POST['vote'])&&isset($_SESSION['user']))
{
    $tee_data = json_decode($_POST['vote']);
    $the_tee = $tee_data['tee'];
    $responce = array('name'=> 'Alex Wow', 'test'=> '1');
    echo json_encode($responce);
}
else {
    echo "error";
}

The error I am getting in Firebug is:

Error: JSON.parse

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Titan
  • 5,567
  • 9
  • 55
  • 90

4 Answers4

0

AFAIK, there is no $.toJSON method in jQuery, you are probably looking for $.parseJSON and by the way you are already creating JSON here:

var thing = {tee: tee, vote: vote};
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
0

I think the problem is that you send data as object, try to send as array var thing = {tee: tee, vote: vote}; to array

Centurion
  • 5,169
  • 6
  • 28
  • 47
0

Check out this question: Serializing to JSON in jQuery

The accepted answer links to a JSON serialization plug-in recommended by John Resig (the creator of jQuery). It doesn't really address your specific bug, but perhaps using that plug-in will help you arrive at a stable solution.

From looking at it briefly, if you use that plug-in, it appears you would then replace this line:

var encoded = $.toJSON(thing);

with this:

var encoded = JSON.stringify(thing); 

Hope that helps!

Community
  • 1
  • 1
Ender
  • 14,995
  • 8
  • 36
  • 51
0

Thanks for your responces, I went with:

$.getJSON(
            '/vote_save.php?vote='+encoded,
            function(data) 
            {
                $('#voting_hint_name').html(data.bob);
                $('#voting_buttons').html('<div id="voting_buttons"><a href="#" id="vote_yes">PRINT IT</a><a href="#" id="vote_no">DON\'T PRINT IT</a></div>');
            }   
    );

instead of $.ajax and it worked.

Titan
  • 5,567
  • 9
  • 55
  • 90