-1

I am able to consume the php endpoint from postman. I try to do the same from angular post, I get this error - Http failure during parsing for. Even though everything looks perfect to me, the problem is surprising. Here is my snippet

php file

<?php
header('Access-Control-Allow-Origin: *');

// check for post
if ($_SERVER['REQUEST_METHOD']=='POST') { 
    $name = $_POST['name'];
    $email = $_POST['email'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];

    // include db connect class
    require_once __DIR__ . '/db_connect.php'; 
    // connecting to db
    $conn = new db_CONNECT();

    $cone=$conn->con;   

    //escpae the strings to be inserted to DB
    $escapedname = mysqli_real_escape_string($cone, $name);
    $escapedemail = mysqli_real_escape_string($cone, $email);
    $escapedsubject= mysqli_real_escape_string($cone, $subject);
    $escapedmessage = mysqli_real_escape_string($cone, $message);

    // mysql inserting a new row
    $sql = "INSERT INTO contacts(name, email, subject, message) VALUES ('$escapedname', '$escapedemail', '$escapedsubject', '$escapedmessage')";
    // $result= $cone -> query($sql);
    // $affected = $cone -> affected_rows;

    if (mysqli_query($cone,$sql)) {
        echo "Information saved successfully.";
    } else {
        echo "Not successful";
    }
 } else {
    echo "Some field missing.";
}
?>

here is the angular snippet

saveContactDetails = function () { 

    this.proceed = true;
    this.success = false;
    const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
    data.append('name', this.contactDeJson.name);
    data.append('email', this.contactDeJson.email);
    data.append('subject', this.contactDeJson.subject);
    data.append('message', this.contactDeJson.message);

    this.http
    .post('http://localhost:80/'+'api/create_contact.php', data.toString(), {headers: myheader})

Please why am I getting this error

{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"http://localhost/api/create_contact.php","ok":false,"name":"HttpErrorResponse","message":"Http failure during parsing for http://localhost/api/create_contact.php",
Blaze
  • 2,269
  • 11
  • 40
  • 82
  • Could you please post what is `data` in the function? – ruth May 31 '20 at 22:21
  • it means that the appended data is a string format, coming from data.append... – Blaze May 31 '20 at 22:23
  • does the response look all right when you inspect it in the dev tools? Looks to me like angular is expecting a json response (the default response type) but not receiving the correct data or headers. – Pevara May 31 '20 at 22:43
  • I tested with postman before implementing to angular/php. But you can suggest your approach, – Blaze May 31 '20 at 22:44
  • postman does not validate your response type i think. Just try sending a content-type header from your backend, or set the responseType to text in your angular request – Pevara May 31 '20 at 22:47
  • Also, try sending the correct response code in your php. If something goes wrong, you should send a 500, if a field is missing a 400, and only on success a 200. It makes debugging a lot easier for your consumers (and is the correct way of implementing an API) – Pevara May 31 '20 at 22:56
  • can u show how to set it from the backend, I did from angular as shown - const myheader = new HttpHeaders().set('Content-Type', 'application/text') and I am getting a cors – Blaze May 31 '20 at 22:56
  • https://stackoverflow.com/questions/50798592/angular-6-how-to-set-response-type-as-text-while-making-http-call – Pevara May 31 '20 at 22:57
  • Now getting this error from the backend - "error":{"error":{},"text":"
    \nNotice: Undefined index: email in ....
    – Blaze May 31 '20 at 23:01

2 Answers2

0

I believe you are trying to send some query parameters using data variable. You could actually send a JS object as the parameters. Try the following

private saveContactDetails() { 
  this.proceed = true;
  this.success = false;
  const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
  const data = {
    'name': this.contactDeJson.name,
    'email': this.contactDeJson.email,
    'subject': this.contactDeJson.subject,
    'message': this.contactDeJson.message
  }

  this.http.post('http://localhost:80/'+'api/create_contact.php', { params: data }, { headers: myheader })
}
ruth
  • 29,535
  • 4
  • 30
  • 57
  • implementing your answer produces -- "error":{"error":{},"text":"
    \nNotice: Undefined index: email in ....
    – Blaze May 31 '20 at 22:40
0

I believe the issue is that your angular script is expecting a json response (the default responseType), but not receiving the correct headers or data. In stead of just echoing out your result in php, I would make a function that can handle sending the response. Something like this:

function sendJsonResponse(data, status = 200) {
    header('Content-Type: application/json', true, status);
    echo json_encode($data);
    exit();
}

In stead of of doing this:

echo "Not successful";

You can now do this:

sendJsonResponse("Not successful", 500);

This should give you more valuable information in the frontend. And the response should now be formatted correctly, and no longer produce the parse error in angular that you are getting now.

Pevara
  • 14,242
  • 1
  • 34
  • 47
  • .... has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. – Blaze May 31 '20 at 23:13
  • adding the function introduced a cors error, but I have enabled it in the top of the file – Blaze May 31 '20 at 23:16