I'm trying to use the connect middleware framework grunt comes preconfigured with to develop the front-end of my application, with static JSON files standing in for actual web services which I'll develop later.
However, sending a POST request to my static file results in a 404 error, even though a GET request with the same URL and parameters works just fine.
Can I configure grunt/connect to simply serve up my static file when a POST request is made to that URL?
I did a trick in my source code to call GET method if the app uses Grunt Server:
var useGruntServer = window.location.href.indexOf("localhost:9000") >= 0;
self.jsonGet = function (url, dataIn, callback, errorCallBack) {
$.ajax({
data: dataIn,
type: "GET",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (callback) callback(result);
},
error: function () {
if (errorCallBack) errorCallBack();
}
});
};
self.jsonPost = function (url, dataIn, callback, errorCallBack) {
//Grunt Server Accepts only GET requests
if (useGruntServer) {
self.jsonGet(url, null, callback, errorCallBack);
return;
}
$.ajax({
data: self.objectToJsonString(dataIn),
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (callback) callback(result);
},
error: function () {
if (errorCallBack) errorCallBack();
}
});
};
Related
Hello I am having issues downloading a file from an ASP.NET Core Razor page using an AJAX Post. What I want to do seems repetitively simple but has proved to be a real pain.
I do not want to store the file on the server but I am alright with TempData and a guid if needed.
I want to do a ajax post because I am sending data from the client to build the file.
Data sent to server will be encrypted into a string and that will be the contents of the file. (Note: Encryption is already working)
I want the file to download as my own extension *.dat.
Here is my asp.net core razor post method.
public IActionResult OnPostDownloadEncryptedFile([FromBody] List<FileData> fileData)
{
var response = ...THIS IS A REST WEB API CALL ASYNC I am calling .Result
var byteArray = Encoding.ASCII.GetBytes(response.EncryptedData);
var stream = new MemoryStream(byteArray);
return this.File(stream, System.Net.Mime.MediaTypeNames.Application.Octet, "myfile.dat");
}
Here is my Ajax post code:
$.ajax({
type: "POST",
url: "/MySite/MyPage?handler=DownloadEncryptedFile",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify(myData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
},
error: function (response) {
alert(response);
}
});
I realize that the ajax post is most likely incomplete and wrong not quite sure how to fix I have seen others using window.location but I am not sure how that works. Since when debugging I never have been able to get into the ajax post success function.
Any help would be greatly appreciated.
I got it working but I feel like its a terrible implementation.
Here is what I did:
public IActionResult OnPostEncryptFileData([FromBody] List<FileDataItem> fileData)
{
var response = this.restEndpoint.EncryptFileData(
new FileDataEncryptionRequest()
{
FileDataListItems = new FileDataList() { FileDataItems = fileData.ToList() }
}).Result;
return new JsonResult(response.EncryptedData);
}
public FileResult OnGetDownloadEncryptedFile(string data)
{
var byteArray = Encoding.ASCII.GetBytes(data);
return this.File(byteArray, "text/plain", "test.dat");
}
The Ajax post:
$.ajax({
type: "POST",
url: "/MySite/MyPage?handler=EncryptFileData",
beforeSend: function (xhr) { xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val()); },
data: JSON.stringify(fileData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
window.location = "/MySite/MyPage?handler=DownloadEncryptedFile&data=" + response;
},
failure: function (response) {
alert(response);
}
});
Would love to hear some better solutions.
All,
I am new to MVC. I have built an application where a button click performs
get market data (lengthy operation).
data message and upload to database.
This is what the JavaScript function looks like:
function OnClick(s, e) {
if (true) {
$.ajax({
type: "POST",
url: "#Url.Action("DataFileUpload", "ImportData")",
data: JSON.stringify({ positionDate: positionDate }),
dataType: "text",
contentType: "application/json; charset=utf-8",
beforeSend: function () { lpImport.Show(); },
success: function (msg) {
ImportDataGridView.PerformCallback();
ImportSuccessMessage.SetVisible(true);
ImportSuccessMessage.SetText(msg);
lpImport.Hide();
},
error: function (xhr) {
alert(xhr)
ImportDataGridView.PerformCallback();
}
});
}
}
What is happening right now is - When users close the browser in the middle of the run, controller action is still running. I can see that in my log.
How do I make browser close to stop running my controller action DataFileUpload ?
Thanks for helping out.
you can use the abort function from the XMLHttpRequest that $.ajax() returns.
abort(). If the request has been sent already, this method will abort the request.
Something like:
var xhr;
function OnClick(s, e) {
if (true) {
xhr = $.ajax({
type: "POST",
url: "#Url.Action("DataFileUpload", "ImportData")",
data: JSON.stringify({ positionDate: positionDate }),
dataType: "text",
contentType: "application/json; charset=utf-8",
beforeSend: function () { lpImport.Show(); },
success: function (msg) {
ImportDataGridView.PerformCallback();
ImportSuccessMessage.SetVisible(true);
ImportSuccessMessage.SetText(msg);
lpImport.Hide();
},
error: function (xhr) {
alert(xhr)
ImportDataGridView.PerformCallback();
}
});
}
}
function closeBrowser() {
xhr.abort();
}
but this will only cancel the event on the client. You should also cancel the request on the serverside.
In C# .NET it seems not to be possible to run 2 ajax request simultaneous. This is my Javascript code:
function startAjaxRequest1() {
setTimeout(startAjaxRequest2, 2000);
$.ajax({
type: "POST",
url: "/test.ashx/status",
contentType: "text/html; charset=utf-8",
dataType: "html",
async: true,
success: function (response) {},
failure: function (response) {}
});
}
function startAjaxRequest2() {
$.ajax({
type: "POST",
url: "/test2.ashx/statusupdate",
contentType: "text/html; charset=utf-8",
dataType: "html",
success: function (response) {},
failure: function (response) {}
});
}
When Ajax request 1 is executing, request 2 (started after 2 seconds), will never start. When I remove request 1, request 2 is executed is performing well.
Is it not possible to start a second ajax request when another is buzzy?
UPDATE:
In fact, this is my first ajax request (send files to server). Maybe it has something to do with this. The second ajax request keeps requesting each 4 seconds untill $.ajax(options) hass succeeded and the inner Ajax request is started. From that time, second request stops requesting. If I remove the inner Ajax request, there is no problem.
var options = {};
options.url = "/uploadGeoJsonFiles.ashx";
options.type = "POST";
options.data = data;
options.contentType = false;
options.processData = false;
options.success = function (result) {
$.ajax({
type: "POST",
url: "/dashboard.aspx/importGeoJsonData",
data: jsonString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
failure: function (response) {
}
});
};
options.error = function (err) {
showError(err.statusText);
};
$.ajax(options);
I am calling a webservice using ajax call(javascript) to return json.It is working fine.But when i changed my site to HTTPS it is not working.What will be the reason?
function GetReportguid1, callback) {
$.ajax({
type: "POST",
url: "/demo/Datapage.aspx/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
guiddemo: guid1
}),
success: function (results) {
callback(results);
},
error: AjaxFailed
});
};
Add the Access-Control-Allow-Origin header from the server
Access-Control-Allow-Origin: https://www.yoursite.com
http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing
And try use JSONP instead.
While calling MVC webservice from my html page it was always going to error; please help me
$.ajax({
type: "GET",
url: url,
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (msg) {
alert(Response.ErrorMessage )
},
error: function (e, status) {
alert(e + " Fail " + status)
}
});
You have to setup CORS (http://www.html5rocks.com/en/tutorials/cors/) or use JSONP. If you decide to use JSONP then you have to send proper callback function name with JSON data.