Convert HTML Form to JSON


Option -1:
function form_to_json(selector) {
    var ary = $(selector).serializeArray();
    var obj = {};
    for (var a = 0; a < ary.length; a++) obj[ary[a].name] = ary[a].value;
    return obj;
}

//Example
var mydata = form_to_json('#form');
JSON.stringify(mydata);
---------------------------------------------------------

Option-2:
Using Third party JQuery plugin- http://maxatwork.github.io/form2js/

<script src="form2js.js"></script>
<script src="jquery.toObject.js"></script>

var data = $('#form').toObject({skipEmpty:false});
JSON.stringify(data)
Advertisements

Working With ION In Android

//
//Android Code
//


//Manifest
<uses-permission android:name="android.permission.INTERNET"/>

//build.gradle (Module:app)
dependencies {
    ...
    compile group: 'com.koushikdutta.ion', name: 'ion', version: '2.1.6'
}

//MainActivity.java
    public void SubmitData(View view){

        JsonObject json = new JsonObject();
        json.addProperty("foo", "bar");
        json.addProperty("bar", "foo");
        try
        {
            Ion.with(getApplicationContext())
                    .load("http://182.160.99.115:1012/Home/SubmitData")
                    .setJsonObjectBody(json)
                    .asJsonObject()
                    .setCallback(new FutureCallback<JsonObject>() {
                        @Override
                        public void onCompleted(Exception e, JsonObject result) {

                         String ServerSaid =  result.get("serversay").getAsString();

                            Toast.makeText(getApplicationContext(),ServerSaid,Toast.LENGTH_LONG).show();
                        }
                    });

        }
        catch (Exception ex ){
            Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
        }
    }
//
//ASP.NET MVC Code
//


namespace WorkingWithIon.Controllers
{
    public class HomeController : Controller
    {     
        public JsonResult SubmitData(string foo, string bar)
        {
            return Json(new{serversay=foo + " and " + bar}, JsonRequestBehavior.AllowGet);
        }
    }
}

Upload file from WinForm application to server

using BizArk.Core.Web; // http://bizark.codeplex.com/
var response = WebHelper.MakeRequest
                  ("http://Domain.com/Home/ReceiveAudio/",
                    new
                       {
                          wavFile = new FileInfo(e.FullPath)
                          //Test = "Hello",
                          //File1 = new UploadFile(@"text\plain", "file1.txt", 
                                   new MemoryStream(Encoding.UTF8.GetBytes("Hello "))),
                          //File2 = new FileInfo("MyFile.txt")
                        });

var result = response.ResultToString();

Periodically send ajax request to server from JavaScript

<script>
    function executeQuery() {
        $.ajax({
            url: 'http://localhost:54802/Calls/CheckNewVoices/',
            type: 'POST',
            data: "{'lastcheckdatetime':'" + lastCheckDateTime + "'}",
            dataType: 'json',
            contentType:'application/json; charset=utf-8',
            success: function (response) {
                lastCheckDateTime = response.lastcheckdatetime;
                console.log(lastCheckDateTime);
                var files = response.files;
                files.forEach(function (file, index) {
                    //Do something
                });
                setTimeout(executeQuery, 30000); //Call after 30 seconds.
            }
        });
    }

    $(function () {
        setTimeout(executeQuery, 30000); //Call after 30 seconds.
    });
</script>

Standard JQuery-Ajax Code Template (v.2)

$.ajax({
    type: 'POST',
    url: '../../../../AreaName(If any)/ControllerName/MethodName/',
    //If datatype is of FormCollection, following 3 lines are not needed-
    //====================================================
    //contentType: 'application/json; charset=utf-8',
    //data: "{'agentdata':'"+ agentdata +"'}",
    //OR, data:JSON.stringify({ key1: value1, key2: value2}),
    //dataType: 'json',
    //====================================================
    //If datatype is of FormCollection, following 3 lines are needed-
    //====================================================
    //processData: false,  // tell jQuery not to process the data
    //contentType: false,   // tell jQuery not to set contentType    
    //data: Data,
    //====================================================
    beforeSend: function () {
        $('SubmitButton').attr('disabled', 'disabled');
        $('SubmitButton').html('Working…');
    },
    success: function (result) {
        if (result == 'Success') {
            SuccessfullSaveNotification();
            ResetMainForm(MainForm);
        }
        else {
            ShowRegularError(result);
        }
    },
    error: function (request, status, error) {
        ShowRegularError('Failed to save. Error Details – Request: ' + request + ', Status: ' + status + ', Error: ' + error);
    },
    complete: function () {
        $('SubmitButton').removeAttr('disabled');
        $('SubmitButton').html('Save changes');
    }
});

Sending List/Datatable from MVC Controller to JQuery-AJAX

Option A: Send as List

//Server Side       
public class Person
{
    public int Id { get; set; }
    public String Name { get; set; }
}

[HttpPost]
public JsonResult GetData()
{
    List<Person> persons = PersonManager.GetList();
    return Json(new { ServerResponse = "Success", PersonList = persons },                     
          JsonRequestBehavior.AllowGet);
}
//Client Side
success: function (response) {
      if (response.ServerResponse === "Success") {
          var persons = response.PersonList;                        
          //Looping persons array without any function parameter
          $.each(persons, function () {
                console.log('Id-' + this.Id + ', Name-' + this.Name);
          });

          //Looping persons array with function parameter
          $.each(persons, function (index, person) {
                 console.log('SL-' + index + ', Id-' + person.Id + ', Name-' + person.Name);
                 $.each(person, function (key, value) {
                       console.log(key + ':' + value);
                 });
          });

          //JavaScript Loop
          persons.forEach(function (person,index) {
                console.log('Id-' + person.Id + ', Name-' + person.Name);
            });
      }
},

Option A: Send as DataTable

//Server side
using Newtonsoft.Json;

[HttpPost]
public JsonResult GetData()
{
    DataTable persons = PersonManager.GetList(); //As DataTable
    String SerializedDatatable = JsonConvert.SerializeObject(persons, Formatting.None);
    return Json(new { ServerResponse = "Success", PersonList = persons },                     
                    JsonRequestBehavior.AllowGet);
}


//Client Side
success: function (response) {
         if (response.ServerResponse === "Success") {
               var persons = JSON.parse(response.PersonList);
                       
               //Looping persons array without any function parameter
               $.each(persons, function () {
                      console.log('Id-' + this.Id + ', Name-' + this.Name);
               });

               //Looping persons array with function parameter
               $.each(persons, function (index, person) {
                     console.log('SL-' + index + ', Id-' + person.Id + ', Name-' + person.Name);
                     $.each(person, function (key, value) {
                           console.log(key + ':' + value);
                     });
               });


               //JavaScript Loop
               persons.forEach(function (person,index) {
                   console.log('Id-' + person.Id + ', Name-' + person.Name);
               });
         }
},