I am not sure if I am missing the point with JSON because from what I have seen; tutorials, examples and questions do not involve posting form data via JSON/AJAX to PHP.
I see a lot of examples using jQuery but I have not learned jQuery yet because I am told that getting an understanding of Javascript first is best and then use jQuery as shorthand later.
I can 'collect' my form data and process and output a string which I believe to be JSON syntax.
"{p1:{'lname':'adsfer','fname':'asdf','email':'ewrt','sex':'male'},p2:{'lname':'erty','fname':'erty','email':'erty','sex':'male'}}"
HTML
<form id="p1">
<h2>Add Person 1:</h3>
Surname: <input type='text' name='lname' value='' ><br>
First Name:<input type='text' name='fname' value='' ><br>
Email: <input type='email' name='email' value=''><br>
Sex:<select name='sex'><option></option><option value='male'>Male</option><option value='female'>Female</option></select>
</form>
<form id="p2">
<h2>Add Person 2:</h3>
Surname: <input type='text' name='lname' value='' ><br>
First Name:<input type='text' name='fname' value='' ><br>
Email: <input type='email' name='email' value=''><br>
Sex:<select name='sex'><option></option><option value='male'>Male</option><option value='female'>Female</option></select>
</form>
<button onclick='submit_forms()'>Next</button>
Javascript
function submit_forms(){
var div = "content";
var url = "contract.php";
var forms = document.forms;
var txt = "{";
for(var i = 0 ;i<forms.length;i++){
txt += forms[i].id + ':{';
for(var n=0;n<forms[0].length;n++){
txt += "'" + forms[i][n].name + "':'" + forms[i][n].value +"',";
}
txt = txt.substring(0,txt.length-1);
txt += '},';
}
txt = txt.substring(0,txt.length-1);
txt +='}';
txt = JSON.stringify(txt);
alert(txt)
post_JSON_PHP(txt,div,url);
}
function post_JSON_PHP(vars,div,url){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(div).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/JSON");
xmlhttp.send(vars);
}
PHP
$json = json_decode($_POST['p1']);
var_dump($json);
PHP replies with Notice: Undefined index: p1 for line and NULL.
Is it just that I have some wrong syntax or am I totally on the wrong track?