Home > front end >  flutter http post request returns html instead of json
flutter http post request returns html instead of json

Time:10-19

In my flutter app I decided to take my app live by hosting it online from local db (xampp) but now whenever i run my app i keep getting

FormatException: Unexpected character (at character 1)
<html><body><script type="text/javascript" src="/aes.js" ></script><script>...

//Full html code
<html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f  )e =(16>d[f]?"0":"") d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("3bbe2c7d2bd575630c6e4c0b1537ed79");document.cookie="__test=" toHex(slowAES.decrypt(c,2,a,b)) "; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="https://www.quelib.com/src/get_api/get_uni.php?i=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>

I have searched on stackoverflow and other website on google, but the answers i got which is to add headers

headers: {
  'Content-Type': 'application/json',
  'Charset': 'utf-8',
  "Accept": 'application/json'
}

or check my statusCode or encode my body parameters using jsonEncode() since i keep getting Bad State Error whenever i run my app with 'Content-Type': 'application/json',

Future<List<String>> getAllUni() async {
    List<String> uniAll = [];
    try {
      var apiUrl = url   "get_api.php";
      final Map<String, dynamic> data = {"action": "GET_UNI"};
      await http.post(Uri.parse(apiUrl), body: jsonEncode(data), headers: {
        'Content-Type': 'application/json',
        'Charset': 'utf-8',
        "Accept": 'application/json'
      }).then((response) {
        debugPrint(response.body);
        debugPrint(json.decode(response.body));
        print(response.body);
        print(json.decode(response.body));
        if (json.decode(response.body) == 'no_data') {
        } else {
          List jDecode = json.decode(response.body);

          if (response.statusCode == 200) {
            jDecode.forEach((e) {
              print(e.toString());
              uniAll.add(e['name'].toString());
            });
          } else {}
        }
      });
    } catch (e) {
      ContentReport.report.catchReport("get_api.dart", "getAllUni",
          e.toString());
    }
    return uniAll;
}

my php code

$action = $_POST['action'];

if($action == 'GET_UNI') {

    $sql = $conn->prepare("SELECT * FROM uni ORDER BY name ASC");
    $sql->execute();
    $res = $sql->get_result();
    if (mysqli_num_rows($res) > 0) {
        while ($row = $res -> fetch_assoc()) {
            $data[] = $row;
        }
        echo json_encode($data);
    }
    else {
        echo json_encode("error_data");
    }
}

Please how do i solve this cause the url link works perfectly fine. Also if you need more explanation please tell me

CodePudding user response:

header('Content-type: application/json');
$action = $_POST['action'];

if($action == 'GET_UNI') {

    $sql = $conn->prepare("SELECT * FROM uni ORDER BY name ASC");
    $sql->execute();
    $res = $sql->get_result();
    if (mysqli_num_rows($res) > 0) {
        while ($row = $res -> fetch_assoc()) {
            $data[] = $row;
        }
        echo json_encode($data);
    }
    else {
        echo json_encode("error_data");
    }
}

CodePudding user response:

Make your PHP code response more informative. Once use the code like below:

<?php 
$response["error"] = false;
$response["errmsg"] = "No message";
$response["date"] = array();

if(isset($_POST["action"])){
    $action = $_POST['action'];
    if($action == 'GET_UNI') {

        $sql = $conn->prepare("SELECT * FROM uni ORDER BY name ASC");
        $sql->execute();
        $res = $sql->get_result();
        if (mysqli_num_rows($res) > 0) {
            while ($row = $res -> fetch_assoc()) {
                array_push($response["data"], $row);
            }
        }else {
            $response["error"] = true;
            $response["errmsg"] = "NO any row found.";
        }
    }
}else{
     $resposne["error"] = true;
     $response["errmsg"] = "No action parameter submitted through POST.";
}

header('Content-Type: application/json');
echo json_encode($response);
?>

You can look to this example at FlutterCampus: Valid way to Generate Nested or Complex JSON data using PHP

  • Related