0

Hello i have a page can calla an ajax page in json with jquery. i just set

dataType: "json"

in ajax call and i set header in php

header("Content-type: application/json; charset=utf-8");

but when i try read my response in a client i have this error:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

var o = JSON.parse(jsonString);

For more information PHP file function:

function _addToWishlist($v,$db){   
$ris = array();
$data = array();    
$data[0]=20;
$data[1]=25;
$data[2]=30;    
$ris['stato']="1";    
$ris['mex']="DA IMPLEMENTARE!!!";
$ris['data']=$data;
$ris['action']="";
ob_clean();    
echo json_encode($ris);   
}

and thi is a php response:

{"status":"success","stato":"1","mex":"DA IMPLEMENTARE!!!","data":[20,25,30],"action":""}

in client i use this javascript:

$.ajax({
                url: "common/function/include/dataLoad.php",
                type: "POST",
                data: datas,
                async:false,
                //dataType: "text", 
                dataType: "json",
                success: function(ris) {
                        // Run the code here that needs
                        //    to access the data returned
                        //$(this).parent
                        //alert (ris);
                        risp=ris;
                       
                        //var a = JSON.parse(ris);
                        tryParseJSON(ris);
                        //return ris;
                },
                error: function() {
                        alert('Errore di rete');
                }

                }).done(function(){
                        if(divwhere!=""){                           
                                $(divwhere).html(risp);
                                }
                        if(actionAfter!=""){
                                eval(actionAfter);
                                }

            });

the function for test json is here: stackoverflow

how can i do for create a correct call json? thank you very much

Community
  • 1
  • 1
Valix85
  • 773
  • 1
  • 9
  • 20
  • Perhaps one of the PHP files involved generates output before your JSON response? – Jon Jan 21 '15 at 10:17
  • Use firebug (FF), or equivalent web developer tools for other browsers. There you can see the real response. – Marek Jan 21 '15 at 10:25

1 Answers1

2

jQuery will automatically parse a JSON response for you - you don't need to do it again. The returned ris object is ready for you to work with as-is. Assuming the request works, there is no problem with the format of your PHP response.

success: function(ris) {
    console.log(ris.status); // = 'success'
    console.log(ris.mex); // = 'DA IMPLEMENTARE!!!'
},
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • thank you very much! if i try a dataType text i can test if a response is a correct json. your answer work perfctly ;) – Valix85 Jan 21 '15 at 10:38