Newbie, 1st post (and desperate). I am trying to get a basic html->javascript->ajax(POST)->php transaction (with passed args) to work. [I also tried (GET) but should use POST to mod server state. right].
My problem: whereas a parameter passed via POST (js->ajax->php) DOES appear in the Params list seen in Firefox's Developer Tools-> Network tab, the PHP code does NOT see it (and isset() = 0).
My php code does execute fine... I am debuging by logging stuff to disk file. My SWAG is that there is something wrong with the syntax I use to assemble the param being sent via .send(); [in jsMyFunc()
in the example below]. I have tried every possible suggestion found on numerous www.sites and am out of ideas.
Am using Firefox 54.0.1 on W7/64 talking to a Rasperry Pi 3B. Apache is in the mix. I have tons of other code working (HTML+JS+PHP(server side), etc. but this one has stumped me. I am relatively new to most of this so my code is adapted from the <sarcasm>
plethora of defect free examples to be found on the www</sarcasm>
but I have spent 12+ hours reading, testing, reading, etc. thus this post. I simplified the code to the minimum so maybe one of y'all can help?
Also, (at the risk of being greedy), what is the syntax for sending 2 text params? I was trying to do that for quite a while until I realized that passing a single param didn't work either. I would like to send 2 params to the server: gpio_bit
and state
(see below).
Please, no need to tell me this is a duplicate bug... been there, read them all. And I really don't want to learn jquery, KISS for a very simple requirement. Any help greatly appreciated.
Main (entire file)
<!DOCTYPE html>
<html>
<head>
<script src='jsMyJS.js'></script>
</head>
<body>
<b><button type='button' onclick='jsMyFunc()'>Test</button></b>
</body>
</html>
Javascript: jsMyJS.js
(entire file)
function jsMyFunc() {
console.log('Executing: jsMyFunc()');
var gpio_bit = 4;
var state = 0;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if( this.readyState == 4 ) {
if( this.status == 200 ) {
alert( 'DONE' );
} else {
alert( 'ERROR: status = ' + status );
}
}
}
xhttp.open( 'POST', 'pMyPHP.php', true );
xhttp.setRequestHeader( 'Content-Type', 'text/plain', 'Content-length', state.length ); // Or 'text'
var myArgs = 'state=' + state; // <<<<<<<<<< HERE ???
xhttp.send( myArgs );
}
PHP: pMyPHP.php
(entire file)
<?php
// Using file writes to debug server code... sigh...
$f = fopen("debug.txt", "w");
fwrite( $f, "\nExecuting: pMyPHP.php()\n" );
$str = "xxxx";
fwrite( $f, "str 1 = " . $str . "\n" ); // OK
if (isset($_POST['state'])) {
$str = $_POST['state'];
fwrite( $f, "str 2 = " . $str . "\n" ); // NEVER
} else {
fwrite( $f, "str 3 = NULL\n" ); // ALWAYS
}
fclose( $f );
?>