Unexpected end of JSON input when sending an HTTP post request


#1

Hello, all. I’m pretty new to Ionic, and one of my first major projects is sending an receiving data to/from a server located in my house.

http.get works completely fine, however, the http post yields an error.

Here’s the relevant code:

 ionViewDidLoad() {
    console.log('ionViewDidLoad SensorData');
    let headers  = new Headers();
    headers.append('Content-Type', 'text/plain');
    let body = '{"ID":"3","ITEM":"blah","STATUS":"0","CREATED_AT":"2016-07-21"}';
    this.http.post('/sidemenu/www/ajax/updateItem.php/', JSON.parse(JSON.stringify(body)), {headers: headers}).map(res => res.json()).subscribe(data1 => {
    console.log(data1);
            });
  }

(There doesn’t seem to be a way to format code, but if there is I’ll change it immediately)

Error:

Runtime Error
Unexpected end of JSON input
SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at Response.Body.json (http://localhost:8100/build/main.js:47836:25)
    at MapSubscriber.project (http://localhost:8100/build/main.js:61365:150)
    at MapSubscriber._next (http://localhost:8100/build/main.js:46705:35)
    at MapSubscriber.Subscriber.next (http://localhost:8100/build/main.js:15865:18)
    at XMLHttpRequest.onLoad (http://localhost:8100/build/main.js:48245:38)
    at t.invokeTask (http://localhost:8100/build/polyfills.js:3:9172)
    at Object.onInvokeTask (http://localhost:8100/build/main.js:4613:37)
    at t.invokeTask (http://localhost:8100/build/polyfills.js:3:9093)
    at r.runTask (http://localhost:8100/build/polyfills.js:3:4349)
Ionic Framework: 3.2.1
Ionic App Scripts: 1.3.7
Angular Core: 4.1.0
Angular Compiler CLI: 4.1.0
Node: 6.9.2
OS Platform: Windows 10
Navigator Platform: Win32
User Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36

Thanks guys. And I’m sorry about the formatting, I tried looking around for anything that’d help but there doesn’t seem support for that here.


#2

How to post code.

Do you see any OPTIONS requests in your server logs? Do they succeed?


#3

Alrighty, finished.

No, I don’t. I started the app by running ionic server --serverlogs and didn’t get anything.


#4

This shouldn’t work. ionic serve doesn’t render PHP code. If you want to do this, you have to run the PHP code in a different directory with a PHP Server and use the hostname and port of the PHP Server in the request.

The PHP code should be usable in a normal browser or request client (like Postman or Insomnia) before you can use it in an Ionic app.


#5

I don’t see any PHP code here, just an HTTP request to a php server right?


#6

I think the specified error is because you are trying to stringify a JSON string that is already a string. Try assigning the body as a json object maybe?

let body = {"ID":"3","ITEM":"blah","STATUS":"0","CREATED_AT":"2016-07-21"};

#7

Just pass ordinary objects as the body of Http requests. No need for all this manual JSONification of anything.


#8

@Sujan12
It is calling another directory,on another server, the URL being http://192.168.1.22:1234/shop_tut/ajax/updateItem.php?

@nuttloose
Just tried that, same error

@rapropos
So I tried setting body equal to

 let body = 
{
        "ITEM": "Hello",
        "ID": "3",
        "STATUS": "0",
        "CREATED_AT":"2016-07-21"
};

And removed the json.stringify.
I’m still receiving the same error


#9

Then you should http.post() to that URL, not a local one.


#10

Here is the php code it is calling

<?php 
require_once '../includes/db.php'; // The mysql database connection script
if(isset($_GET['itemID'])){
	$status = $mysqli->real_escape_string($_GET['status']);
	$itemID = $mysqli->real_escape_string($_GET['itemID']);

	$query="UPDATE shop set status='$status' where id='$itemID'";
	$result = $mysqli->query($query) or die($mysqli->error.__LINE__);

	$result = $mysqli->affected_rows;

	$json_response = json_encode($result);
}
?>

@Sujan12
It is posting to that URL, I’m using a proxy.

I have a get request earlier in the file from http://192.168.1.22:1234/shop_tut/ajax/getItem.php which works perfectly fine, here’s the code for that.

  constructor(public navCtrl: NavController, public navParams: NavParams, public http: Http) {
    this.http.get('/shop_tut/ajax/getItem.php?').map(res => res.json()).subscribe(data => {
        console.log(data);
        this.posts = data;
            });

#11

I think the error is in your PHP code I think it should be if(isset($_POST['itemId'])).


#12

Exactly.

You should use your browser’s dev tools to look at the result of that POST to the URL and then you will see that it doesn’t return the expected JSON.


#13

Exactly, like there is something wrong with the php code?

Here’s what it returns (updateItem.php)

Here’s getItem.php, which works perfectly


#14

It responds with nothing. That is because you work with $_GET which is empty on POST requests, as @nb1990 said.


#15

I’ve replaced the $GET_ with a $POST_ request, as per @nb1990’s suggestion, still no change.


#16

I don’t know if we’re talking about actual HTTP methods or PHP stuff at this point, but just want to say that the determination of what method (GET/POST/PUT/whatever) to use should be made for functional RESTy reasons, not technical convenience.


#17

Have a look at the best answer given to a stack-overflow question,

https://stackoverflow.com/questions/35734411/angular-2-web-api-json-parsing-error-syntax-error-unexpected-end-of-input


#18

Of couse, because you are not POSTing any itemId that your script expects. Your PHP script has to be adapted to what you are sending, or you have to send what the PHP script assumes and needs.


#19

All good, he is acceptably sending the data via POST. The script he is POSTing to was only reading data from GET paramaters (URL query string basically) which can not work if this doesn’t exist. Unfortunately the rest of the script is also garbage :confused:


#20

Good thing I didn’t write it then lol. But I do have access to it. How should I change the script?

Also, while poking around the server’s files I found /shop_tut/ajax/addItem.php?. It seemed more suited to what I was trying to do (I’m not all that familiar with php). The code for that is

<?php 
require_once '../includes/db.php'; // The mysql database connection script
if(isset($_GET['item'])){
	$item = $mysqli->real_escape_string($_GET['item']);
	$status = "0";
	$created = date("Y-m-d", strtotime("now"));
    $ID=0;
 $query="SELECT ID from shop ORDER BY ID LIMIT 2";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($result->num_rows > 0) {
	while($row = $result->fetch_assoc()) {
		$ID = $row["ID"];	
	}
}

$ID=$ID+1;

	$query="INSERT INTO shop(ID,item,status,created_at)  VALUES ($ID,'$item', '$status', '$created')";
	$result = $mysqli->query($query) or die($mysqli->error.__LINE__);

	$result = $mysqli->affected_rows;

	echo $json_response = json_encode($result);
	}
?>

I changed the $GET_ to a $POST_ and received the same error.

@nuttloose
I implemented both of the solutions, and I didn’t get a fatal error when I ran it which is good–but the request didn’t return anything. I think it’s an issue with the php files.

@rapropos
Pretty sure it’s an issue with the php files I’m calling at this point.

In the meantime I think I’ll head over to codeacademy and take a course in php.