0

I've got working code in JQuery Ajax, however I've been told I have to use Native JS code to use it, and I'm not very familiar with using native JS for ajax, and most of the internet examples are basic ones. Basically, I have this object:

 var Narudzba =
        {
            SifraNarudzbe: "AAA",
            DatumNarudzbe: "",
            Osigurano: document.getElementById("checkOsiguranje").value,
            BrzaDostava: document.getElementById("checkBrza").value,
            KlijentId: document.getElementById("klijentid").value,
            Adresa: AdresaVar,
            StatusNarudzbeID: 2,
            Primaoc: PrimaocVar,
            VrijemeIsporuke: null,
            CijenaNarudzbe: UkupnaCijena,
            NacinPlacanja: parseInt(document.getElementById("NacinPlacanja_Select").value)
        };

Which I'm trying to post to my Controller. Here's how my working code in Jquery Ajax looks:

$.ajax({
    url: "/klijentarea/klijent/SnimiNarudzbu",
    data: Narudzba,
    type: 'POST',
    success: function (data) {
        for (var i = 0; i < stavke_niz.length; i++) {
            stavke_niz[i].NarudzbeId = parseInt(data);
        }
        stavke_niz = JSON.stringify(stavke_niz);
        $.ajax({
            url: "/klijentarea/klijent/SnimiStavke",
            type: "POST",
            dataType: "json",
            data: stavke_niz,
            contentType: 'application/json',
            success: function (data) {
                if (data === true) {
                    var id = document.getElementById("klijentid").value;
                    window.location.href = '/KlijentArea/Klijent?id=' + id;
                }
            }
        });
    }

});

Basically, it creates an order (Narudzba) with all sorts of details, posts it to this controller:

[HttpPost]
public int SnimiNarudzbu(Narudzbe Narudzba)
{
    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    var stringChars = new char[8];
    var random = new Random();

    for (int i = 0; i < stringChars.Length; i++)
    {
        stringChars[i] = chars[random.Next(chars.Length)];
    }

    var finalString = new String(stringChars);

    Narudzba.SifraNarudzbe = finalString;
    Narudzba.DatumNarudzbe = DateTime.Now;
    ctx.Primaoci.Add(Narudzba.Primaoc);
    ctx.Naruzbee.Add(Narudzba);
    ctx.SaveChanges();
    int newid = Narudzba.Id;
    return newid;
}

Then I use the returned new ID, and assign it to all the objects inside stavke_niz, which is an array of order listings which gets created elsewhere in the code, and require OrderID before being added to database (I can add that code as well if necessary). Then the array with the updated OrderIDs gets sent to this controller:

 [HttpPost]
        public string SnimiStavke(IEnumerable<StavkaNarudzbe> stavke_niz)
        {          
            if (stavke_niz != null)
            {
                ctx.StavkeNarudzbi.AddRange(stavke_niz);
                ctx.SaveChanges();
                return "true";
            }
            return "false";
        }

Which successfully accepts the JSON posted with AJAX and adds the stuff to the database. Now, when I try to post in Native, like so:

var xhr = new XMLHttpRequest();
xhr.onload = function () {
    if (xhr.status === 200 && this.readyState === 4)
    {
        alert(this.getAllResponseHeaders());
    }
};
xhr.open('POST', '/klijentarea/klijent/SnimiNarudzbu', true);
xhr.send(Narudzba);

All of the values inside "Narudzba" are null, despite the object clearly having all the right values before being posted to controller. Help would be greatly appreciated.

WhatAmIDoing
  • 109
  • 1
  • 11
  • You need to do the stuff `$.ajax` does automatically, namely `JSON.stringify()` your Object first, and setting the headers accordingly. See [this answer](https://stackoverflow.com/a/42493030/5734311). –  Sep 07 '18 at 22:04
  • How would I go about inserting the whole new post inside the then() part of the fetch request? I need the int variable that the server sends back to me to edit the stavke_niz array before posting it to the different controller method – WhatAmIDoing Sep 07 '18 at 22:14
  • `.then()` expects a function as parameter; the answer uses a shorter version where the function body is replaced with the return value; the standard syntax is `.then((param, ...) => { ... /* function body here */ })` –  Sep 07 '18 at 23:24

1 Answers1

0

You are missing Content-Type setting in your xhr request.

xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

This should solve your problem.

Hope this helps!

dj079
  • 1,389
  • 8
  • 14