user3312792
user3312792

Reputation: 1111

Uncaught SyntaxError: Unexpected token +

I am getting this error using this code, the php id variable is set, why does it show unexpected token?

var current_page = 1;
var id = <?php echo $id; ?>;
$(document).ready(function(){ 
    $.ajax({
        'url':'get_data.php',
        'type':'post',
        'data': 'p='+current_page, 'id='+id,
        success:function(data){
            var data = $.parseJSON(data);
            $('#posts').html(data.html);
            $('#pagination').html(data.pagination);
        }
        console.log(data);  
    });
});

Upvotes: 2

Views: 536

Answers (3)

Kevin
Kevin

Reputation: 41885

You should concatenate the data query strings properly:

'data': 'p='+current_page +'&id='+id,

Or using this interface:

data: {p : current_page, id: id},

So it would look like this:

<script type="text/javascript">
var current_page = 1;
var id = <?php echo $id; ?>;
$(document).ready(function(){
    $.ajax({
        url: 'get_data.php',
        type :'POST',
        data: 'p='+current_page+'&id='+id,
        // data: {p: current_page, id: id},
        success:function(data){
            var data = $.parseJSON(data);
            $('#posts').html(data.html);
            $('#pagination').html(data.pagination);
            console.log(data);
        }
    });
});
</script>

Sidenote: You could also explicitly set dataType: 'JSON', so that you would not need $.parseJSON at all.

Upvotes: 2

roullie
roullie

Reputation: 2820

you can do it like this

data: {
    p: current_page, 
    id: id
}

Upvotes: 0

Bhumi Shah
Bhumi Shah

Reputation: 9476

Wrong syntax for data

replace with following

  'data': 'p='+current_page+'&id='+id,

Upvotes: 0

Related Questions