I want to send data though Ajax to a C# file, but when I check the received data, It gives me null. Is there someting wrong with my code?
Javascript file
$(".save").click(function () {
var ss = "Helloo!";
$.ajax({
type: "POST",
url: "/Notes/save.cshtml",
global: true,
data: {fofo: ss},
processData: false,
contentType: false,
cache: false,
success: function(data){
console.log(data);
},
error: function (req, status, error) {
alert("There was a problem with the server. Try refreshing the page.");
return false;
}
});
});
C# File which receives the data (save.cshtml)
#{
var s = Request.Form["fofo"];
var result = "";
var userData = s;
var dataFile = Server.MapPath("~/Notes/lolo.txt");
File.WriteAllText(#dataFile, s);
result = "Information saved.";
}
#if(result != ""){
<p>Result: #result, #s</p>
}
You are not sending a response back to your AJAX function. Not only that what you're doing isn't standard MVC. You should be hitting a Controller which saves the data in the file at the server side and then send the result back using a JsonResult.
For example:
public JsonResult SaveNotes()
{
// Code to save file here
// Return the response
return Json({NotesSaved = true});
}
Then in your JavaScript AJAX success object you will then have the NotesSaved object set to true.
Note: You should also change your URL parameter in the AJAX command to something like:
url: '#Url.Action("SaveNotes")'
Related
I'm executing an ajax call to a external api (this cannot be modified) to upload an store a file into a folder. This request must return a path (ex. "C:\Doctos\File.pdf" but after a console.log is returning something like this:
#document < string xmlns="http://tempuri.org/">"C:\Doctos\File.pdf"
So my question is, what can I do to get only the text that I want without any change in the api (because I'm not able to do it).
Here is the ajax call that I'm using.
PD. This ajax call is using the provided structure for the dev team that developed the api so things like dataType also cannot be modified
var data = new FormData();
var files = $('#fileUpload').get(0).files;
if (files.length > 0) {
data.append("UploadedFile", files[0]);
}
$.ajax({
type: 'POST',
url: 'api/v1/moreurl/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (data) {
var res = data;
//Returns above example
console.log(res);
//Returns something like <p>[object XMLDocument]</p>
$('#MyInput').attr('src', res);
}
});
I would use regular expressions to get the desired string from received data. Put this after success line.
var regex = />\"(.*)\"/;
var matched = regex.exec(data);
var result = matched[1];
console.log(result);
The regex matches the last quoted string in your example.
You can get the data in the xml with jQuery
$.ajax({
type: 'POST',
url: 'api/v1/moreurl/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (data) {
// Get the contents of the xml
var file = $(data).find('string').text();
$('#MyInput').attr('src', file);
}
});
I have a method in MVC that I post to it and I need to return some data back to process.
This is my MVC method that I post to and return Value is a json data.
[HttpPost]
public JsonResult GetCalculateAmortizationSchedule()
{
var data = ...
var httpClient = new HttpClient();
var response = httpClient.PostAsJsonAsync("http://localhost:62815/v1/APR/CalculateAmortizationSchedule", data).Result;
var returnValue = response.Content.ReadAsAsync<Dictionary<int, AmItem>>().Result;
return Json(returnValue);
}
This is my AJax call that successfully run the MVC method.
$('#MyForm').submit(function (e) {
debugger;
$.ajax({
url: "/home/GetCalculateAmortizationSchedule",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert("success");
},
error: function (result) {
alert("error");
}
});
e.preventDefault();
});
My problem is how to catch the return value from method? when I run this after return Json(returnValue) the value is not returning to Ajax method and instead of seeing the Success Alert I see the error Alert.
Try this:
success: function (result) {alert(JSON.stringify(result)); }
From the error you have posted in comments below, it appears Dictionary is not serializable. Try setting AllowGet as mentioned in other answers. If doesn't work, you will need to convert Dictionary to some other object that is serializable. Or you may follow this to serialize Dictionary to json in your controller.
How do I convert a dictionary to a JSON String in C#?
You should add JsonBehavious if you are not getting values.
return Json(returnValue, JsonRequestBehavior.AllowGet);
Try this piece of code :
return Json(returnValues, JsonRequestBehavior.AllowGet);
I have a method in my controller that submits some changes in the database after receiving a filename that being uploaded to the server. Also this method is getting the fileNameOrigin and fileNameUnique (to be downloaded for saving in the server folder)
public JsonResult Upload()
{
var upload = Request.Files[file];
string fileNameOrigin = System.IO.Path.GetFileName(upload.FileName);
string fileNameUnique = String.Format("{0}_" + fileNameOrigin,
DateTime.Now.ToString("yyyyMMddHHmmss"));
//there is more code that isn't needed in my case
return Json(fileNameOrigin, fileNameUnique);
}
So, here's the question - how to send and receive this data on the client side?
$('#uploadFile').on('change', function (e) {
e.preventDefault();
var files = document.getElementById('uploadFile').files;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
}
$.ajax({
type: "POST",
url: '#Url.Action("Upload", "ChatRooms")',
contentType: false,
processData: false,
data: data,
success: onSuccess, //here I need to receive data and do smth with it
error: onError
});
}
}
});
Create a anonymous object with the properties that are required and then pass that single object to the JSON method like:
var data = new {
FileNameOrigin = fileNameOrigin,
FileNameUnique = fileNameUnique
};
return Json(data);
In success callback of ajax, you can access it, for just to check it is working log it on console to see what server has returned like:
success: function(data) {
console.log(data);
},
you might also need to specify datatype in ajax call to json which dictates that JSON is expected from server to be returned in response to this ajax call:
dataType: "json"
Hope it helps!
I am more of a java developer and am having difficulty with javascript callback. I am wondering if any experts here would help me out of my struggle with this code.
I am trying to pull our locations from db and populating in an array. On first load i am trying to refresh all locations and I am having trouble to control the flow of execution and loading values. Below is the code and I have put in the output at the end.
JQUERY CODE:
// load all locations on first load.
refreshLocations();
$("#locInput").autocomplete({source: locationData});
}); // end of document.ready
// function to refresh all locations.
function refreshLocations() {
getLocationArray(function(){
console.log("firing after getting location array");
});
}
// function to get the required array of locations.
function getLocationArray() {
getJsonValues("GET", "getLocalityData.php", "", getLocalityFromJson);
}
// function to pick up localities from json.
function getLocalityFromJson(json){
if (!json) {
console.log("====> JSON IS NOT DEFINED !! <====");
return;
} else {
console.log("json is defined so processing...");
var i = 0;
$.each(json.listinginfo, function() {
var loc = json.listinginfo[i].locality;
locationArray[i] = loc;
console.log("added location ->" + locationArray[i]);
i++;
});
}
//return locationArray;
}
// function to get raw json from db.
function getJsonValues(type, url, query, getLocalityFromJson) {
var json;
// if the previous request is still pending abort.
if (req !== null)
req.abort();
var searchString = "";
if (query !== "") {
searchString = "searchStr" + query;
}
console.log("searchString : (" + query + ")");
req = $.ajax({
type: type,
url: url,
data: searchString,
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function(result) {
json = JSON.parse(result);
console.log("========start of json
return============");
console.log(JSON.stringify(json));
console.log("========end of json
return============");
//return json;
}
});
getLocalityFromJson(json);
return json;
}
the output from above code is as follows:
searchString : () (18:25:36:473)
at locality1.php:74
====> JSON IS NOT DEFINED !! <==== (18:25:36:518)
at locality1.php:48
========start of json return============ (18:25:37:606)
at locality1.php:83
{"listinginfo":[{"listing":"1","locality":"birmingham"},
{"listing":"2","locality":"oxford"}]} (18:25:37:624)
at locality1.php:84
========end of json return============ (18:25:37:642)
at locality1.php:85
>
Help will be greatly appreciated.
call getLocalityFromJson(json); inside your success callback
function getJsonValues(type, url, query, getLocalityFromJson) {
var json;
// if the previous request is still pending abort.
if (req !== null)
req.abort();
var searchString = "";
if (query !== "") {
searchString = "searchStr" + query;
}
console.log("searchString : (" + query + ")");
req = $.ajax({
type: type,
url: url,
data: searchString,
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function(result) {
json = JSON.parse(result);
console.log("========start of json return============");
console.log(JSON.stringify(json));
console.log("========end of json return============");
//return json;
getLocalityFromJson(json);
}
});
}
You need to call getLocalityFromJson(json) and return json inside your ajax success function. Ajax requests are asynchronous, there's no guarantee that the request will be finished by the time you get to the lines getLocalityFromJson(json); return(json); where they are currently.
The call back functions from a jquery ajax call is complete, failure, success, etc..
Success is called after a request is successful,
Failure is called if theres something like an error 500, or a 404, or w/e.
Complete is Always called after a ajax call.
If you want your code to just follow sequence like in java, throw async: false into your ajax call.. but I wouldnt' recommend this as it defeats the purpose of using this method, and also locks up your browser.
You should make sure you are waiting for the request to finish before moving on - so put code in the success function that you want to run AFTER the request has finished fetching your data.
I think you need to remember Ajax is running async, so you need to follow this thread to execute your refresh.
Inside my MVC view I have javascript that is executed by a button click. I'm trying to set a string to a random set of characters which I can get to work fine but when I try and set that string to 'randomchars' string inside the javascript I get a NullReferenceException when I try and run the view.
Below is the code snippet, the CreateRString is where the model parameter (RString) is set to the random string.
<script type="text/javascript">
function showAndroidToast(toast) {
var url = '#Url.Action("CreateRString", "Functions")';
$.ajax({ url: url, success: function (response) { window.location.href = response.Url; }, type: 'POST', dataType: 'json' });
var randomchars = '#(Model.RString)';
}
</script>
Is the syntax correct? I'm not too sure why it's getting the NULL.
The javascript is executed after the page been delivered to the client (i.e. web browser). Your razor code here is executed on the server before the page is sent to the client. Therefore, the ajax method will execute after you try to access Model.RString
To fix this you can either call CreateRString on the server, or you can set randomchars by using the response in the success callback.
To explain option 2 a bit further. You could do something like this:
//Action Method that returns data which includes your random chars
public JsonResult CreateRString()
{
var myRandomChars = "ABCDEF";
return new JsonResult() { Data = new { RandomChars = myRandomChars } };
}
//The ajax request will receive json created in the CreateRString method which
//contains the RandomChars
$.ajax({ url: url, success: function (response) {
var randomchars = response.Data.RandomChars;
window.location.href = response.Url;
}, type: 'POST', dataType: 'json' });
More specifically, the razor calls #Url.Action("CreateRString", "Functions") and #(Model.RString) execute first on the server.
Then showAndroidToast executes in the client's browser when you call it.