So the thing is I'm currently working on a mobile app with ionic2 and I have to use Mailchimp for subscriptions. I write a php file which handle the API and upload it on a server. The API is works fine with the static email that I write in it so it's actually working. After I made it I start to working on the post data in angular2/ionic2. But i get
SyntaxError: Unexpected token A in JSON at position 0
error.
The whole thing is fail in this code:
createPost(post: {email: string}): Observable<any>{
const email = JSON.stringify(post);
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:8100/api', email, {
headers: headers
}).map(res => {console.log(res.json())});
}
I figure out the problem is the url but I can't figure out why. When I use http://jsonplaceholder.typicode.com/posts in the url it works.
My php code looks like this(I use MailChimnp.php wrapper):
<?php // for MailChimp API v3.0
include('MailChimp.php'); // path to API wrapper downloaded from GitHub
use \DrewM\MailChimp\MailChimp;
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email = $request->email;
$MailChimp = new MailChimp('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-usXX');
$list_id = 'xxxxxxxxxx';
$result = $MailChimp->post("lists/$list_id/members", [
'email_address' => $email,
'status' => 'subscribed',
]);
print_r($result);
if ($MailChimp->success()) {
print_r($result);
} else {
echo $MailChimp->getLastError();
}
Your map function needs to return data. You have to fix this:
createPost(post: {email: string}): Observable<any>{
const email = JSON.stringify(post);
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:8100/api', email, {
headers: headers
}).map(res => {
console.log(res.json())
return res.json(); //add this line
});
}