skip to Main Content

I have a form in an html page. I want to submit values to the following api using ajax.

{
    "userName": "john",
    "description": "funny dood",
    "address": 
        {
            "addressLine1": "house number from formdata",
            "addressLine2": "some value picked from form",
            "daDa": "some val from form"
        }
    
}

I am using the following snippet to submit to the api using jquery ajax:

function AjaxSubmit(form_Data){
var ajaxOptions =
    {
        type:"POST",
        contentType: "multipart/form-data",        
        url: "/api/Users/",
        data: form_Data,
        success: function (result) {
            alert(result);
            window.location.href = "/Home/Index"
        }
    }

    if ($(form_Data).attr('enctype') == "multipart/form-data") {
        ajaxOptions['contentType'] = false;
        ajaxOptions['processData'] = false;
    }

    $.ajax(ajaxOptions);
    return false;
}

The issue is how can i pass the address values to various fields inside the address object.
The api is built on .net core, just fyi.
Thanks 🙂

2

Answers


  1. Is your problem that how to use JS getting an object form_Data ?

    Maybe this is your issue:

    var form_Data = {};
    var userName = ${'#some_id1').val();
    var description = ${'#some_id2').val();
    var addressLine1 = ${'#some_id3').val();
    var addressLine2 = ${'#some_id4').val();
    var daDa = ${'#some_id5').val();
    form_Data['userName'] = userName;
    form_Data['description'] = description;
    form_Data['address'] = {};
    form_Data['address']['addressLine1'] = addressLine1;
    form_Data['address']['addressLine2'] = addressLine2;
    form_Data['address']['daDa'] = daDa;
    
    Login or Signup to reply.
  2. parametername is varibales in the controller.

    function AjaxSubmit(form_Data){
    var ajaxOptions =
        {
            url: "/api/Users/",
            type:"POST",        
            data: JSON.stringify({parametername: form_Data}), 
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                alert(result);
                window.location.href = "/Home/Index"
            }
        }
    
        if ($(form_Data).attr('enctype') == "multipart/form-data") {
            ajaxOptions['contentType'] = false;
            ajaxOptions['processData'] = false;
        }
    
        $.ajax(ajaxOptions);
        return false;
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search