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');
}
});
}
Related
My c# action looks like:
[HttpPost]
public JsonResult GetItems(int id)
{
var productsQryList = some-query-to-getitems.ToList();
if(productsQryList != null)
{
return Json(productsQryList);
} else
{
return Json(new());
}
}
In my view, the autocomplete configuration looks like:
$("#productInfo").autocomplete({
minLength: 1,
source: function( request, response ) {
$.ajax({
type: "GET",
url: "/api/purchase/SearchProductsSimple",
data: {
term: request.term
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function( data ) {
response( data );
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
select: function (event, ui) {
if (ui.item) {
$("#order-items-table tbody tr").remove();
$.ajax({
cache: false,
type: "POST",
url: "/api/purchase/GetItems",
data: { "id": ui.item.value },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
response($.map(data.d, function (itemList) {
for(const item of itemList) {
appendOneRow(item);
counter++;
}
countTrSetIndex();
return false;
}))
},
failure: function (response) {
alert(response.d);
}
});
}
}
});
In firefox plugin RESTED,
The GetItems method runs good if I change its attribute to HttpGet.
But, if The attribute is HttpPost, I got 400 error.
By the way, The select event must be POST call.
wait for resolution.
Thank you guys.
You might have [AutoValidateAntiforgeryToken] attribute on your controller, so you must send forgery token value at ajax call.
data: { "id": ui.item.value,
"__RequestVerificationToken":$( "input[name='__RequestVerificationToken']" ).val() },
I have this simple ajax method:
$.ajax({
type: 'POST',
url: 'http://localhost:1195/widget/postdata',
datatype: "jsondata",
async: false,
success: function (data) {
alert("ok")
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
And this simple method in c#:
[HttpPost]
public JsonResult PostData()
{
return Json("1");
}
When I check the inspector console I have "1" in response but my ajax method always goes to error function.
Why is it so?
In your AJAX call it should be dataType: "json" and not datatype: "jsondata". You can refer to the docs
Also use #Url.Action tag in your url call: url: '#Url.Action("postdata", "widget")'
For a small test, I have used the following AJAX call to the same controller method that you have posted and I am getting the correct result:
$(document).ready(function () {
$("#button_1").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url:'#Url.Action("PostData", "Home", null, Request.Url.Scheme)',
datatype: "json",
async: false,
success: function (result) {
alert(result);
},
error: function (error) {
alert(error);
}
});
});
});
</script>
<button id="button_1" value="val_1" name="but1">Check response</button>
Output:
Change the Ajax request to the following :
$.ajax({
type: 'POST',
url: '/widget/postdata',
datatype: "json",
async: false,
success: function (data) {
console.log(data);// to test the response
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
Always use relative URL instead of full URL that contains the domain name, this will make the deployment easier so you don't have to change the URls when going live
I want to get new value from controller and set it to view when form submit.
Controller:
public JsonResult GetVoucherNo()
{
var voucherno = 1001;
var lastvoucherno = db.PaymentsAndReceipts.Where(x => x.StakeHolder.StakeHolderType.Name == "Supplier").OrderBy(x => x.VoucherNo).ToList().LastOrDefault();
if (lastvoucherno != null)
{
voucherno = lastvoucherno.VoucherNo.GetValueOrDefault() + 1;
}
return new JsonResult { Data = voucherno, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
My Jquery function:
I just want to do when this function calls, I can get the value from controller action.
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: 'Payments/GetVoucherNo',
dataType: "json"
}).done(function () {
//don't know what to do here.
});
}
The data should be available in the done function argument like this:
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: 'Payments/GetVoucherNo',
dataType: "json"
}).done(function (result) {
//don't know what to do here.
console.log(result);
//you should see the exact JSON you return from the controller
});
}
I done it with success.
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: '/Payments/GetVoucherNo',
dataType: "json",
success: function (result) {
console.log(result);
return $('#VoucherNo').val(result); //to set value in textbox.
},
error: function (xhr, status, error) {
alert(xhr);
console.log(xhr, status, error);
}
});
}
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)
},
});
}
I'm currently working on an ASP.Net MVC project.
I have a JavaScript function which takes an XML string as input. I would like to send this to the controller.
I have done so using an AJAX request, but in the controller the string is null.
View:
function save() {
var xml = scheduler.toXML();
alert(xml);
var url = '#Url.Action("Save", "Home")'
$.ajax({
url: url,
Type: "POST",
dataType: 'json',
async: false,
data: xml,
contentType: 'application/json; charset=utf-8',
success: function (data) { alert("OK");},
error: function (jqXHR, exception) {
alert('Error message.');
}
});
Controller:
public ActionResult Save(string xml)
{
Console.WriteLine(xml);
W6ViewModel viewModel = new W6ViewModel();
viewModel.engineers = db.W6ENGINEERS.ToList();
viewModel.tasks = db.W6TASKS.ToList();
viewModel.skills = db.W6TASKS_REQUIRED_SKILLS1.ToList();
var engList = new List<object>();
foreach (var engineer in viewModel.engineers)
{
engList.Add(new { key = engineer.ID, label = engineer.Name });
}
ViewBag.engineers = engList;
return View("Index", viewModel);
}
var xml = scheduler.toXML()
alert(xml):
Error Code (Sorry, wall of text):
[HttpRequestValidationException (0x80004005): A potentially dangerous Request.QueryString value was detected from the client (xmlString="<data><event>
Name your parameter like this:
function save() {
var xml = scheduler.toXML();
alert(xml);
var url = '#Url.Action("Save", "Home")';
$.ajax({
url: url,
Type: "POST",
dataType: 'json',
async: false,
data: { xml: xml},
contentType: 'application/json; charset=utf-8',
success: function (data) { alert("OK");},
error: function (jqXHR, exception) {
alert('Error message.');
}
});
Also put this tag above you controller action:
[ValidateInput(false)]
See the following ajax call:
$.ajax({
url: '#Url.Content("~/myaccount/CheckDuplicateEmailAddress")',
data: { "emailAddress": email },
async: false,
type: "post",
success: success,
error: error
});
And controller action is below. you need to send param as this:
data: { "emailAddress": email }
Remember case sensitivity and double quotes:
public bool CheckDuplicateEmailAddress(string emailAddress)
{
}