Click here to Skip to main content
15,886,780 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I'm looking to code this in pure JavaScript please? This works for JQUERY1-2. Note: Not looking for MVC Core 1+
var sMVCParameter1 = "1";
var sMVCParameter2 = "2";
var sToken = document.getElementsByName("__RequestVerificationToken")[0].value;    
$.ajax({
                url: "/Home/ClickCreateAccount/",
                type: "POST",
                contentType: "application/x-www-form-urlencoded",                                                    
                data: { '__RequestVerificationToken': sToken, 'sMVCParameter1': sMVCParameter1, 'sMVCParameter2': sMVCParameter2 }
            })
.done(function (data) {
//Process MVC Data here
})
.fail(function (jqXHR, textStatus, errorThrown) {
//Process Failure here
});


What I have tried:

==========================================================
The JavaScript Might Look like this
==========================================================
<script type="text/javascript">
        function Test_JS_Ajax() {

            var sToken = document.getElementsByName("__RequestVerificationToken")[0].value;

            var xmlHttp;
            //Let us create the XML http object
            xmlHttp = null;

            if (window.XMLHttpRequest) {
                //for new browsers
                xmlHttp = new XMLHttpRequest();
            }
            else if (window.ActiveXObject) {
                var strName = "Msxml2.XMLHTTP"
                if (navigator.appVersion.indexOf("MSIE 5.5") >= 0) {
                    strName = "Microsoft.XMLHTTP"
                }
                try {
                    xmlHttp = new ActiveXObject(strName);
                }
                catch (e) {
                    alert("Error. Scripting for ActiveX might be disabled")
                    return false;
                }
            }

            if (xmlHttp != null) {
                //Handle the response of this async request we just made(subscribe to callback)
                xmlHttp.onreadystatechange = function () {
                    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                        var data = JSON.parse(xmlHttp.responseText);
                        alert(data);
                    }
                }
                xmlHttp.onerror = function () {
                    //Not Connected                
                }
                //Pass the value to a web page on server as query string using XMLHttpObject.
                
                
                //VERSION 1 TESTED FAILED
                //xmlHttp.open("GET", "/Home/Test/?sString1=" + "1", true);
                //xmlHttp.setRequestHeader("__RequestVerificationToken", sToken);
                //xmlHttp.send();

                //VERSION 2 TESTED FAILED
                //xmlHttp.open("GET", "/Home/Test/", true);
                //xmlHttp.setRequestHeader("Content-type", "application/json");
                //xmlHttp.setRequestHeader("__RequestVerificationToken", sToken);
                //xmlHttp.send(JSON.stringify({ "sString1": "1" }));

                //VERSION 3 TESTED FAILED
                //xmlHttp.open("GET", "/Home/Test/", true);
                //xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                //xmlHttp.setRequestHeader("__RequestVerificationToken", sToken);
                //xmlHttp.send(JSON.stringify({ "sString1": "1" }));
                
                //VERSION 4 TESTED FAILED
                xmlHttp.open("GET", "/Home/Test/", true);
                xmlHttp.setRequestHeader("__RequestVerificationToken", sToken);
                xmlHttp.send(JSON.stringify({ "sString1": "1" }));
            }
            else {
                //Browser not supported! Please update your browser!            
            }
        }
    
</script>

C# Code looks like
[ValidateAntiForgeryToken]
public JsonResult Test(string sString1)
{
   return Json("T", JsonRequestBehavior.AllowGet);
}

Html
<body onload="Test_JS_Ajax()">
Posted
Updated 16-Oct-18 5:45am
v3

JavaScript
var sMVCParameter1 = "1";
var sMVCParameter2 = "2";
var sToken = document.getElementsByName("__RequestVerificationToken")[0].value;

var body = new URLSearchParams();
body.append("__RequestVerificationToken", sToken);
body.append("sMVCParameter1", sMVCParameter1);
body.append("sMVCParameter2", sMVCParameter2);

fetch("/Home/ClickCreateAccount/", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: body
})
.then(function(response) { 
    if (response.ok) {
        return response.json(); 
    }
    
    throw new Error('Network response was not ok.');
})
.then(function(data){
    // Process MVC data here
})
.catch(function(error){
    // Process failure here
});

Using Fetch - Web APIs | MDN[^]

If you need to support Internet Explorer, you'll need two polyfills:
GitHub - github/fetch: A window.fetch JavaScript polyfill.[^]
GitHub - WebReflection/url-search-params: Simple polyfill for URLSearchParams standard[^]
 
Share this answer
 
I found a way that works in all browsers and tested below. If you have any code updates to below let me know thank you.

var xmlHttp = null;
if (window.XMLHttpRequest) {
    xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
    var versions = [
        "MSXML2.XmlHttp.6.0",
        "MSXML2.XmlHttp.5.0",
        "MSXML2.XmlHttp.4.0",
        "MSXML2.XmlHttp.3.0",
        "MSXML2.XmlHttp.2.0",
        "Microsoft.XmlHttp"];
    var xhr;
    for (var i = 0; i < versions.length; i++) {
        try {
            xmlHttp = new ActiveXObject(versions[i]);
            break;
        } catch (e) {
        }
    }
}
if (xmlHttp != null) {
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            document.getElementById("divLOAD").style.display = "none";
            var data = JSON.parse(xmlHttp.responseText);
            if (data == "" && sIsAutoComplete == "F") {
                PlateResult("", "", "", "", "RED", sSearch);
                return;
            }
            else if (data == "") {
                return;
            }
            if (sIsAutoComplete == "T") {
                return AutoComplete(data);
            }
            else if (sIsAutoComplete == "F") {
                SearchPlateShow(data, "F");
            }
            else if (sIsAutoComplete == "A") {
                s_CacheSelectedCompanyID = s_SelectedCompanyID;
                AllData = data;
                var dt = new Date();
                CacheDate.setTime(dt.getTime() + (CacheMinutes * 60 * 1000)); //1 minute //days (exdays * 24 * 60 * 60 * 1000) || minute (exdays * 60 * 1000)
            }
        }
    }
    xmlHttp.onerror = function () {
        document.getElementById("divLOAD").style.display = "none";
        if (sIsAutoComplete == "T") {
            return AutoComplete(AllData);
        }
        else if (sIsAutoComplete == "F") {
            SearchPlateShow(AllData, "T");
        }
    }
    xmlHttp.open("POST", "/Home/SearchPlate/", true);
    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlHttp.send('__RequestVerificationToken=' + sToken + '&sLicensePlate=' + Encode(sLicensePlate) + '&sIsAutoComplete=' + sIsAutoComplete + '&sID=' + s_SelectedCompanyID + '&sKey=' + sKey + '&sIV=' + sIV);
}
else {
    //Browser not supported! Please update your browser!
    document.getElementById("spParkingTracker").innerHTML = "Browser not supported!";
}
 
Share this answer
 
v2
Note I decided to use JQUERY $.ajax which prevented the random error "500 (internal server error)", which means something went wrong on the server's side.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900