Simple Custom POST Request

Simple Custom POST Request

SnacklesSnackles Posts: 33Questions: 8Answers: 0

Hi all,

I have a button within my DataTables Editor form that opens a prompt and requests the user to enter a string. The string that's entered is then supposed to be sent to the SQL server and update the table. The controller that this string is sent to uses Editor code.

I attempted to mimic the format of data sent from when I submit the form. The requests looks successful, but the table on the SQL server is never updated.

JavaScript:

// Enter new Brand
$(document).on('click', '#newbrand', function () {
    var newbrand = prompt("Please enter the new brand:");
    if (newbrand == null || newbrand == "") {
        txt = "User cancelled the prompt.";
    } else {

        brand = newbrand.toUpperCase();
        console.log(brand);

        function CreateNewBrand() {
            $.ajax({
                url: "api/CreateNewBrand",
                type: "GET",
                dataType: "json",
                data: {
                    'data[0][Brands][brand]': brand
                },
                error: function (error) {
                    console.log(`Error ${error}`);
                }
            });
        };

        CreateNewBrand();

        editorNP.field('ProductUpdates.OBJ_TAB_F155').val(newbrand);
    }
});

Controller:

public class NewBrandController : ApiController
{
    [Route("Maintenance/api/CreateNewBrand")]
    [HttpGet]
    [HttpPost]
    public IHttpActionResult ProductUpdates()
    {
        var request = HttpContext.Current.Request;
        var settings = Properties.Settings.Default;

        using (var db1 = new Database(settings.DbType, settings.DbConnection1))
        {
            var response = new Editor(db1, "Brands", "Brand")
                .Field(new Field("Brand")
                )
                 .Process(request)
                .Data();

            return Json(response);

        }
    }
}

This question has an accepted answers - jump to answer

Answers

  • SnacklesSnackles Posts: 33Questions: 8Answers: 0

    I added action: 'create', but it looks like there isn't any data being sent. How would I properly format the brand variable to be sent and accepted by the SQL server?

    function CreateNewBrand() {
        $.ajax({
            url: "api/CreateNewBrand",
            type: "POST",
            dataType: "json",
            data: {
                action: 'create',
                'data[0][Brands][Brand]': brand
            },
            error: function (error) {
                console.log(`Error ${error}`);
            }
        });
    };
    
    

  • SnacklesSnackles Posts: 33Questions: 8Answers: 0

    I realized the table I was attempting to update didn't have a key set within the SQL server. The table only has one column, Brand, so I set that as the key and then updated my controller and now it's updating the table!

    Now the issue is after the POST, the editor field within my form doesn't update to reflect the newly enter brand name.

    I'm hoping to leverage dependent() to update the editor field after submitting the new brand through the JavaScript prompt.

    This is my current setup:

    JavaScript:

    // Enter new Brand
    $(document).on('click', '#newbrand', function () {
        var newbrand = prompt("Please enter the new brand:");
        if (newbrand == null || newbrand == "") {
            txt = "User cancelled the prompt.";
        } else {
    
            brand = newbrand.toUpperCase();
    
            function CreateNewBrand() {
                $.ajax({
                    url: "api/CreateNewBrand",
                    type: "POST",
                    dataType: "json",
                    data: {
                        action: 'create',
                        'data[0][Brands][Brand]': brand
                    },
                    error: function (error) {
                        console.log(`Error ${error}`);
                    }
                });
            };
    
            CreateNewBrand();
            editorNP.field('ProductUpdates.OBJ_TAB_F155').val(brand);
        }
    });
    
    

    Controller:

    public class NewBrandController : ApiController
    {
        [Route("Maintenance/api/CreateNewBrand")]
        [HttpGet]
        [HttpPost]
        public IHttpActionResult ProductUpdates([FromBody] string brand)
        {
            var request = HttpContext.Current.Request;
            var settings = Properties.Settings.Default;
    
            using (var db1 = new Database(settings.DbType, settings.DbConnection1))
            {
                var response = new Editor(db1, "Brands", "Brand")
                    .Field(new Field("Brands.Brand")
                    )
                    .Debug(true)
                     .Process(request)
                    .Data();
    
                return Json(response);
    
            }
        }
    }
    
    
  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin

    Now the issue is after the POST, the editor field within my form doesn't update to reflect the newly enter brand name.

    Can you show me the JSON that the server is responding with please?

    Thanks,
    Allan

  • SnacklesSnackles Posts: 33Questions: 8Answers: 0

    If I exit the form and reload the page or exit the form and set the DataTable to refresh then reopen the form the brand shows up.

    Ideally, "TEST BRAND" should show up below "TEST" in the select list right after entering the new brand.

    Also, it appears to be returned in the same format as when I do a GET request?

    Thank you, Allan! I appreciate your help.

  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin

    Is that the data that is loaded after an edit request? If so, it would suggest you are editing 100 rows at a time?

    I suspect that is the initial load data, so can you show me the JSON from after an edit request please?

    Allan

  • SnacklesSnackles Posts: 33Questions: 8Answers: 0

    The first image is the data that's loaded after an edit request. As far as I can tell it's showing only 1 record.

    The 2nd image is a GET request/initial load just for a comparison of format.

  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin
    Answer ✓

    Sorry - yes I'm with you now. I missed that distinction yesterday.

    I suspect the space in your id values is going to be messing with things since that doesn't allow it to be a valid ID selector.

    Is that the only value you can index off, or do you have a sequence number in the database you could use?

    Thanks,
    Allan

  • SnacklesSnackles Posts: 33Questions: 8Answers: 0

    Is that necessary? The POST request is successful. If I refresh the web page the newly added value shows up in the select list.

    I merely just need a way to refresh the select list within the Editor form after entering the new value without without having to close the form or refresh the web page.

  • SnacklesSnackles Posts: 33Questions: 8Answers: 0

    I ended up figuring something out after seeing a comment by brendons on the select documentation!

    On my Editor form, I have a button next to a select list for adding new options to the database. When clicked, a JavaScript prompt appears and the user can enter the new option. The string is sent to the POST controller, added to the SQL server, and then the GET controller is requested to refresh the select list.

    The SetNewBrand.done function part of the code was the key to get the select list on my form to update with the newly added string. I'm able to manipulate the data to have label/value properties and update the select list with the new array.

    So, thank you brendons and thank you Allan!

    JavaScript:

    // Enter new Brand
    $(document).on('click', '#newbrand', function () {
        var newbrand = prompt("Please enter the new brand:");
        if (newbrand == null || newbrand == "") {
            txt = "User cancelled the prompt.";
        } else {
    
            brand = newbrand.toUpperCase();
    
            var CreateNewBrand = $.ajax({
                url: "api/CreateNewBrand",
                type: "POST",
                dataType: "json",
                data: {
                    action: 'create',
                    'data[0][Brands][Brand]': brand
                },
                error: function (error) {
                    console.log(`Error ${error}`);
                }
            }),
                SetNewBrand = CreateNewBrand.then(function (data) {
                    return $.ajax({
                        url: "api/RefreshBrand",
                        type: "GET",
                        dataType: "json",
                        error: function (error) {
                            console.log(`Error ${error}`);
                        }
                    });
                });
    
            var optionsA = [];
            SetNewBrand.done(function (data) {
                var option = {};
                for ($i = 0; $i < data.data.length; $i++) {
                    option.label = data.data[$i].Brands.Brand
                    option.value = data.data[$i].DT_RowId
                    optionsA.push(option);
                    option = {};
                };
                editorNP.field('ProductUpdates.OBJ_TAB_F155').update(optionsA);
            });
    
            editorNP.field('ProductUpdates.OBJ_TAB_F155').val("row_" + brand)
        }
    });
    

    POST Controller with .NET Editor code:

    [Route("Maintenance/api/CreateNewBrand")]
    [HttpGet]
    [HttpPost]
    public IHttpActionResult ProductUpdates([FromBody] string brand)
    {
        var request = HttpContext.Current.Request;
        var settings = Properties.Settings.Default;
    
        using (var db1 = new Database(settings.DbType, settings.DbConnection1))
        {
            var response = new Editor(db1, "Brands", "Brand")
                .Field(new Field("Brands.Brand")
                )
                .Process(request)
                .Data();
    
            return Json(response);
        }
    }
    
    

    GET Controller with .NET Editor code:

    [Route("Maintenance/api/RefreshBrand")]
    [HttpGet]
    [HttpPost]
    public IHttpActionResult RefreshBrand()
    {
        var request = HttpContext.Current.Request;
        var settings = Properties.Settings.Default;
    
        using (var db1 = new Database(settings.DbType, settings.DbConnection1))
        {
            var response = new Editor(db1, "Brands", "Brand")
                .Field(new Field("Brands.Brand")
                )
                .Process(request)
                .Data();
    
            return Json(response);
        }
    }
    
    
  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin

    That looks spot on - nice one. The other way would be to use a success callback from your $.ajax call (which is basically the same thing as the done method).

    Good to hear you've got it working the way you need now!

    Allan

This discussion has been closed.