How to receive a data from the JSon method? - javascript

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!

Related

Get Object XmlDocument value

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);
}
});

How to post file with ajax?

Trying to save a file to a db. I am using formData via javascript to append the file and adding this as a post object via ajax. for some reason nothing gets sent.
What am I doing wrong?
HTML
<input type="file" style="display: none;" class="btn btn-primary uploadFile">
script:
$(".saveImage")
.on("click",
function() {
var files = $(".uploadFile");
var data = new FormData();
data = $.OverWatch.worker.uploadFileHandler.addUploadFiles(files, data);
$.OverWatch.worker.postUserData("/Administration/AddUserImage", data, function () {
alert("done");
});
});
Functions above look like:
addUploadFiles: function (files, data) {
$.each(files, function (i, v) {
var file = $(this).data("files");
data.append("file", file);
});
return data;
}
postUserData:
postUserData: function(url, data, callback) {
$.LoadingOverlay("show");
$.ajax({
url: url,
type: 'POST',
data: data,
cache: false,
processData: false,
contentType: false,
dataType: "HTML",
success: function(data) {
if (callback) {
callback(data);
$.LoadingOverlay("hide");
}
},
error: function(event, jqxhr, settings, thrownError) {
//$.helpers.errorHandler($("#fileDialogErrors"), event.responseText);
var h;
$.LoadingOverlay("hide");
}
});
},
backend:
public ActionResult AddUserImage()
{
if (Request.Files.Count != 0)
{
//save
}
return null;
}
edit:
var files = $(".uploadFile");
returns:
Your var file = $(this).data("files"); line of code would be returning undefined (unless you have some other javascript adding a data value, but you cannot add files to data so it in any case it would not be returning a file).
Change your loop to
$.each(files, function (i, v) {
for (i = 0; i < v.files.length; i++) {
var file = v.files[i];
data.append("file", file);
}
});
However, you can simplify this by using var data = new FormData($('form').get(0)); which will serialize all you form controls including file inputs to FormData (refer how to append whole set of model to formdata and obtain it in MVC for more information).
I also recommend you change your method signature to
public ActionResult AddUserImage(IEnumerable<HttpPostedFileBase> files)
and let the DefaultModelBinder do its magic.
you can directly get file from controller when called using Request.Files
//(Request) HttpRequestBase object for the current HTTP request
if (Request.Files.Count > 0)//// Is image is uplaod by browse button
{
var inputStream = Request.Files[0].InputStream;
using (var binaryReader = new BinaryReader(inputStream))
{
var ImageBytes = binaryReader .ReadBytes(Request.Files[0].ContentLength); // same as you can get multiple file also
}
var fileExtension = Path.GetExtension(Request.Files[0].FileName);
}
thanks.
I haven't done it with jQuery but just learned how to do it myself yesterday using plain old javascript... the following worked for me. If you want to stick with jquery maybe you can translate the functions to what you need:
var formElement = document.querySelector("form");
var payload = new FormData(formElement);
function onStateChange(ev) {
// Check if the request is finished
if (ev.target.readyState == 4) {
editor.busy(false);
if (ev.target.status == '200') {
// Save was successful, notify the user with a flash
} else {
// Save failed, notify the user with a flash
}
}
};
xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', onStateChange);
xhr.open('POST', '/posts');
xhr.send(payload);
Maybe see if using the above code works for you (it just targets a form that you have on the same page), and then you can troubleshoot whether it's your script that's the problem or a backend / communication problem.

C# - Get Ajax data

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")'

Returning an object from Web Service to Ajax Request success callback function

Hello Fellow Developers,
I have a SSN textbox that onblur calls a function which does an ajax request to a Web Method to decide if an employee has been previously hired.
The Web Method returns a TermedEmployee Object to the success callback, but I'm unsure how to parse the object.
$('#<%=FormView1.FindControl("SSNField").ClientID%>').blur(hideValue);
hideValue = function (ev) {
var $this = $(this);
$this.data('value', $this.val());
$('#<%=FormView1.FindControl("hiddenSSN").ClientID%>').val($this.val());
var data2Send = '{"SSN": ' + $this.val() + ' }';
$.ajax({
type: "POST",
url: "AuthforHire.aspx/EmployeeisRehire",
data: data2Send,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var obj = JSON.stringify(result.d);
if (obj.IsTermed) {
$('#%=RadWindowRehire.ContentContainer.FindControl("TextBoxTermID").ClientID%>').val(arg.d);
var wndWidth = 900;
var wndHeight = 500;
var wnd = window.radopen(null, "RadWindowRehire");
}
},
error: function (xhr) {
alert('Form update failed. '); //error occurred
}
});
Below is a minified version of my webMethod, which works correctly
[System.Web.Services.WebMethod]
public static TermedEmployee EmployeeisRehire(string SSN)
{
TermedEmployee termedEmp = new TermedEmployee();
// Db call to get necessary data.
termedEmp.Name = dr["name"];
termedEmp.TermDate = Convert.ToDateTime(dr["TermDate"].ToString());
......
}
So How Can I extract Name, TermDate,StartDate, ReasonforTerm, etc from the object returned to the callback function?
Thank you in advance!
The first line in your success callback is:
var obj = JSON.stringify(result.d);
Which is trying to serialize what ASP.Net will already have serialized for you.
Change this to:
var obj = result.d;
And you will then have access to obj.Name, obj.TermDate and all the other properties by name.

How to convert simple form submit to ajax call;

I have a form with input field which can be accessed like
var algorithm = document.forms["algoForm"]["algorithm"].value;
var input = document.forms["algoForm"]["input"].value;
and earlier call was
document.forms["algoForm"].submit();
and form was
<form name="algoForm" method="post" action="run.do">
It all run fine
Now I wanted convert it to the ajax call so that I can use the returned data from java code on the same page. So I used soemthing like
var algorithm = document.forms["algoForm"]["algorithm"].value;
var input = document.forms["algoForm"]["input"].value;
var data = 'algorithm = ' + algorithm + '&input = ' + input;
$.ajax(
{
url: "run.do",
type: "POST",
data: data,
success: onSuccess(tableData)
{ //line 75
alert(tableData);
}
}
);
However the above code doesn't run. Please help me make it run
Let's use jQuery's serialize to get the data out of the form and then use the jQuery's ajax function to send the data to the server:
var data = $("form[name=algoForm]").serialize();
$.ajax({
url: "run.do",
type: "POST",
data: data,
success: function(tableData){
alert(tableData);
}
});
data expects a literal object, so you need:
var data = {
'algorithm': algorithm,
'input': input
};
Instead of retrieving all the parameter value and then sending them separately (which can be done server side as well, using below code), Use this:
var $form = $("#divId").closest('form');
data = $form.serializeArray();
jqxhr = $.post("SERVLET_URL', data )
.success(function() {
if(jqxhr.responseText != ""){
//on response
}
});
}
divId is id of the div containing this form.
This code will send all the form parameters to your servlet. Now you can use request.getParameter in your servlet to get all the individual fields value on your servlet.
You can easily convert above jquery post to jquery ajax.
Hope this helps :)
// patching FORM - the style of data handling on server can remain untouched
$("#my-form").on("submit", function(evt) {
var data = {};
var $form = $(evt.target);
var arr = $form.serializeArray(); // an array of all form items
for (var i=0; i<arr.length; i++) { // transforming the array to object
data[arr[i].name] = arr[i].value;
}
data.return_type = "json"; // optional identifier - you can handle it on server and respond with JSON instead of HTML output
$.ajax({
url: $form.attr('action') || document.URL, // server script from form action attribute or document URL (if action is empty or not specified)
type: $form.attr('method') || 'get', // method by form method or GET if not specified
dataType: 'json', // we expect JSON in response
data: data // object with all form items
}).done(function(respond) {
console.log("data handled on server - response:", respond);
// your code (after saving)
}).fail(function(){
alert("Server connection failed!");
});
return false; // suppress default submit action
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I don't know how but this one runs well,
var algorithm = document.forms["algoForm"]["algorithm"].value;
var input = document.forms["algoForm"]["input"].value;
$.post('run.do', {
algorithm : algorithm,
input : input
}, function(data) {
alert(data);
}
);

Categories