I am currently working on a little project for my PLC. I use PHP to open a connection to said PLC.
I have created a little website to make interacting easier.
What I want to include on this website is a couple of toggles to send different commands to the device.
I want this done without having to reload the website, so what my researches came up with was to use AJAX.
Now I have tried multiple tutorials on AJAX onclick events using normal buttons and toggles....but none of them gave me the results I wanted.
What would be the easiest way to accomplish what I need?
When the button is pressed I need to execute this php code
$plc->WriteBit("E", 0, 0, 0, 1);
When the button is pressed again I need this to execute
$plc->WriteBit("E", 0, 0, 0, 0);
All this should work without reloading the site.
Like I said I have really no clue how to parse this php code directly from AJAX. I hope someone can push me in the correct direction!
Thanks!
Try something like this:
MULTIPLE BUTTONS/ADDRESSES:
<input type='button' name='writeA' value='WRITE BIT A' data-bit='1' data-address='000' class='plc'>
<input type='button' name='writeB' value='WRITE BIT B' data-bit='0' data-address='001' class='plc'>
<div id='output'></div>
jQuery:
$(document).on('click', 'input.plc', function() {
var bit = parseInt($(this).attr('data-bit'));
var address = $(this).attr('data-address');
$('#output').load('plc.php', {'bit':bit, 'address':address});
$(this).attr('data-bit', bit^1); // xor bit to toggle value
});
PHP script (plc.php):
$bit = isset($_POST["bit"]) ? $_POST["bit"] : 0;
$address = isset($_POST["address"]) ? $_POST["address"] : '000';
$lst_address = str_split($address);
$plc->WriteBit("E", $lst_address[0], $lst_address[1], $lst_address[2], $bit); // or use an 'if' or 'switch' statement
echo $bit;
First, you will have to send an ajax request on button click. For this you can use jQuery.
<button type="button" onclick="callAjax();" value="My Button">My Button</button>
Than in callAjax() function you can send an ajax request to a php page.
function callAjax(){ //your ajax call will come here }
You can check jQuery ajax api here https://api.jquery.com/jQuery.ajax/
In you PHP page print response of your above mentioned fucntion accordingly.
echo ($anyFlag == 1)? $plc->WriteBit("E", 0, 0, 0, 1) : $plc->WriteBit("E", 0, 0, 0, 0);
Than in success method of jQuery ajax call you can check response and react accordingly.