this is my function, where i post json only
function test() {
var imgFile = document.getElementById('image');
// var imgData = JSON.stringify(getBase64Image(imgElem));
//var imgData = Convert.FormBase64String(imgElem);
$.ajax({
type: 'POST',
dataType: 'json',
url: "http://localhost:59102/Contacts/AddContact",
data: "json=" + "{\"token\":\"8mVm/nS1OfpU+nlQLbJjqXJ7kJI=VyLGI2GEKkGgtDt0babrAw==\"}",
success: function (returnPayload) {
console && console.log("request succeeded");
},
error: function (xhr, ajaxOptions, thrownError) {
console && console.log("request failed");
},
processData: false,
async: false
});
and i dont know how to add to my data, image, i need to post json and image
this is my controller
[HttpPost]
[AllowAnonymous]
public JsonResult AddContact(string json, HttpPostedFileBase file)
{}
You can't upload files via AJAX (by design) unless you use a plugin that utilises other 'technology' such as flash, or iframes - this is a security measure as JavaScript reading local files on your machine would not be the best idea
There's an option here: http://jquery.malsup.com/form/
...otherwise I suggest looking up one of the many other alternatives!
after you getting the data to a base 64 , your json should be an object
from your controller your json should be something like this
{"json":"something here that is a string","file":"some file"}
Also on the client side you should have a n object on which you invoke JSON.stringify()
var ob = {json:imageDataAsBase64,file:fileDataAsBinary}
although I dont see the reason to send both.
if what you need is just transafering an image that you just need to get the image as base64 and post it as a json
Related
In MVC, why does returning Content sometimes fail in the Ajax callback, while returning Json works, even for simple string objects?
Even when it fails, the data is still available if you were to access it in the always callback...
Update:
When I set the contentType in the ajax call to text/xml the response will no longer enter the error message.
AJAX:
$.ajax({
cache: false,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: 'json',
url: "/MyController/GetFooString",
data: { },
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Ajax Failed!!!");
}
}); // end ajax call
Controller Action That Fails (Sometimes)
Even when it fails, the data is still available.
public ActionResult GetFooString()
{
String Foo = "This is my foo string.";
return Content(Foo);
} // end GetFooString
Controller Action That Always Works
public ActionResult GetFooString()
{
String Foo = "This is my foo string.";
return Json(Foo, JsonRequestBehavior.AllowGet);
} // end GetFooString
Using Content(Foo); sends a response that doesn't have the mime type header. This happens because you're not setting ContentType when using this overload. When the Content-Type is not set, jQuery will try to guess the content type. When that happens, whether it can successfully guess or not depends on the actual content and underlying browser. See here:
dataType (default: Intelligent Guess (xml, json, script, or html))
Json(...) on the other hand explicitly sets the content type to "application/json" so jQuery knows exactly what to treat the content as.
You can get consistent result from Content if you use the 2nd overload and specify a ContentType:
return Content(Foo, "application/json"); // or "application/xml" if you're sending XML
But if you're always dealing with JSON, then prefer using JsonResult
return Json(Foo, JsonRequestBehavior.AllowGet);
I am passing json data to my generic handler page GenericHandler.ashx.cs using jquery ajax request and json as data type.
in my handler code i would like to return html table in string format. here is snap of my handler code
context.Response.ContentType = "text/plain";
context.Response.Write(sResponse);
where sResponse contains <table><tr><td>PropertyName</td><td>PropertyID</td></tr><tr><td>abc</td><td>1</td></tr></table>
my jquery code (check inline comment in error function):
id = { 'PropertyID': id };
$.ajax("Handlers/GenericHandler.ashx?Type=getProperties",
{
type: 'post',
dataType: 'json',
cache: false,
contentType: "application/json",
data: JSON.stringify(id),
success: function (data) {
console.log(data);
},
error: function (xhr, status) {
console.log(status); // Output as parseError
console.log(xhr.responseText); // My sResponse string ! But Why Here ?
}
});
My Question :
Why i am not getting response in success function
Is it right way to do ? or should i convert html table to json object and then return it. And again display it in tabular format ?
From jQuery documentation here, you can see that the dataType parameter is what AJAX is expecting back as a response from the server. The contentType parameter is what is put in the header in your request to the server so that the server knows how to read the request.
Therefore, you should change your dataType to "text" like:
$.ajax("Handlers/GenericHandler.ashx?Type=getProperties",
{
type: 'post',
cache: false,
dataType: 'text',
contentType: "application/json",
data: JSON.stringify(id),
success: function (data) {
console.log(data);
},
error: function (xhr, status) {
console.log(status);
console.log(xhr.responseText);
}
});
I find this useful when alerting of a successful INSERT or UPDATE call on a database. It would be extraneous to create and return a JSON object for such a task.
Your response isn't valid JSON sine it's returning plain text. jQuery is expecting the response to be JSON because you've set contentType: "application/json"
If the rest of your site uses JSON as a transmission format, then wrap your HTML as a JSON object and return it.
In your back end code, return something that looks like this
{response_html : "<table><tr><td>PropertyName</td><td>PropertyID</td></tr><tr><td>abc</td><td>1</td></tr></table>"}
And in your jQUery code, you can access it in the success callback.
success: function (data) {
console.log(data.response_html);
},
NOTE - You'll need to remove the plain text content type from your backend code and make that JSON.
If you tell $.ajax that you expect a JSON, then a text/plain response from the server is not a valid response.
Regarding your second question: The good way to do it would be to return the data you want to work with, in JSON format, for example:
[
{ "label" : "PropertyName", "value" : "abc" },
{ "label" : "PropertyId", "value" : "1" }
]
And then in the success callback of your Ajax request, work with that data to build your HTML structure with jQuery.
I'm trying to senda csv file opened with JS to the method written in C# where csv file will be parsed and added to database.
I have no problem with opening file and getting its contents.
But whatever I do with my Ajax call I receive empty data in the method CreateFromFile.
here you can see my code:
var a = fr.result;
$.ajax({
url: "/DeviceInstance/CreateFromFile",
type: "POST",
datatype: "html",
data: a,
error: function (data) {
alert("Dodanie nie powiodło się Jeden lub wiecej numerów seryjnych nie są nikalne " + data);
},
success: function (data) {
if (data.length > 0) {
alert(data);
}
else {
alert("Operacja zakonczona sukcesem")
}
}
});
and:
[HttpPost]
public JsonResult CreateFromFile(object data)
{
return Json("Sukces");
}
I'm asking how should i modify my code to make things work?
here : fr.result:
samsung;galaxy ;s3;1234567
samsung;galaxy ;s4;54321
samsung;galaxy ;s5;34567yu8
You could read the request input stream to access the body payload:
[HttpPost]
public JsonResult CreateFromFile()
{
byte[] data = new byte[Request.InputStream.Length];
Request.InputStream.Read(data, 0, data.Length);
string csv = Encoding.UTF8.GetString(data);
// ... do something with the csv
return Json("Sukces");
}
Also in your AJAX request you seem to have specified datatype: "html". There are 2 problems with this:
The parameter is called dataType instead of datatype.
You specified html but your controller action returns JSON.
So that's very inconsistent thing. I would recommend you to get rid of this parameter and leave jQuery use the response Content-Type header to automatically infer the correct type.
Try the following (assuming your a payload is really a string):
$.ajax({
url: '/DeviceInstance/CreateFromFile',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({ dane: a }),
/* callbacks */
});
And your controller action should now look like the following:
[HttpPost]
public JsonResult CreateFromFile(string dane)
{
// Parse CSV data from "dane"
}
Hope this helps.
I am calling a method using JQuery ajax given below
$.post('../User/GetCountry',
{
zone: 1
},
function (data) {
alert(data);
alert(data["Countries"]);
}, "json").fail(function (jqXHR, textStatus, errorThrown) {
//alert(textStatus);
});
C# code
public static string GetCountry()
{
var result = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Countries.GetAll());
return result;
}
Now when I debug my code on server side i see the below result which is perfect json according to me
[{"Id":4,"Name":"France"},{"Id":3,"Name":"Germany"}]
But in javascript I am getting the json as
[[object Object],[object Object]]
Can anyone please let me know what I am missing here
SOLVED USING
var jsonData = JSON.stringify(data);
var jsonParse = JSON.parse(jsonData);
There's a few issues with your code. First, despite the fact that you're passing a parameter zone to the web service method the method itself doesn't receive this parameter. Second, if you want to return JSON don't use the return type string. Use JSONResult. This will allow you to remove the static keyword as well. I'd recommend changing your method like so:
public JSONResult GetCountry(int? zone)
{
// ...
}
There are two final changes you should make. The first is to use ASP.Net MVC's built in Json() method to handle serialization of your object. The second is that you should always project your data layer results even if they happen to already be in the structure you want to use. This way if you change your data layer object in a way that breaks the service you'll get a compile error instead of a run time exception.
return Json(from c in Countries.GetAll() select new { Id = c.Id, Name = c.Name })
I'd also recommend avoiding using $.get or $.post as they abstract away settings that can be useful when access web services. If you want to shorthand it I'd recommend wrapping the $.ajax call in your own function. You're also going to want to think about standardizing your web service responses. Your web service is a protocol of sorts and as such it benefits from having a well defined header. For a more in-depth explanation take a look here: Introduction to MVC Service Based Web Applications
try this :
alert(data[0].Name)
$.ajax({
type: 'POST',
url: '../User/GetCountry',
data: {
zone: 1
},
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
works good for me. You need to make sure you're sending a content-type of "application/json", preferably using the Json() helper method in Controller.
Solved this after searching bit more
$.post('../User/GetCountry',
{
zone: 1
},
function (data) {
var jsonData = JSON.stringify(data);
var jsonParse = JSON.parse(jsonData);
}, "json").fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
});
Try using JSON.parse():
$.post('../User/GetCountry',
{
zone: 1
},
function (data) {
data=JSON.parse(data)
alert(data["Countries"][0].Name);
}, "json").fail(function (jqXHR, textStatus, errorThrown) {
//alert(textStatus);
});
I need to submit a simple form and validate the model. If the model is valid, I would like to serialize that model and send it via POST to an external (https) web service using custom headers. Finally I would handle the response that I get back from the request and display the appropriate message.
I am validating the model from the controller perfectly and serialize the object but can't seem to find a way to create a JSON post request to the external URI. Is there a way to do this using JQuery.ajax or $.post. Maybe I am missing a key ajax param to achieve this.
Thanks
So based on the clarification on the question this is what you can do:
Define the controller method that will validate the object
public ActionResult TestMethod() {
// do server-side validation
return Json(aValidObject);
}
You do an ajax post to your controller so you can validate your model then get back a json result.
$.ajax({
url: '#Url.Action("TestMethod")',
data: some_data,
type: "post",
success: function (result) {
// result is a valid json object
doExternalPost(result);
}
});
Add custom header and do the external post
function doExternalPost(o) {
$.ajax({
url: 'http://some_external_url',
data: o,
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader('custom_header', 'some_value');
},
success: function() {
// post is sucessful
},
error: function (xhr, errorType, exception) {
var errorMessage = exception || xhr.statusText || xhr.responseText;
alert('An error has occured: ' + errorMessage);
},
});
}
try this
var data = {jsonDataObjectHere};
var request = $.ajax({
url : 'externalUrl.com/something.whatever',
type : 'POST',
data : data // see above
});
request.success(function(response){
// the response is the stuff from the server
});
i'm sleepy so forgive typos
good luck
EDIT: for a bit of clarification, with MVC you really dont need to serialize the json object, mvc will accept it as it is.