Power Engineering
Power Engineering

Reputation: 722

PHP JSON encoded output non compatible with Javascript Ajax

Here I've built a script to generate the following JSON output:

[{"lat":41.081348,"lon":14.73292,"type":"F"},...,{"lat":41.09837,"lon":14.83176,"type":"F"}]

However when I try to get data using the following Javascript code:

        $.ajax({
            url: 'myJSONscript.php',
            dataType: "json",
            success: function (data, status, xhr) {
                console.log("data:"+data);
                console.log("status:"+status);
                console.log("xhr:"+xhr);
                }, //End Success
            error: function () {
                alert("ERROR");
                }
            });

I get just an empty data variable
(in other words the console returns
data:empty,
status:success,
xhr:[object Object]).
The JSON output is valid (tested with JSONlint) and was built using the following code:

$arr=array();
while ($row=mysqli_fetch_array($r)) {
$element=array('lat'=>floatval($row['LATITUDE']),'lon'=>floatval($row['LONGITUDE']),'type'=>$row['TYPE']);
    array_push($arr, $element);
    }
$data=json_encode($arr,true);
header("Content-Type: application/json", true);
echo $data;

I cannot figure out what's wrong...

Upvotes: 1

Views: 43

Answers (1)

Power Engineering
Power Engineering

Reputation: 722

Fixed! the contentType: "application/json" cannot be used together with dataType: "json", removing contentType solved the problem.

Upvotes: 2

Related Questions