javascript - Angular 2: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data - Stack Overflow

I am using Angular 2 and I want to send the json data to a php file. When I try to send the data using

I am using Angular 2 and I want to send the json data to a php file. When I try to send the data using the post request, it says "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data". When I look at the network tab it says status 200, so it sent it. I am not sure what I am doing wrong, but I would appreciate if someone could look this over.

Here is the data service I am using for the post request

sendData(data): Observable<Object>{
 let url = "test.php";
 let encoded_data = JSON.stringify({data});
 console.log('encoded', encoded_data);
    let headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(url, encoded_data).map(
        (res: Response) => res.json() || {}
    );
}

I use it in my ponent like this.

sendDatatoServer(){
  this.dataService.sendData(this.data)
     .subscribe(
        data => {
           console.log('the data', data);
        },
       (err) => console.log(err),
       () => console.log("data success!!")
      );
 }

My json data looks somewhat like this when it is stringified.

{"data": [{"title": "sometext" }, {"title": "sometext" }]}

Here is the test.php file I have so far. I am not sure if this is correct or not, but it doesnt send any response.

<?php


header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

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

 echo $request;

I am using Angular 2 and I want to send the json data to a php file. When I try to send the data using the post request, it says "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data". When I look at the network tab it says status 200, so it sent it. I am not sure what I am doing wrong, but I would appreciate if someone could look this over.

Here is the data service I am using for the post request

sendData(data): Observable<Object>{
 let url = "test.php";
 let encoded_data = JSON.stringify({data});
 console.log('encoded', encoded_data);
    let headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(url, encoded_data).map(
        (res: Response) => res.json() || {}
    );
}

I use it in my ponent like this.

sendDatatoServer(){
  this.dataService.sendData(this.data)
     .subscribe(
        data => {
           console.log('the data', data);
        },
       (err) => console.log(err),
       () => console.log("data success!!")
      );
 }

My json data looks somewhat like this when it is stringified.

{"data": [{"title": "sometext" }, {"title": "sometext" }]}

Here is the test.php file I have so far. I am not sure if this is correct or not, but it doesnt send any response.

<?php


header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

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

 echo $request;
Share Improve this question asked Jan 11, 2017 at 23:24 LadyTLadyT 6592 gold badges12 silver badges32 bronze badges 6
  • $request is an object, what do you expect echo $request; to display? – Barmar Commented Jan 11, 2017 at 23:50
  • @Barmar I tried to echo the keys, but I keep getting an error. – LadyT Commented Jan 12, 2017 at 0:01
  • The issue is not the request, but the response. You map your response to res.json(), which will throw the parsing error, when for example the response contains html. This can easily happen when your webserver returns an exception. – Jan B. Commented Jan 12, 2017 at 0:03
  • The client is expecting the response to be JSON. You can't just echo the keys, you need to echo a JSON string. echo json_encode($request);. – Barmar Commented Jan 12, 2017 at 0:03
  • @Barmar I understand what you mean. I added the json_encode and the parse error disappears. When I try to access the keys like echo json_encode($request->title), I get the syntax error in the console. – LadyT Commented Jan 12, 2017 at 0:06
 |  Show 1 more ment

1 Answer 1

Reset to default 3

Your problem seems to be entirely on PHP side, I think. Just wondering about the following:

let encoded_data = JSON.stringify({data});

Should you really have the curly brackets there? Well, the important thing is that if it the stringified JSON looks like:

{"data": [{"title": "sometext" }, {"title": "sometext" }]}

it should all be good.

As mentioned in the ments, you need to json_encode your data on the PHP side:

echo json_encode($request);

In the ment you said you wanted to access the title like so:

echo json_encode($request->title)

It's not possible, which title do you mean? Your json is an object that contains an array, so to access e.g the first title, you would have to do the following:

echo json_encode($request->data[0]->title);

Apart from this, the rest of your code looks fine, so this should work :)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745100324a4611233.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信