Search code examples
gogo-iris

Reading Json Form data golang


I am sending form data in JSON & serialize format to golang server using ajax. I am not able to read those data.

I am using kataras/iris golang framework.

Below is my code -

(function ($) {
    $.fn.serializeFormJSON = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
})(jQuery);

var Contact = {
    sendMessage: function() {
      return m.request({
          method: "POST",
          url: "/send/message",
          data: JSON.stringify(jQuery('#contact-form').serializeFormJSON()),
          withCredentials: true,
          headers: {
              'X-CSRF-Token': 'token_here'
          }
      })
    }
}
<!-- Data looks like below, what is sent -->
"{\"first_name\":\"SDSDFSJ\",\"csrf.Token\":\"FjtWs7UFqC4mPlZU\",\"last_name\":\"KJDHKFSDJFH\",\"email\":\"DJFHKSDJFH@KJHFSF.COM\"}"

And I am trying to fetch the data from server using below code -

// Contact form
type Contact struct {
    FirstName string `json:"first_name"`
    LastName  string `json:"last_name"`
    Email     string `json:"email"`
}

contact := Contact{}
contact.FirstName = ctx.FormValue("first_name")
contact.LastName = ctx.FormValue("last_name")
contact.Email = ctx.FormValue("email")
ctx.Writef("%v", ctx.ReadForm(contact))

My all data is blank, How to grab the data? I am using https://github.com/kataras/iris golang framework.


Solution

  • One the one hand, you are sending a JSON to the server, but when fetching the parameters you are fetching them as "application/x-www-form-urlencoded", first, send the JSON parameters as JSON and not as string, remove the stringifying, i.e:

    instead of:

    JSON.stringify(jQuery('#contact-form').serializeFormJSON())
    

    do:

    jQuery('#contact-form').serializeFormJSON()
    

    and in your Go file, bind it to your object:

    var contact []Contact 
    err := ctx.ReadJSON(&contact) 
    

    good luck :)