Link to home
Create AccountLog in
Avatar of Ahmet Ekrem SABAN
Ahmet Ekrem SABANFlag for Austria

asked on

Problems writing my first POST request

Hallo!

I am working on a Web project for several months now. Since a few days ago, everything was easy, and I could send my data over the IP address with a GET request. This may not be the right way, but to me, it was functioning all well. To be honest, I do not know much about the server-side.

Now, I am requested to pass a greater amount of data to the PHP server that sends it to the database, and the IP address length exceeds 8190 characters. So, I read the Web and found out that a POST request to the PHP server would be more appropriate to pass the large amount of data.

So, I make a POST request with

	var jsonObject = json.stringify({
		 'renderedStaticPage': renderedStaticPage,
		 'newsTickerEnabled': (newsTickerEnabled ? 1 : 0)
	});
	var messageText = 'ipAddress = ' + Apostrophe
		+ strings.excerpt(ipAddress) + Apostrophe
		+ CommaSpace + Apostrophe + 'jsonObject = '
		+ Apostrophe + jsonObject + Apostrophe;

	messages.print(functionName, messageText);

	$http({
		method: 'POST',
		url: ipAddress,

		headers : {
			'Content-Type': 'application/json; charset=UTF-8'
			//'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
		},
		data: JSON.stringify(jsonObject),
	}).success(function(data, status, headers, config) {
		swal('Data sent successfully.', '', 'info');
	}).error(function(data, status, headers, config) {
		swal('No connection possible!', 'URL: '
			+ messageText, 'error');
	});
};

Open in new window


By the way: The strings.excerpt just cuts out the beginning and the end of the content, if it exceeds 50 characters, and the messages.print just makes a compact log print to the console. So, there is nothing exciting about that…

When I make the call with the backend PHP code

<?php

include('./general/connectDB.php');
include('./general/constants.php');

$renderedStaticPage = $_POST['renderedStaticPage'];
$newsTickerEnabled = $_POST['newsTickerEnabled'];

//print "renderedStaticPage = $renderedStaticPage" . $CR;	# Test line
//print "newsTickerEnabled = $newsTickerEnabled" . $CR;	# Test line

$query = "INSERT INTO StartSite (renderedStaticPage, newsTicker_enabled) VALUES ('"
		. $renderedStaticPage . "', " . $newsTickerEnabled . ")";

// Start query
$result = MYSQL_QUERY($query);

//print "query = $query\nresult = $result" . $CR;	# Test line
	
?>

Open in new window


it finishes with the 'Data sent successfully' message. Unfortunately, there is no new record in the database. If I uncomment one or more of the //print lines in the PHP code, I get the error message 'No connection possible!' with the sent renderedStaticPage (should contain an HTML page or part of it) and the Boolean newsTickerEnabled (0 or 1).

I heard from a colleague today about Postman plug-in for Google Chrome that I started to use. Whenever I have uncommented one or more //print lines in the PHP code, I can see that all the variables on the server are empty, and on the client side, there is the error message

SyntaxError: Unexpected token r in JSON at position 0
    at JSON.parse (<anonymous>)
    at fromJson (ionic.bundle.js:10063)
    at defaultHttpResponseTransform (ionic.bundle.js:18080)
    at ionic.bundle.js:18171
    at forEach (ionic.bundle.js:9168)
    at transformData (ionic.bundle.js:18170)
    at transformResponse (ionic.bundle.js:18926)
    at processQueue (ionic.bundle.js:23399)
    at ionic.bundle.js:23415
    at Scope.$eval (ionic.bundle.js:24678)

Open in new window


if the first print starts with print "r…. In the included connectDB.php file (attached below), the header command decides to use 'application/json'. Without the JSON part, the code should be

	[…]
	var messageText = 'ipAddress = ' + Apostrophe
		+ strings.excerpt(ipAddress) + Apostrophe + CommaSpace
		+ Apostrophe + 'renderedStaticPage = ' + Apostrophe
		+ strings.excerpt(renderedStaticPage) + Apostrophe + CommaSpace
		+ 'newsTickerEnabled = ' + strings.excerpt(newsTickerEnabled);

		messages.print(functionName, messageText);
		$http({
			method: 'POST',
			url: ipAddress,

			headers : {
				'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
			},
			data: {
				'renderedStaticPage': renderedStaticPage,
				'newsTickerEnabled': (newsTickerEnabled ? 1 : 0)
			},
		}).success(function(data, status, headers, config) {
			swal('Data sent successfully.', '', 'info');
		}).error(function(data, status, headers, config) {
			swal('No connection possible!', 'URL: '
				+ messageText, 'error');
		});
		[…]

Open in new window


Can you help me to find out why the PHP server does not get the parameter values? If it does, I am sure the PHP code will write it to the database, as it did it before.

To eliminate other problems & for the time being, I set renderedStaticPage = '<div name="test22"></div>'.

Thank you for your help!
2017-03-07-PHP-code.zip
Avatar of Mukesh Yadav
Mukesh Yadav
Flag of India image

You are using the JSON.stringify() twice on the JavaScript object so you have to remove one, I have removed the 2nd call:

var jsonObject = JSON.stringify({
		 'renderedStaticPage': renderedStaticPage,
		 'newsTickerEnabled': (newsTickerEnabled ? 1 : 0)
	});  /* Here you was using json.stringify() it sould be JSON.stringify() */
	var messageText = 'ipAddress = ' + Apostrophe
		+ strings.excerpt(ipAddress) + Apostrophe
		+ CommaSpace + Apostrophe + 'jsonObject = '
		+ Apostrophe + jsonObject + Apostrophe;

	messages.print(functionName, messageText);

	$http({
		method: 'POST',
		url: ipAddress,

		headers : {
			'Content-Type': 'application/json; charset=UTF-8'
			//'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
		},
		data: jsonObject, /* removed JSON.stringify from because jsonObject is already in json format */
	}).success(function(data, status, headers, config) {
		swal('Data sent successfully.', '', 'info');
	}).error(function(data, status, headers, config) {
		swal('No connection possible!', 'URL: '
			+ messageText, 'error');
	});
};

Open in new window




UPDATE:
You are getting the following  error because you are passing a string to JSON.stringify() method call, now you just need to remove this 2nd call; That's it.
SyntaxError: Unexpected token r in JSON at position 0
    at JSON.parse (<anonymous>)
    at fromJson (ionic.bundle.js:10063)
    at defaultHttpResponseTransform (ionic.bundle.js:18080)
    at ionic.bundle.js:18171
    at forEach (ionic.bundle.js:9168)
    at transformData (ionic.bundle.js:18170)
    at transformResponse (ionic.bundle.js:18926)
    at processQueue (ionic.bundle.js:23399)
    at ionic.bundle.js:23415
    at Scope.$eval (ionic.bundle.js:24678)

Open in new window

Avatar of Ahmet Ekrem SABAN

ASKER

Thank you very much for your assessment! That was really one of the errors I have. But I still have some problems.

User generated image
You can print the POST data as
print_($POST); 

Open in new window


and print the query with echo

echo $query 

Open in new window

for $query = "INSERT INTO StartSite (renderedStaticPage, newsTicker_enabled) VALUES ('"      . $renderedStaticPage . "', " . $newsTickerEnabled . ")";

Also please not mysql_connect is deprecated

You need to use something like this, $connection = mysqli_connect('localhost', 'username', 'password', 'database');

mysqli_query($connection, 'YOUR QUERY GOES HERE....');
Good learning resources for those new to PHP are here (just skip over the parts you already know from academics or work experience).
https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html

The problems with the MySQL extension is shown with many examples here.  It has been removed from PHP.  The article shows how to do the necessary remediation to remove MySQL and replace it with one of the supported extensions.
https://www.experts-exchange.com/articles/11177/PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html
Thank you for your comments! I changed the code to MYSQLI_QUERY & added the print_($POST);, but still get the 'No connection possible!' message. I will read the information you sent, Ray. Thank you again!
You are checking POST in your PHP but you are sending it JSON ???

Either don't send  JSON by not doing a stringify on the data object - just send it straight as an object
OR
do the following on the php
$json = file_get_contents("php://input");
$json = json_decode($json);

Open in new window

If a POST works for you then simply do that

So doing the post you would do something like this
$http({
	url: ipAddress,
	data: {
          'renderedStaticPage': renderedStaticPage,
          'newsTickerEnabled': (newsTickerEnabled ? 1 : 0)
        },
	method: 'POST',
}).then(function(resp) {
	console.log(resp);
});

Open in new window

On the server you can now check $_POST
Look at the part of the article about Connect to the Server and Choose the Data Base.  It shows code examples teaching how to get a more exact and useful error message than "no connection possible."
Bear in mind that Angular has shortcut methods on $http so you could also just do this
var data = {
  'renderedStaticPage': renderedStaticPage,
  'newsTickerEnabled': (newsTickerEnabled ? 1 : 0)
};
$http.post(ipAddress, data).then(function(resp) {
   console.log(resp);
});

Open in new window

EDIT
Added missing .post()
This may or may not be part of the issue, but when I use Firefox (where I do not accept cookies) and visit http://app.avm.at, the site attempts to redirect to link.avm.at in a way that does not work, and the browser gets this message: The page isn’t redirecting properly.  

On Chrome (where I do accept cookies) I see this:
The avm.at page isn’t working

avm.at redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS

If you're getting into the PHP script far enough that you can access the contents of $_POST, this is probably not part of the issue, but it's worth checking.

You can find the POST request variables with this bit of code.  After the run, look in the PHP error_log file.
<?php
ob_start();
var_dump($_POST);
error_log( ob_get_clean() );

Open in new window

Oh, there is a typo! It is not avm.at, but ivm.at!
Thank you for your responses. I read the articles above, but I still have a problem with the access control. Obviously, something elementary is wrong with my code. The current content of the all-used connectDB.php file is

$username = "<username>";
$password = "<password>";
$hostname = "localhost"; 

//$echo 'Current PHP version is ' . phpversion();
//header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");

// Create connection to the database
$dbhandle = MYSQLI_CONNECT($hostname, $username, $password)
	or die("Unable to connect to MySQL");

$selected = MYSQLI_SELECT_DB("test_apptest", $dbhandle)
	or die("Could not select examples");

MYSQLI_QUERY("SET NAMES 'utf8'");

Open in new window


With this code, I get the error dialog 'No connection possible!' message depicted above & the error

XMLHttpRequest cannot load http://app.ivm.at/ServiceTest/addStartSite.php. Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

Open in new window


If I make the following change in the file

header("Access-Control-Allow-Headers: Content-Type");
//header("Access-Control-Allow-Origin: *");

Open in new window


the reply is

XMLHttpRequest cannot load http://app.ivm.at/ServiceTest/addStartSite.php. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Open in new window


with the error dialog. If I uncomment the Access-Control-Allow-Origin line in the file above, there are no errors in the console, but the error dialog still opens.

What do you think is still missing/wrong so that the POST comment does not send the data to the PHP server?

Thank you for your reply!
If you are making a cross domain request you have to have the Access-Control-Allow-Origin - that is not what is causing your error.

Advice - forget the AJAX for now - get your server side working without it.

To do this I would change your script to use $_GET instead of $_POST so that you can submit user name and password in the URL.

Test the URL with parameters directly (leave AJAX out) and see what that returns. When that is working we can change back to $_POST.

NB: The change to $_GET is for convenience of testing only - it should not be used in production.

Try the above and report back what is displayed.
I changed the followint in my Angular.JS code:

	var ipAddress = database.createPostIPAddress(calls.START_SIDE)
		+ QuestionMark + 'username="ivmtest"&password="tegucigalpa33"';

	var renderedStaticPage = database.encode('<div name="test22"></div>');

	var messageText = 'ipAddress = ' + Apostrophe
		+ strings.excerpt(ipAddress) + Apostrophe + CommaSpace
		+ Apostrophe + 'renderedStaticPage = ' + Apostrophe
		+ strings.excerpt(renderedStaticPage) + Apostrophe + CommaSpace
		+ 'newsTickerEnabled = ' + strings.excerpt(newsTickerEnabled);

	messages.print(functionName, messageText);

	var data = {
		'renderedStaticPage': renderedStaticPage,
		'newsTickerEnabled': (newsTickerEnabled ? 1 : 0)
	};

	$http.post(ipAddress, data).then(swal('Daten wurden erfolgreich übermittelt.', '', 'info'),
		swal('Keine Verbindung möglich!', 'URL: ' + messageText, 'error'));

Open in new window

The username & password is new. On the server side, I added the following lines:

include('./general/connectDB.php');
include('./general/constants.php');

// OPEN A CONNECTION TO THE DATA BASE SERVER AND SELECT THE DB
$mysqli = new mysqli($hostname, $username, $password/*, $db_name*/);

[…]

$db_user = $_GET['username'];
$db_password = $_GET['password'];

Open in new window


The response in the console is

MainDB.createPostIPAddress(eCall.START_SITE) returns with "http://app.ivm.at/ServiceTest/addStartSite.php"
messages.js:152 ivmDatabase.controller(DatabaseController.startSite2DB) ipAddress = 'http://app.ivm.at/Se … username="ivmtest"&password="tegucigalpa33"', 'renderedStaticPage = '%3Cdiv%20name%3D%22test22%22%3E%3C%2Fdiv%3E', newsTickerEnabled = 0

Open in new window


So, the username & the password is (unsafely) passed & read with the $_GET function.
As noted above - the $_GET change is ONLY so you can test the service call with a URL typed directly into the browser.

I always build my services and test them in a browser before I go anywhere near my angular code. That way I know the service is returning the right data based on the required inputs.

Did you do the URL test?
Yes, I called the code with the modifications above & posted the result. As we do not use AJAX at all, there are no issues with that. I could GET the fake username & the password successfully, although the POST part still fails to do so.
As we do not use AJAX at all, there are no issues with that.
$http.post(ipAddress, data).then(swal('Daten wurden erfolgreich übermittelt.', '', 'info'),
		swal('Keine Verbindung möglich!', 'URL: ' + messageText, 'error'));

Open in new window

That is AJAX

although the POST part still fails to do so.
While your script is set up to accept $_GET POST will fail.

Lets start from the beginning

1. Your script does use AJAX - the angular $http is an AJAX call
2. You need to first establish that your server script is working before you touch your Angular code
3. To test your server script easily we change $_GET to $_POST so we don't have to go through the hassle of writing code (Form or ajax script) to test the service - we can just do the following directly into the browser
http://yourserver/service.php?username=Fred&password=Secret

Open in new window

4. Repeat step 3 until you get the expected results showing in the browser
5. Change script back to $_POST
6. Test angular script
7. Examine console (F12) to look for errors and information on requests sent and responses received.

Right now we are on step 3.
Yes, sorry for that! I saw the AJAX wording, although I was not aware of using AJAX. I am just helping another colleague in the project that started the whole page, but we never talked about AJAX.
AJAX is inherent in the Angular solution you are using.

I am still not sure where we are - is your service working yet?
I try to make an example run, not the whole project. The project uses Angular.JS, AJAX (as you pointed out), the ionic framework & I think a lot more...
You need to establish if your PHP service is working correctly - are you able to do that using the method described above i.e. changing $_POST to $_GET and then calling the script with URL parameters?

If we can't get past this step then we cannot solve the problem.
I wrote the following code:

HTML: index.html:
<html>
    <head>
        <title>Backend POST test</title>

        <script src="./js/startSite2DB.js"></script>
    </head>

    <body>
        <div>
            <button type="button" onclick="startSite2DB();">Click Me!</button>
        </div>
    </body>
</html>

Open in new window


JavaScript: ./js/startSite2DB.js
"use strict;"

var Apostrophe = "'";

function startSite2DB ($http) {
	var ipAddress = 'http://app.ivm.at/ServiceTest/addStartSite.php?'
		+ 'username=\'ivmtest\'&password=\'tegucigalpa33\'';

	var renderedStaticPage = '<div name="test22"></div>';

	var messageText = 'ipAddress = ' + Apostrophe
		+ ipAddress + Apostrophe + ', '
		+ 'renderedStaticPage = ' + Apostrophe
		+ renderedStaticPage + Apostrophe;

	console.log(messageText);

	/* var data = {
		'renderedStaticPage': renderedStaticPage,
	};

	var headers = {
		'Content-Type': 'application/x-www-form-urlencode'
	}; */

	window.open(ipAddress);
};

Open in new window


PHP: addStartSite.php
<?php
<?php

// ======================================================================
// File name	: addStartSite
// Author		: Juri Schreib
// Co-author	: Ahmet Ekrem Saban
// Date			: 2016-08-31
// Last revision: 2017-03-07
// ======================================================================
//include('./general/connectDB.php');
//include('./general/constants.php');

$username = "<username>";
$password = "<password>";
$hostname = "localhost"; 

// OPEN A CONNECTION TO THE DATA BASE SERVER AND SELECT THE DB
$mysqli = new mysqli($hostname, $username, $password);

//header('Access-Control-Allow-Origin: *');

// DID THE CONNECT/SELECT WORK OR FAIL?
if ($mysqli->connect_errno)
{
    $err
    = "CONNECT FAIL: "
    . $mysqli->connect_errno
    . ' '
    . $mysqli->connect_error
    ;
    trigger_error($err, E_USER_ERROR);
}
// SHOW WHAT THE DB CONNECTION OBJECT LOOKS LIKE
//var_dump($mysqli);

$got_username = $_GET['username'];
$got_password = $_GET['password'];

print "got_username = $got_username\n";	# Test line
print "got_password = $got_password\n";	# Test line
/* 
$renderedStaticPage = $_GET['renderedStaticPage'];
$newsTickerEnabled = $_GET['newsTickerEnabled'];

print "renderedStaticPage = $renderedStaticPage\n";	# Test line
print "newsTickerEnabled = $newsTickerEnabled\n";	# Test line

$query = "INSERT INTO StartSite (renderedStaticPage, newsTicker_enabled) VALUES ('"
		. $renderedStaticPage . "', " . $newsTickerEnabled . ")";

// Start query
$result = MYSQLI_QUERY($dbhandle, $query); */

?>

Open in new window


The result is fine: I get got_username = 'ivmtest' got_password = 'tegucigalpa33'.
Now, I (the POST rookie!) changed the code (see attachement) & get the following on the newly-opened Web page:

renderedStaticPage = '
'

Open in new window


The address filed of the new browser tab contains http://app.ivm.at/ServiceTest/addStartSite.php?renderedStaticPage=%27%3Cdiv%20name=%22test22%22%3E%3C/div%3E%27.

Notice: I added one line to the PHP script & know now that the server uses PHP 5.6.29-1~dotdeb+7.1
all-the-code.zip
If you can send me a simple POST example that runs here, I think that I can find out the problem.
SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Thank you very much for your effort! The script also run here & returned a 'Success: []'. I will continue with this example tomorrow, as it is time to go for today. Have a nice evening, Julian!
Thank you again for your help! I added the files you propose, changing the address in & the names of some of them so that they fit in my environment. What I see is that the code comes in the startSide2DB.js till the done part with a resp.status = false, but with a resp.message, as you can see below. Remember that this message was empty yesterday.
User generated image
Where does the "Failed" in the message box come from?

The PHP script is correct. The "success" is returned if mysqli->query returns TRUE - if it returned FALSE you should see the MySQL error not "Success"

So I am guessing the problem is in how you interpret the return from the service call. Can we see that code.
I changed the $_GET to $_POST, as a GET gives other error messages; it is not correct either, as we say in startSide2DB with the line type: 'POST', that we are going to POST.

Here is all the example code I am using currently… You should adopt the IP address & file names, perhaps by uncommenting my changes.

Beside my POST 'solution', I add also a try with GET here. The message with the GET version is
User generated image
(The last POST code with minor improvements returns with a Failed: [success] (see above).)
code.zip
code-with-GET.zip
code-with-POST.zip
Two things I picked up in the code (my error)

1. The newsEnabled value can be 0 which is valid - but it will trigger an invalid parameter message because the check is for a falsy value not explicitly for false. Need to change to
if ($renderedStaticPage !== false && $newsTickerEnabled !== false) {

Open in new window


2. The success message ternary was the wrong way round - should be

$result->message = $result->status ? 'success' : $mysqli->error ;

Open in new window


Full listing here
<?php

// SO THIS CAN BE CALLED FROM A DIFFERENT DOMAIN / PORT / PROTOCOL
header("Access-Control-Allow-Origin: *");
require_once('../db.config.php');

// Our result return
$result = new stdClass;
$result->status = false;
$result->message = 'Fail';

$mysqli = new mysqli($hostname, $username, $password/* , $database */);

// Get the input data safely
$renderedStaticPage = isset($_POST['renderedStaticPage'])
	? $mysqli->real_escape_string($_POST['renderedStaticPage'])
	: false;
$newsTickerEnabled = isset($_POST['newsTickerEnabled'])
	? $mysqli->real_escape_string($_POST['newsTickerEnabled'])
	: false;

// Only proceed if we got valid input
if ($renderedStaticPage !== false && $newsTickerEnabled !== false) {

    $query = <<< QUERY
INSERT INTO 
	StartSite (
		renderedStaticPage, 
		newsTicker_enabled
	 ) 
VALUES (
	'{$renderedStaticPage}',
	'{$newsTickerEnabled}'
)
QUERY;

    $result->status = $mysqli->query($query);
    $result->message = $result->status ? 'success' : $mysqli->error ;
}else {
    $result->message = 'Invalid parameters';
}

die(json_encode($result));
	
?>

Open in new window

I use the last POST version with your corrections now. The message is 'Failed: success'.

Currently, I made some other changes, which I attach to this message. The message is
User generated image
I also added a new GET code. Please see the new attachement. The message is 'Failed: null'. The console shows the line

ipAddress = "http://app.ivm.at/ServiceTest/addStartSite.php?renderedStaticPage='<div name="test22"></div>'&newsTickerEnabled=1"

Open in new window

new-POST-code.zip
new-GET-code.zip
Why are we doing $_GET code? The only reason for doing $_GET was to test the service - once that is working you change back to $_POST and don't use $_GET. To avoid confusion - can we drop the $_GET going forward as the service is working.

The message box that is popping up is not generated by the code you posted. That appears to be rendered by something else - which is putting the Failed into the message. The "success" comes from the service - which indicates that the service is working and the database INSERT is succeeding - can you confirm?

Can we see the code that renders the message box.
Thank you for your comment!! I forgot to write that the data (the one DB record) does not appear in the database! That's why, I test once with GET & once with POST. Here are the contents of the test DB _apptest:
User generated image
I tested the SQL command for some typo in the database SQL tab & saw that the INSERT is OK. I do not see the problem; it's a kind of nightmare…
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
What I see is
User generated image
And there is no new record in the database.
Then there is something wrong with your database code.

I noticed in your code you commented out the $database parameter to new mysqli()

Why was that?

How are you selecting what database to run against?

Bottom line - db code not working - that is why the rest is not working and it is why I originally suggested you test the service script independently of ANY other script (only URL) so that we could get that working first - I was under the impression that had been done.

Add the code to select your database and try the above again.
I feed the $database parameter from the ./general/dbconstant.php file. The last code I used to test is below. I get no errors, the client-side returns with a 'Failed: [null]', and there is still no new data record in the database. The INSERT INTO statement is not the problem – it runs properly when input directly over the SQL tab in the database with

INSERT INTO StartSite (renderedStaticPage, newsTicker_enabled) VALUES ('<div name="test99"></div>', 1);

Open in new window


To come to your last remark, I entered directly the following address to the browser after switching the addStartSiteTest.php to $_GET's by adding the two parameters to the address, removing the data element, and changing the dataType to 'GET', and the data to 'text':

http://app.ivm.at/ServiceTest/addStartSiteTest.php?renderedStaticPage=%27%3Cdiv%20name=%22test22%22%3E%3C/div%3E%27&newsTickerEnabled=1

Open in new window


The browser displayed

{"status":null,"message":null}

Open in new window


but there is of course no authentification when sending directly the IP address over the browser.
POST-code.zip
GET-code.zip
I worked on the problem with my colleague here, and after hours we came to an end: the record is written to the database!!

addStartSiteChristian.php:
<?php

require_once('./general/connectDB.php');

// Get the input data safely
$renderedStaticPage = $_POST['renderedStaticPage'];
	
$newsTickerEnabled = $_POST['newsTickerEnabled'];

// Only proceed if we got valid input
if ($renderedStaticPage !== false && $newsTickerEnabled !== false) {
	$query = "INSERT INTO StartSite (renderedStaticPage, newsTicker_enabled) 
VALUES ('" . $renderedStaticPage . "', " . $newsTickerEnabled . ")";

	$result = MYSQL_QUERY($query);
} else {
	$result = 'Invalid parameters';
}

die(json_encode($result));
	
?>

Open in new window


index.html:
<!DOCTYPE html>
<html>
	<head>
		<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
		<script>
			$(document).ready(function () {
				$('button').click(function () {
					$.post('http://app.ivm.at/ServiceTest/addStartSiteChristian.php',
					{
						renderedStaticPage: '<div name="test99"></div>',
						newsTickerEnabled: 1
					}, function (data, status) {
						alert('Data: ' + data + ', status: ' + status);
					});
				});
			});
		</script>
	</head>
	<body>
		<button>Click me!</button>
	</body>
</html>

Open in new window


The whole code is attached. Thank you very much & have a nice day! You helped alot! :-)
I feed the $database parameter from the ./general/dbconstant.php file.
Yes but you don't use in your code - this is your connection code
$mysqli = new mysqli($hostname, $username, $password/* , $database */);

Open in new window


The working code you posted above does not include the code for the database connection and is substantially the same as the code we have been working with - what did you do differently that enables it now to work?
ASKER CERTIFIED SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
We found at the company using the good advices & code from Julian Hansen the solution to the problem. It was tricky … five days lost for a "simple" (?) POST request, writing a record with two fields to the database. But that's life! :-D Thank you, Julian!