Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
add comment

4 Answers

I did not know that when the content type is set to JSON it does NOT give the PHP page POST data, therefore it can not be retrieved with $_POST.

Using this PHP code worked for me AFTER I removed the stringify function from my javascript

$json = json_decode(file_get_contents('php://input'),true);
echo $json['p1']['fname'];
share|improve this answer
add comment
up vote 0 down vote accepted

In case it helps anyone else, my code above was building JSON text string but I found that it had limitations.

Instead I built a JavaScript object and then converted that object to JSON using the JSON.stringify function.

This script works even if I amend the form AND it handles ARRAYs of forms with the same name.

After researching endlessly I found that there is a jQuery function that does the same thing plus more and probably more elegantly. However, if you are like me and haven't learned jQuery yet; you might find this useful

function submit_forms(){
    var div = "content";    //for AJAX call
    var url = "process.php";    //for AJAX call
    var form = document.forms;
    var ppl = {};
    for(var i = 0;i<form.length;i++){
        if (ppl[form[i].name]){
            ppl[form[i].name].push({});
        } else {
            ppl[form[i].name] = [{}];
        }
        var index = ppl[form[i].name].length-1;
        for (var n=0;n<form[i].length;n++){
            ppl[form[i].name][index][form[i][n].name] = form[i][n].value;
        }
    }
    console.log(ppl);
    var vars = JSON.stringify(ppl);
    ajax_json(vars,div,url)

} 
share|improve this answer
add comment

As I understood you are trying to send a row data in request body, so server can't recognise that you are sending a form data, that's why your $_POST array is empty.

Check out this link

You should send header Content-type as application/x-www-form-urlencoded and serialise your form data not as json string but as urlencoded.

xmlhttp.open("POST","ajax_test.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");

In this case your data will be available in your php script as form data.

share|improve this answer
    
Thank you for your reply, I had hoped that I could send JSON data to the server (nested objects/arrays etc) instead of standard key=value type post data, do you know if this is possible? –  rosscosack Aug 13 '13 at 4:17
add comment

JSON keys and values must be enclosed on double quotes:

'{ "key": "value1", "key2": "value2", "object": { "prop": "value" } }'
"{ \"key\": \"value1\", \"key2\": \"value2\", \"object\": { \"prop\": \"value\" } }"

After a successful decode on PHP, you should use it as an object, not an array:

$class = json_decode('{ "key": "value", "sclass": { "name": "abc", "surname": "xyz" } }');
echo $class->key; // = value
echo $class->sclass; // Error: cannot convert std class to string
echo $class->sclass->name; // = abc
share|improve this answer
    
In PHP, quotes don't matter. You can use double to quote and double on the inside too, you just need to do \" –  Cole Johnson Aug 13 '13 at 3:37
    
But why when parsing json, if I send this (using AJAX): r={'sclass': {'prop': 'value'}} PHP doesn't decode it right? Whereas if I send this: r={"sclass": {"prop": "value"}} It works :S. I know quotes doesn't matter for PHP –  Skaparate Aug 13 '13 at 4:10
1  
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested. : json.org –  jeff Aug 13 '13 at 6:01
    
I know that, but json_decode needs double quotes for keys and values. I have tested it using ajax and there is a difference. –  Skaparate Aug 13 '13 at 15:13
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.