0

So I am using query strings to pass data from a form to my server. The query strings look like this:

this.$http.post('http://localhost:3000/operation?Stime='+this.Stime+'&Etime='+this.Etime+'&eAMPM='+this.eAMPM+'&sAMPM='+this.sAMPM+'&id='+this.id+'&activity='+this.activity+'&auto_insert='+this.auto_insert+'&yearmonthday='+this.yearmonthday+'&color1='+this.c)

and In my server I have all these variables to store the query's variables:

var color = req.query.color1; 
var Stime = req.query.Stime; 
var Etime = req.query.Etime;
var sAMPM = req.query.sAMPM;
var eAMPM = req.query.eAMPM;
var id = req.query.id;
var activity = req.query.activity;
var requestAccepted = req.query.requestAccepted;
var yearmonthday = req.query.yearmonthday;
var auto_insert = req.query.auto_insert;

It just seems like a lot of code to just post my variables to the server (It works just fine) but I was wondering if there were some ways I could refactor it/ make it cleaner

Matt
  • 501
  • 4
  • 14
  • is it angular http module? then use the data attribute to send data as JSON object – shakeel osmani Jul 27 '17 at 17:00
  • 1
    JSON is your friend here. It will go as the payload of the request. You can still keep a few query strings for routing. I'm not answering the question since I'm in a hurry right now, but I'm pretty much sure this is the best approach: https://stackoverflow.com/questions/10955017/sending-json-to-php-using-ajax – Loudenvier Jul 27 '17 at 17:00
  • well... I am not entirely sure why would you create local copies of members of query on the server. Still, which library/framework are you using on the client side? In angular or jquery, for example, you usually have to configure your request with provided APIs and not to combine url's by hand. – Vladimir M Jul 27 '17 at 17:12

1 Answers1

0

Of course there is!

Consider doing some research into the HTTP message body:

A message body is the one which carries the actual HTTP request data (including form data and uploaded, etc.) and HTTP response data from the server ( including files, images, etc.).


In your case, you can change your Angular $http POST request to as follows -

var data = { 
  Stime: '+this.Stime+',
  Etime: '+this.Etime+',
  eAMPM: '+this.eAMPM+',
  sAMPM: '+this.sAMPM+',
  id: '+this.id+',
  activity: '+this.activity+',
  auto_insert: '+this.auto_insert+',
  yearmonthday: '+this.yearmonthday+', 
  color1: '+this.c+'
}

$http({
  method: 'POST',
  url: 'http://localhost:3000/operation',
  data: JSON.stringify(data)
})
Trent
  • 4,208
  • 5
  • 24
  • 46
  • If using angular 1.x, it might be more desirable to use [resources](https://docs.angularjs.org/api/ngResource/service/$resource) – Vladimir M Jul 27 '17 at 17:18