I'm looking for a good approach to AJAX communication using only pure JS and PHP. I would like it to be as safe as possible and compatible with most modern browsers and IE 10+. I did some research and found some code examples for writing a vanilla JS function to handle AJAX communication, but I was not sure how safe and up to date those were. I started coding my own solution based on what I've found. I need to receive and send data using AJAX. There will be a login system and also a text posting system.
index.html
<input type="checkbox" id="agreement"/> I agree with terms.
<input type="text" id="user"/> User
<input type="password" id="password"/> Password
<textarea id="text"></textarea> Text
<button id="submit" onclick="submit_form()">Submit</button>
<span id="result"></span>
ajax.php
if($_GET['action'] == 'submit_form')
{
$agreement = $_POST['agreement'];
$user = $_POST['user'];
$password = $_POST['password'];
$text = $_POST['text'];
echo 'Data received: <br/>';
echo 'Agreement: '.$agreement.'<br/>';
echo 'User: '.$user.'<br/>';
echo 'Password: '.$password.'<br/>';
echo 'Text: '.$text.'<br/>';
}
scrip.js
function submit_form()
{
var ajax = new XMLHttpRequest();
ajax.open('POST', 'ajax.php?action=submit_form', true);
ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
var content = '';
content = content + 'agreement=' + document.querySelector('#agreement').checked;
content = content + '&user=' + document.querySelector('#user').value;
content = content + '&password=' + document.querySelector('#password').value;
content = content + '&text=' + document.querySelector('#text').value;
ajax.send(content);
ajax.onreadystatechange = function()
{
if (ajax.readyState == 4 && ajax.status == 200)
{
document.querySelector('#result').innerHTML = ajax.responseText;
}
}
}
Can you spot any problems with this approach? Are there better, simpler or more cross-browser compatible ways for doing the same? Are there any special concerns I should have when sending and receiving passwords?