This is my ajax post:
$.ajax({
type: "POST",
url: "AddUpdateConfigs",
data: ({id: #Model.QueueMonitorConfigurationsID, pathType: $('#ddlConfigTypeName').val(), threshold:$('#ddlThreshold').val(), valueType:$('#ddlValueTypeName').val(), location: $('#txtbLocation').val(), limit: $('#txtbLimit').val(), config: $('#NewOrUpdate').val() }),
dataType: JSON,
statusCode: {
404: function() {
alert("Data is duplicated");
},
405:function(){
alert("Location Path is not correct");
},
406: function(){
alert("Location Path has to be UNC path");
},
407: function(error){
alert(error);
}
},
success: function()
{
alert ("Success");
}
});
It works good at the beggining and the AddUpdateConfigs function is called.
That function finished with return Json(result); where result is true.
And then my success is not firing because I'm not getting the alert
Any ideas please, what am I doing wrong?
Thank you
success: function()
this should be
success: function(data)
Never mind, I solved it using:
[HttpPost]
public ActionResult AddUpdateConfigs(int id, string pathType, string threshold, string valueType, string location, int limit, string config)
{return new HttpStatusCodeResult(410, "New Data inserted");}
and:
$.ajax({
type: "POST",
url: "AddUpdateConfigs",
data: ({id: #Model.QueueMonitorConfigurationsID, pathType: $('#ddlConfigTypeName').val(), threshold:$('#ddlThreshold').val(), valueType:$('#ddlValueTypeName').val(), location: $('#txtbLocation').val(), limit: $('#txtbLimit').val(), config: $('#NewOrUpdate').val() }),
dataType: 'application/json',
statusCode: {
404: function(){
alert("Data is duplicated");
},
405:function(){
alert("Location Path is not correct");
},
406: function(){
alert("Location Path has to be UNC path");
},
407: function(error){
alert(error);
},
410:function(result){
alert("Item added correctly");
},
411:function(result){
alert("Item updated correctly");
}
}
});
First, on your controller method you should use this:
return Json(result, JsonRequestBehaviour.AllowGet);
Basically, if your action method does not return sensitive data, then it should be safe to allow the get.
However, MVC puts this in with DenyGet as the default to protect you against this attack. It makes you consider the implications of what data you are exposing, before you decide to expose it over HTTP GET.
In your AJAX, change your ContentType to
contentType: 'application/json'
JS:
var queueMonitor = { id: #Model.QueueMonitorConfigurationsID,
pathType: $('#ddlConfigTypeName').val(),
threshold:$('#ddlThreshold').val(),
valueType:$('#ddlValueTypeName').val(),
location: $('#txtbLocation').val(),
limit: $('#txtbLimit').val(),
config: $('#NewOrUpdate').val() };
$.ajax({
url: 'AddUpdateConfigs ',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ parameterName: queueMonitor }),
success: function() {
alert("Success");
}
});
Controller:
[HttpPost]
public JsonResult AddUpdateConfigs(QueueMonitor parameterName) //Note parameter being same as that passed in AJAX Call.
{
//Logic
return Json(result, JsonRequestBehaviour.AllowGet);
}
My success wasnt firing because I wasn't returning with a success, I was using a random error code because I thought I can just give them numbers like that.
For my case it was because the form beaviour, closed before reaching the success/error event
preventDefault() solved it
Related
I've found a small problem in sending just plain text(string) via ajax compared to sending an json object.
I have currently this setup working
(cs)html
<label for="search">
<i class="fa fa-search" onclick="sendtoC()"></i>
<input type="search" id="search" placeholder="Sök här..." autofocus; />
<input type="button" id="SÖK" value="SÖK" onclick="sendtoC()" />
Script
<script>
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}
and current controller
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return Json(new { success = true, message = input }, JsonRequestBehavior.AllowGet);
}
I would like to just send a straight string to the controller and i tried this Script
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "text",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: invalue ,
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}});}
with this Controller
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return View(input);
}
however this didn't work, the input string was shown to get value of null and ajax gave error. I currently have no idea of how to fix this nor what gives the error. If someone could Point me in the right direction I would appreciate it
You can simply use the $.get function here and secondly you should use the Ùrl.Action helper for getting the url against the controller action method, as the magic strings would cause issues in deployments where the application might be deployed in sub-directories and in those case the url becomes wrong :
$.get('#Url.Action("SearchResults","Home")?input='+invalue , function (data) {
if (data.success) {
alert(data.message);
}
});
You can easily pass it as a request parameter, since you've also set the type to "GET".
url: "/Home/SearchResults?input="+invalue
You also have to remove the data attribute. Let me know if it helps.
UPDATED ANSWER
datatype is what you are expecting to return from the server. Content type is what you are sending. so to return a view change datatype to htmL.
dataType: 'html',
the problem is that when you call the function sendtoC you are not receiving any parameters in the function. Change the function to accept a parameter.
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC(invalue ) {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}
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);
}
});
});
I have to call a REST url for example : https://{baseurl}/employees/taxvalidation/. The Request type is JSON, but I'am always get the error Alert. I can't figure out what is the wrong in my code. I am using JQuery
The Supported HTTP Method is : PUT (HTTP PUT with correct request needs to be made) and also i need to pass a API key: XXXXX-XXXXX-XXXXX-XXXXX as request Header.
I have just have two mandatory fields in web page Employee name and Employee Tax.
I have tried the below using JQuery Ajax call.
Request Body Sample:
"name": "Company XYZ", /* mandatory */
"TAX": "*********", /* mandatory */
"taxType": "U", /* Could be E, S, or U */
"address": "2501 Boilermaker road", /* optional */
"citystatezip":"Lapalma ca 76567", /* optional */
"country": "US", //optional
"checks" : "DT",`enter code here`
"details": "DT"`enter code here` //optional
$(function() {
$("#btnSubmit").click(function() {
alert("Hi JQuery");
var URL = "https://api.dev.amx-city.com/tesmdm/dev/tesmdm/empcatalog/partners/taxvalidation/";
$.ajax({
url: URL,
headers : {
'AMX-API-KEY': '487b9474-27a6-4d21-8eda-c3a2a14e4ebe'
},
type: 'POST',
data: {
name: 'Employeename',
tin: '79847324987',
tinType: 'U'
},
dataType: 'json',
success: function(result) {
alert(result);
},
error: function (restul) {
alert(result);
}
});
});
});
when i try to hit the button the debugging is stopped till Alert, after that i don't see the URL is hitting. Let me know if i am doing any wrong?
I am able to get the response now. Below is the working script
$.ajax({
url: URL,
type: "PUT",
headers: {
'AXT-API-KEY': '48776474-26a6-4d21-8eda-c3a2a14e4ebe'
},
data: JSON.stringify({"name": "SupplierName, LLC","tin": "522323454","tinType": "U","checks": "DT"
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr);
alert(thrownError);
}
});
It worked when i use the key in beforeSend function. But i am not sure the difference.
beforeSend: function (xhr) {
xhr.setRequestHeader("AXT-API-KEY': '48776474-26a6-4d21-8eda-c3a2a14e4ebe");
in my ASP.net MVC application, I have a button that call a controller action which takes longer (>60 mins) to complete. To keep my session alive I am using setInterval function.
reference: http://www.dotnetcurry.com/ShowArticle.aspx?ID=453&AspxAutoDetectCookieSupport=1
view looks like:
#Html.DevExpress().Button(settings =>
{
settings.Name = "LoadData";
settings.Text = "Load Data";
settings.ClientSideEvents.Click = string.Format("function(s, e) {{ OnButtonClick(s, e, '{0}', '{1}'); }}", Url.Action("Start", "ImportData", null), Url.Action("alive", "ImportData", null));
settings.UseSubmitBehavior = false;
}).GetHtml()
my OnButtonClick Function looks:
function OnButtonClick(s, e, startUrl, progressUrl) {
//debugger;
StartActionOnServer(startUrl);
setInterval(keepalive, 600000); //every 10 minutes.
}
Keep Alive looks like:
function keepalive()
{
console.log("I am alive");
$.ajax({
type: 'POST',
url: '/ImportData/alive',
dataType: "text",
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (msg) {
debugger;
console.log("pinging");
},
Error: function (xhr) {
debugger;
alert(xhr)
},
});
}
my issue is that code is not hitting my Controller function, as result I never get result back in my success block.
success: function (msg) {
debugger;
console.log("pinging");
},
Controller action function:
[HttpPost]
public ActionResult alive()
{
var result = "Still Alive";
return Content(result);
}
Instead of me hardcoding: console.log("I am alive"); I would like Controller to return this.
my console.log looks like attached screeshot
Any idea how to get value from Controller ?What am I doing wrong here.
Thanks.
This solved my issue:
function keepalive()
{
console.log("I am alive");
$.ajax({
type: 'POST',
url: '/ImportData/alive',
dataType: "text",
contentType: "text",
success: function (msg) {
console.log(msg);
},
Error: function (xhr) {
alert(xhr)
},
});
}
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"