简体   繁体   中英

Unexpected token C in JSON at position 0 when passing array from php to ajax

I am trying to send array from php to ajax in json file but when i alert res var for testing it i see this error message :

Uncaught SyntaxError: Unexpected token C in JSON at position 0

My array is this :

["C", "Dbm", "Bb", "Bb", "F", "Cm", "Eb", "Dbm", "Bb", "Bb", "F", "Cm", "F", "Bb", "Eb", "Bb", "F",…]

My array created by php function and array item's will different when user clicking on a button in view .

Java Script :

$(".T-chords").on('click',function(event){

    event.preventDefault();
    var This = $(this);
    $.ajax({

        url : data.ajax_url,
        type : 'post',
        dataType: 'json',
        data : {

            action : 'transpose_callback',
            content : data.content,
            target_scale : This.text(),
            base_scale : data.base_scale,
        },

        success:function(response){

            var res = JSON.parse(response);
            alert(res[1]);

        },

        error: function(){

            alert("err");

        }


    })

})

php code :

function Ajax_transpose_callback(){
    header('Content-Type: application/json');
    $content = $_POST['content'];
    $Target_Scale = $_POST['target_scale'];
    $Base_Scale = $_POST['base_scale'];
    $Flag_db = "";
    $transposed_chord = "";
    $transposed_arr = array();

    if(preg_grep('/#/', $content)){
        $Flag_db = "0";
    }
    elseif (preg_grep('/b/', $content)){
        $Flag_db = "1";
    }
    else{
        $Flag_db = "0";
    }

    foreach ($content as $item) {

        $final_item = substr( $item, 1, - 1 );
        $transposed_arr[] = Transpose( $Flag_db, $Base_Scale, $Target_Scale, $final_item );

    }
    wp_die(json_encode($transposed_arr));
}

This is either because you are parsing a already parsed object. Try to remove var res = JSON.parse(response); and change it to var res = response;

You could fixed it either in 2 way, 1) Replace var res = JSON.parse(response); alert(res[1]); With var res = response; alert(res[1]);

because here you will get an array, instead of an JSON Object. 2) Or you could pass an associative array here

$transposed_arr = array("c"=>"C", "Dbm"=>"Dbm","Bb" =>"Bb");
     json_encode($transposed_arr)

An associative array will product a JSON object, on which you could apply

 var res = JSON.parse(response);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM