1

Here's my ajax call:

    $.ajax({
        url : hostGlobal + "site/modulos/prefeitura/acoes-jquery.php",
        type: "POST",
        dataType : "JSON",
        data: {
            acao: "filtrarCidades",
            estado_id: $(".estados:chosen").val()
        },
        success: function(json) {
            console.log("worked");
            $(".cidades").html('');
            var options = "<option value=\"\"></option>";
            $.each(json, function(key, value) {
               options += '<option value="' + key + '">' + value + '</option>';
            });
            $(".cidades").html(options);
            if (!filterThroughCEP) { 
                $(".cidades").trigger("chosen:updated"); 
            }
        },
        error: function(e) {   
            console.log(e.responseText);
        }
    });

Here's the php action:

if ($acao == 'filtrarCidades') {
    $estado_id = $_POST['estado_id'];
    $cidade->where = "estado_id = '".$_POST['estado_id']."'"; 
    $cidade->LoadFromDB();
    for ($c=0; $c<count($cidade->itens); $c++) {
        $cidades[$cidade->itens[$c]->id] = $cidade->itens[$c]->nome;
    }
    echo json_encode($cidades);
    die();
}

json_encode($cidades) is valid json data (UTF8), here's one example using debug:

{"1778":"Bras\u00edlia"}

This {"1778":"Bras\u00edlia"} goes as e.responseText (Error), even with Status OK, and the URL is on the same domain (No need for JSONP). I have no idea why I can't reach success.

EDIT: I've set the contentType:

contentType: "application/json",

And the call still can't "reach" success. Here's the third error argument:

SyntaxError: Unexpected token 
    at parse (native)
    at ajaxConvert (http://localhost/sisconbr-sistema-novo/site/visual/js/jquery.js:7608:19)
    at done (http://localhost/sisconbr-sistema-novo/site/visual/js/jquery.js:7363:15)
    at XMLHttpRequest.<anonymous> (http://localhost/sisconbr-sistema-novo/site/visual/js/jquery.js:7835:9)

It is indeed related to unicode characters inside the strings that come from the database.

EDIT2: I wrote the whole thing again, and now it's clearer:

function getCitiesByState() {
    $.ajax({
        url : hostGlobal + "site/estrutura/ajax.php",
        type: "POST",
        dataType : "text",
        data: {
            action: "getCitiesByState",
            state_id: $(".estados option:selected").val()
        },
        success: function(json, textStatus, jqXHR) {
            console.log($.parseJSON(json));
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(errorThrown); 
        }
    });
}

PHP:

if ($_POST["action"] == "getCitiesByState") {
    $cities = getResults("SELECT * FROM tbl_cidades WHERE estado_id = ".$_POST["state_id"]);
    echo json_encode($cities, JSON_UNESCAPED_UNICODE);
    die();
}

Output:

[{"id":"1778","estado_id":"7","nome":"Brasília","cep":"","loc_no_abrev":"Brasília"}]

Error:

Uncaught SyntaxError: Unexpected token 
Ericson Willians
  • 7,606
  • 11
  • 63
  • 114
  • What are the rest of the properties of `e`? – TbWill4321 Dec 08 '15 at 17:40
  • 1
    You are undoubtedly vulnerable to [sql injection attacks](http://bobby-tables.com), and stop assuming success. jquery has a `error` parameter for ajax requests - if success isn't being reached, then check for errors. – Marc B Dec 08 '15 at 17:40
  • The error handler you are using has three arguments. Log the 3rd one for us. – Kevin B Dec 08 '15 at 17:43
  • Set the headers so it can be converted to JSON object properly, headers of response. header('Content-Type: application/json'); – Senad Meškin Dec 08 '15 at 17:43
  • @SenadMeškin not required if he's using dataType. – Kevin B Dec 08 '15 at 17:44
  • @KevinB Would uppercase `dataType` `"JSON"` affect response ? – guest271314 Dec 08 '15 at 17:45
  • yes it is, dataType is just so jQuery knows it should convert it to JSON, but if headers are not set then it can throw exception, I had problem with it. – Senad Meškin Dec 08 '15 at 17:45
  • no, i doubt the uppercase would affect it. This is most likely either a case of jQuery assuming JSONP for some reason, or the response containing more than just the json, such as a hidden character. – Kevin B Dec 08 '15 at 17:46
  • 1
    Try to get rid of 'die()' – Franco Dec 08 '15 at 17:47
  • Could try setting `dataType` to `"text"` , convert to `JSON` at `success` ? – guest271314 Dec 08 '15 at 17:47
  • setting the client-side contentType isn't what he meant. (or if it was, it was incorrect, you want the default contentType for clientside since you are sending form params.) – Kevin B Dec 08 '15 at 17:49
  • so... the 3rd argument contains the responsetext too? i've never seen that before... that should contain error text, for example, "parseerror" or simply "error" – Kevin B Dec 08 '15 at 17:50
  • I've tried to set the dataType to text and convert the result to JSON as suggested (jQuery.parseJSON(json)), and now I get a syntax error. [I suppose this is the problem (UTF8).](http://stackoverflow.com/a/16456769/1795924) – Ericson Willians Dec 08 '15 at 17:53
  • Not directly, but I mean the '\' character. The data comes with unicode characters. – Ericson Willians Dec 08 '15 at 17:56
  • Yes, that's very well could be the cause. I think i clicked on your link before you fixed it to point directly to a specific answer. – Kevin B Dec 08 '15 at 17:57
  • I've managed to output the third argument correctly. I've edited the question again. – Ericson Willians Dec 08 '15 at 18:04
  • Can you do a `curl -v -d 'acao=filtrarCidades&estado_id=whateveriditshouldbe' 'urlofyourscript'` and report the output? – jcaron Dec 08 '15 at 18:18
  • Can you run the same thing in a different browser? Safari for instance would tell you what the unexpected token is... – jcaron Dec 08 '15 at 18:40
  • My opinion is that you have something else than the JSON in the output of your PHP script. Possibly something not visible at first sight (like a BOM, an unbreakable space...). Run the `curl` command above and pipe it into `hexdump -C` to check for it. Or save it to a file and open it with a decent text editor like `vi`. – jcaron Dec 08 '15 at 23:56

1 Answers1

-2

I think that the problem is the object property {"1778":"Bras\u00edlia"} means an object with an invalid property name, thus json decoding fails; to prove if this is right try either

  1. use plain text as dataType and log it, it should work [but of course you will not be able to convert it to json]
  2. changeLoadFromDB method so that property name is valid [starts with letter, _ or $], you will have a valid JSON response, but you will need to change the way you use it

it 1778 is an ID, a proper structure should be {id:"1778",property:"Bras\u00edlia"} and work flawless give it a try and let us know

EDIT: as jcaron kindly suggested, i have to fix, this answer: the "1778" is indeed a valid property name, but invalid identifier if dot notation is used. Since I don't know how jQuery manage this i would suggest to test as above, and see if one of the tests gives results.

Community
  • 1
  • 1
user1555320
  • 485
  • 2
  • 8
  • Do you have a reference that states that a property name should start with a letter, _ or $? The [JSON spec](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) requires them to be strings, which is any sequence of Unicode code points. – jcaron Dec 08 '15 at 18:39
  • "1778" is just as valid as id for an object property name. – Kevin B Dec 08 '15 at 18:39
  • http://stackoverflow.com/questions/16908476/javascript-object-property-name-as-number. The point is not being a valid JSON property, but having it used without dot notation in JSON decoding process, i would give it a try, because beside this, everything seems fine – user1555320 Dec 08 '15 at 19:20