Maarten Kuijper
Maarten Kuijper

Reputation: 354

Ajax dataType Json, can't get my data to be send correctly.

In my frame I have this working ajax request, 'reorder_rows' triggers a function which echo's 'function reached!'.

var data = {};
data['reorder_rows'] = 'test';
data['token'] = $('input[name="token"]').val(); //req to pass

$.ajax({
    url:'',
    method:'post',
    data:data,
}).done(function(data){
    console.log(data);
});

//php
public function newRowOrder(){
    echo 'function reached!';
}

But when I try sending more data using json datatype I'm not getting a response anymore, after checking for what went wrong $_POST['reorder_rows'] & ['token'] doesn't seem to be set. Basically the call triggers nothing. What I was trying to do is the following:

var new_order = [];

$('.sortable').children().each(function(i){
    new_order.push({
        'id':$(this).data('id'),
        'val':parseInt($(this).find('.overview-number').val()),
    });
});

var data = {
    'reorder_rows': new_order,
    'token': $('input[name="token"]').val(),
};

$.ajax({
    url:'',
    method:'post',
    dataType: 'json',
    data:data,
}).done(function(data){
    console.log(data);
}); 

All I need to go on is to get the post var 'reorder_rows' to be set properly, but honestly the code above smells a bit fishy to me.. objects into and array into an object?

I've used Json before and the sending/receiving went fine, including all the encoding/decoding stuff. But it didn't involve such data arrays. Here is a working example...

data['id'] = $('#id').val(); //used to exclude current item in double checks
data['form_checks'] = "";
data['token'] = $('input[name="token"]').val();

$.ajax({
    url:'',
    method:'post',
    dataType:'json',
    data:data,
    success: function(data){
        //stuff here is being done
    }
});

Anyone knows how I can send the data from my overview rows? I need each row's ID and (old) order number. The rows are already ordered in the html when my function triggers

Upvotes: 0

Views: 339

Answers (1)

Barmar
Barmar

Reputation: 780688

Use json_encode() in the PHP code to return JSON:

public function newRowOrder() {
    echo json_encode("function reached!");
}

Upvotes: 1

Related Questions