Search code examples
javascriptjqueryajaxgoogle-apps-scriptweb-applications

Posting Array data in Ajax in JavaScript and Reading the parameter at server side


I am posting array data in json format to Google app script server.My concern is how to read the data at serverside

                var url = myappscripturl;
                var mydata = { 
                    name : "sunil",
                    arraydata :  [
                        {
                            phone:'7898',
                            landline : '2678-789'
                        },
                        {
                            phone:'87658',
                            landline : '0672348'
                        }

                    ] 
                };
                $.ajax({
                    url : url,
                    method:'POST',
                    data:mydata,
                    success: function(data){
                        console.log(data);
                    }
                })

//Google App Script doPost method:

function doPost(e){
try{
var result = {"result7":e.parameter};
var jsondata = JSON.stringify(result);
return ContentService.createTextOutput(jsondata).setMimeType(ContentService.MimeType.JSON);
}
catch(e){
var error = {"error":e};
  var jsonerror = JSON.stringify(error);
  return ContentService.createTextOutput(jsonerror).setMimeType(ContentService.MimeType.JSON);

}
}

Getting Response in the Console:

result7:
arraydata[0][landline]: "2678-789"
arraydata[0][phone]: "7898"
arraydata[1][landline]: "0672348"
arraydata[1][phone]: "87658"
name: "sunil"

How do i read the phone numbers at server side ? Tried to use the JSON.parse(e.parameter) at serverside but it is not working


Solution

  • Notes:

    • jquery's POST method, by default posts content as application/x-www-form-urlencodedand not as application/json.

    • POST is sent as:

      arraydata[0][phone]=7898&
      arraydata[0][landline]=2678-789&
      name=sunil&
      arraydata[1][landline]=0672348&
      arraydata[1][phone]=87658
      
    • Note that arraydata is converted as plain string keys.

    • You can access the phone as

      const phone = e.parameter["arraydata[1][phone]"];//87658
      const phones = e.parameters["arraydata[1][phone]"];//[87658]
      

    References: