简体   繁体   中英

Collect multiple forms data as JSON with Javascript and send via AJAX to PHP

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?

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'];

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)

} 

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM