Search code examples
javascriptphpfetchnativescript

how to use fetch to post data to php


i'm trying to create a comment function for my nativescript app, using the link on my brwser, this functionality works fine. but using the fetch API in my app, it returns the error function (error message is unexpected token < in JSON at position 0)

function AddCommentViewModel() {
      const viewModel = observableModule.fromObject({});
      var comm = "nice guy";
      var email = appSettings.getString("email");
      var phone = appSettings.getString("number");
        alert(comm);
        alert(email);
        alert(phone);
        var url = "https://adekunletestprojects.000webhostapp.com/skog/addComment.php?email" + email + "&number=" + phone + "&comment=" + comm;
        fetch(url).then((response) => response.json()).then((res) => {
    viewModel.set("itemsd", res.itemss);
            alert("successful");
     }).catch((err) => {
            alert("failed");
    });
      return viewModel;
    }

my php is

<?php 

include 'config.php';
$number = $_GET['number'];
$comment = $_GET['comment'];
$email = $_GET['email'];
try {
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
    $sql = "SELECT name FROM searchResults WHERE email='$email'";
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $dbh->prepare($sql);  
    //$stmt->bindParam(":email", $_GET['email']);
    $stmt->execute();
    $employees = $stmt->fetch(PDO::FETCH_ASSOC);
    $employees1 = $stmt->fetchAll(PDO::FETCH_OBJ);
    $name = $employees['name'];
    $sql1 = "INSERT INTO comments (number, comment, user, date) VALUES ('$number', '$comment', '$name', '02/04/2020')";
    $sth = $dbh->query($sql1);
    $sth->execute();
    $dbh = null; 
    echo '{"itemss":'. json_encode($employees1) .'}';
    //$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}'; 
}

?>

Solution

  • The error Unexpected token < in JSON at position 0 most likely means that you got HTML back instead of JSON. (Imagine parsing <html>..... as JSON - then the first character is < which is not valid JSON.)

    You can temporarily use response.text() instead of response.json() and then print what res you got, so you can see the actual contents before you fail parsing them as JSON. (Ideally you'd use a debugging proxy to see what is actually going over the line, or just use DevTools and look at the network tab!)

    I'd assume that your server shows an error, and it shows it as HTML.

    Actually, I spotted another issue in your code, which may be the reason for your invalid request:

    var url = "https://adekunletestprojects.000webhostapp.com/skog/addComment.php?email" + email + "&number=" + phone + "&comment=" + comm;
    

    The code here has "?email" + email which will generate something like ?emailjohn@doe.com, which is probably not what you want. You are missing an equal sign here: "?email=" + email

    But this has another problem, you are not encoding the values. What if the email is set to john&alice=bob@doe.com? Then you'll have ?email=john&alice=bob@doe.com which you don't want either. (Or imagine a comment text containing &, which is more likely.)

    If this were in a browser or node.js, you'd best use the URL object, but in NativeScript you don't have that. So, you'd just use encodeURIComponent to encode each individual value:

    var url = "https://adekunletestprojects.000webhostapp.com/skog/addComment.php?email=" +
      encodeURIComponent(email) + "&number=" + encodeURIComponent(phone) + "&comment=" +
      encodeURIComponent(comm);
    

    Or, you could write a helper function to do it for you, and get cleaner code:

    const buildQuery = params => Object.entries(params)
      .map(([k, v]) => `${k}=${encodeURIComponent(v)}`)
      .join('&')
    
    // Later on:
    const query = buildQuery({ email: email, number: phone, comment: comm })
    const url = `https://adekunletestprojects.000webhostapp.com/skog/addComment.php?${query}`