1

I'm learning how to use HttpClient.post to update MySQL database. The table i'm inserting is:

|id - log|

The PHP file is as follows,

<?php 
   header('Access-Control-Allow-Origin: *');    
    header('Access-Control-Allow-Headers: X-Requested-With');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
include 'db.php';

$postdata=file_get_contents("php://input");
$request = json_decode($postdata);
$message = $request->message;

// Create connection
$conn = new mysqli($server_name, $mysql_username, $mysql_password, $db_name);


 $sql = "INSERT INTO shootingchatlog (id, log) VALUES (NULL, '$message')";

 if($conn -> query($sql) === TRUE ){
 echo "message Uploaded Successfully";
 }else{
 echo "Error Uploading Image";
 }
 mysqli_close($conn);

I keep receiving errors at the line

$message = $request->message;

which brings me to think that the problem has to do with my code here in angular.

   httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  };



  constructor(private http: HttpClient) { }


  public uploadService(mess: string): void {
    console.log(mess);
     this.http.post(this.url, JSON.stringify({"messasge": mess}), this.httpOptions)
           .subscribe((res: Response) => {
        console.log(res);
      },
      err => {
        console.log("Error occured", err);
      });
    }

The most common error I get is:

SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse

I'm really not sure what I'm doing incorrectly. There doesn't seem to be any documentation on this. Or if it is, it's usually too abstract. Any help would be grateful!

JD333
  • 391
  • 3
  • 16
  • Look at the inspector in chrome or firefox and look at the response from the server. It seems as if it's returning HTML or XML instead of JSON if you're getting the ' – Chad K Aug 01 '18 at 16:26
  • 1
    **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you have created a severe [SQL injection bug](http://bobby-tables.com/). **NEVER** put `$_POST`, `$_GET` or **any** user data directly into a query, it can be very harmful if someone seeks to exploit your mistake. – tadman Aug 01 '18 at 18:07
  • 1
    Do try and get out of the habit of cluttering up your code with needless things like `=== true`. Many functions are designed to return values that evaluate as logically true or false so that's redundant. – tadman Aug 01 '18 at 18:08
  • with httpClient you needn't use JSON.stringify or header that say a json – Eliseo Aug 01 '18 at 19:26

1 Answers1

2

from https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST

application/x-www-form-urlencoded: the keys and values are encoded in key-value tuples separated by '&', with a '=' between the key and the value. Non-alphanumeric characters in both keys and values are percent encoded: this is the reason why this type is not suitable to use with binary data (use multipart/form-data instead)

Change the content type from application/x-www-form-urlencoded to multipart/form-data

also check this thread which is quite helpful: application/x-www-form-urlencoded or multipart/form-data?

Taher
  • 10,838
  • 2
  • 27
  • 41
  • Originally I was using application/json. But, I was getting the error. Failed to load Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response. – JD333 Aug 01 '18 at 16:51
  • using multipart form data. I still get the same error in my HTTP response. MySQL database gets an update. It adds a new row, but the value is never inserted in the log column. – JD333 Aug 01 '18 at 17:38
  • what happens when you change the content type to application/x-www-form-urlencoded, multipart/form-data or remove httpOptions at all ? – Taher Aug 03 '18 at 00:24