Im having the following ajax cal in my JS file in Durundal ,
var dataJSON ={ID : "jo"};
self.js = $.ajax({
type: "POST",
dataType: text,
url: "http://localhost:53081/api/File",
data: JSON.stringify(dataJSON),
error: function (xhr, status, error) {
alert(error);
},
success: function (json) {
alert("Data Returned: " + JSON.stringify(json));
}
});
and my REST api is
[HttpPost]
public string upload(string ID)
{
string givenId = ID;
return givenId;
}
but when i call thsi methos im simply getting error alert . what went wrong
update
i have updated my code but now im getting Not found error
Change string to Text:
self.js = $.ajax({
type: "POST",
dataType: **Text**,
url: "url",
data: JSON.stringify(dataJSON),
error: function (xhr, status, error) {
alert(status);
},
success: function (json) {
alert("Data Returned: " + JSON.stringify(json));
}
});
click here for list of datatype and there representation.
You may need to change the name of the method to be PostFile. I had issues getting this to work without having the proper naming convention, even though I had the [HttpPost] attribute at the beginning of the method.
Also: try changing your dataType to "json" and adding the content type:
dataType: "json",
contentType: "application/json"
Related
I have a webapi method defined like the following in a controller:
[Authorize]
[HttpPost]
[Route("api/Resources/{resourceID:int}/VerifyUrl")] //Custom Routing
public object VerifyResourceURL([FromBody]string url, int resourceID)
When I call it with jquery ajax the variable url is always null, why?
(resourceID has the correct value)
$.ajax({
url: '/api/resources/15/VerifyUrl',
type: "POST",
async: true,
dataType: "json",
data: { url: 'some-url-to-verify' },
success: function (data) {
if (data.Exist === false) {
urlIsValid = true;
}
else {
alert('URL already exist');
urlIsValid = false;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus, "Error: " + errorThrown);
}
});
You're sending an object with a url property, but expecting the body to be a string.
Try changing datatype and data as such:
dataType: "text",
data: 'some-url-to-verify',
I have sample code and you can try something like this
//JavaScript
var command = {
url: $("#txtOrigin").val()
};
$.ajax({
type: "POST",
url: "/api/booking",
contentType: "application/json",
data: JSON.stringify(command),
dataType: "text",
success: Created,
error: Failed
});
//C# MVC Controller
public async Task<IActionResult> Create([FromBody] CreateBookingCommand command)
{
}
This question already has answers here:
How do you post a JSON file to an ASP.NET MVC Action?
(4 answers)
Closed 3 years ago.
I am trying to send my email and password to my home Controller jsonresult method.
values of email and password are displayed in first alert but when i am passing userCredential to data it displays alert undefined.
values of email and password are not getting passed in ajax post method
$("#button_val").click(function () {
var userCrdential = "email=" + $("#username").val() + "&password="
+ $("#pwd").val();
alert(userCrdential);
$.ajax({
type: "POST",
url: "/Home/adduser",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: userCrdential,
success: function (res) {
// alert("data is posted successfully");
if (res.success == true)
alert("data is posted successfully");
else {
// alert("Something went wrong. Please retry!");
}
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr.statusMessage);
}
});
});.
controller
[HttpGet] public JsonResult adduser(user obj) { }
By looking at your comment, the first thing that I observed is that, you are using the post method on ajax call while at the controller level, it is the http get. It could be the problem. It is good if you can put the code for your action method too.
Here is the sample example of post object through ajax in mvc,
[HttpPost]
public ActionResult YourMethodName(MyViewModel myViewModel)
{
//your code goes here.
}
You can make the ajax call like below,
var requestData = {
Email: 'pass the email value here',
Password: 'pass the password value here')
};
$.ajax({
url: '/en/myController/YourMethodName',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
},
async: true,
processData: false
});
In your controller method you use [HttpGet] but in ajax request you write POST. So, go to one option POST or GET. I write the solution with GET First change your Controller method with this:
[HttpPost]
public JsonResult adduser(string email, string password) {
// work here
}
Then modify your code:
$("#button_val").click(function () {
var userCrdential = "email:"+ $("#username").val()+", password:"+ $("#pwd").val();
alert(userCrdential);
$.ajax({
type: "POST",
url: "/Home/adduser",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {userCrdential },
success: function (res) {
// alert("data is posted successfully");
if (res.success == true)
alert("data is posted successfully");
else {
// alert("Something went wrong. Please retry!");
}
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr.statusMessage);
}
});
});
In my MVC3 app, I'm using $.ajax to call a method of type JsonResult to get data to be displayed:
function GetData(e) {
var ordersId = e.row.cells[0].innerHTML; //this is fine
$.ajax({
type: "POST",
url: "/Documents/GetDocumentData",
contentType: "application/json; charset=utf-8",
data: "{'id': '"+ordersId +"'}",
dataType: "json",
success: function (result) {
//load window
},
error: function (result) {
if (!result.success)
//show error
}
});
This is my Action:
[HttpPost]
public JsonResult GetDocumentData(string id)
{
//my code
return Json(new { success = true});
}
When im debugging on my development machine, it works fine. I deployed it to my test web server and i get '404 page not found dev/testwebsite/Documents/GetDocumentData' I should get this when debugging if something was wrong, but i dont. Why am I getting this error? Thanks
Your URL in the javascript is wrong, if that dev/testwebsite/Documents/GetDocumentData is the URL on the server.
You should be using #Url.Action() to automatically form those URLs in the cshtml page.
Example:
#Url.Action("actionName","controllerName" )
So, for your specific case, it would be:
#Url.Action( "GetDocumentData", "Documents" )
In the javascript, it would look like this:
function GetData(e) {
var ordersId = e.row.cells[0].innerHTML; //this is fine
$.ajax({
type: "POST",
url: '#Url.Action("GetDocumentData","Documents")',
contentType: "application/json; charset=utf-8",
data: "{'id': '"+ordersId +"'}",
dataType: "json",
success: function (result) {
//load window
},
error: function (result) {
if (!result.success)
//show error
}
});
i use first time ajax call from asax page.
it is working fine i am getting data in C# page and but when trying get success function than i am getting error msg in error function
"SyntaxError: JSON.parse: unexpected character"
here is my code
var options = {
type: "POST",
url: "ChemistrieAddToCart.aspx",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function () {
alert("sucsess");
},
error: function (xhr, status, error) {
alert("failed" + xhr.responseText);
alert(error);
alert(status);
}
};
var returntext = $.ajax(options).responseText;
if (returntext = "added") {
alert("Matched");
window.location="shoppingcart.aspx"
}
else {
alert("not completed");
}
Thanks.
if you are passing <img src="1-800-optisource.com/Email/image/jsonstring.jpg"; width="497" height="394"/> as Json string that its is wrong you might look at json format first than pass the value might give you idea and resolve your issue
check json over here : http://www.json.org/
I want to use jQuery to make a call to a c# web service called c.ashx which checks whether that username is valid and returns an error message as a string.
What should I put for data: and content type: if the return value of the c# webservice is a string value?
jQuery.ajax({
type: "GET",
url: "/services/CheckUserName.ashx",
data: "",
contenttype: "",
success: function (msg) {
alert("success");
},
error: function (msg, text) {
alert(text);
}
});
I have created a .asmx file instead, but it doesn't get called by the jQuery. Is the following correct?
jQuery.validator.addMethod("UsernameCheck", function (value, element) {
jQuery.ajax({
type: "POST",
url: "/services/CheckUsername.asmx?CheckUsername",
data: '{ "context": "' + jQuery("#username").value + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert("success");
},
error: function (msg, text) {
alert(text);
}
});
});
Data should contain the parameters of the method you are calling in a web service. However, the ashx extension is for an HTTP Handler, which is not a good choice for this scenario. A web service should by used instead.
So if you were calling /services/LoginServices.asmx?CheckUserName, and CheckUserName.asmx had a webmethod ValidateUser such as
public string ValidateUser(string username)
then the data attribute for jQuery would be
data: '{ "username": "' + usernameValue + '"}'
your contentType should be application/json; charset=utf-8, and dataType should be "json".
Note that you're not going to call /services/CheckUserName.asmx, the name of the method in the web service has to be appended to the webservice url, /services/LoginServices.asmx?CheckUserName.
Also, you'll need to change your type to "POST".
Here's a complete example:
$.ajax({
type: 'POST',
url: 'LoginServices.asmx/CheckUserName',
data: '{"username": "' + usernameValue + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
alert("Result: " + msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus);
}});
Hope this helps
The jQuery code wasn't working because it wasn't calling the webservice. I fixed this by creating a HTTP handler class and passing it the username. I changed the value for data: to the following and it passed the username entered by the user:
data: "username=" + jQuery("#username").val(),