Json data not returning back to success - c#

Please consider below code. I am loading my products view using below ajax call.
$.ajax({
cache: true,
type: "GET",
url: url,
data: json.stringify(data),
success: function (data) {
var mainview = $(data).find(".maindiv");
$('.maindiv').replaceWith(mainview);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error Occured...... No Products Found');
},
complete: function () { subscribeProgress.hide(); }
});
Now when I load this view there is add to cart button for each product on which another ajax call is executed to check if customer is registerd or guest and accordingly popup for register is shown. Now for registering customer, another ajax method is called which works properly but json data is not returned to the success and is directly shown on the page.
Below id code for registering customer through popup
$('#formpopupReg').unbind('submit');
$('#formpopupReg').bind('submit', function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
// you can post your model with this line
data: $(this).serialize(),
success: function (data) {//Json should get back to this call but doesnt
if (data.status == "Wrong email") {
$('#modelerrors').text("Wrong email");
}
if (data.status == "emailexists") {
//Code on Error
}
if (data.status == "registersuccess") {
location.reload();
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Internal Error.');
},
complete: function () { }
});
}
return false;
});
Any solutions.I want json data to return back to success call.

Add dataType:"json" to your ajax call.

Try this, problem is your } is extra in your code, and missing dataType: 'json', if you use json.
$.ajax({
cache: true,
url: url,
dataType: 'json',
data: json.stringify(data),
success: function (data) {
var mainview = $(data).find(".maindiv");
$('.maindiv').replaceWith(mainview);
}
error: function (xhr, ajaxOptions, thrownError) {
alert('Error Occured...... No Products Found');
},
complete: function () { subscribeProgress.hide(); }
});

Related

Jquery ui autocomplete trigger select event then ajax Post to call c# action, but it returns 400 error

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() },

how to use autocomplete on asp.net mvc

I want know how to use autocomplete with database using ajax and the data get faster on local server and Main server also
And i try this script
$("#SI").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetSearchValue","Main")',
dataType: "json",
data: { search: $("#SI").val() },
success: function (data) {
response($.map(data, function (item) {
return { label: items.Name, value: items.Name };
}));
},
error: function (xhr, status, error) {
alert("Error");
}
});
}
});

ASP.net MVC unable to get value back from Controller

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

Autocomplete with Ajax returns No HTTP resource was found that matches the request URI

I am trying to implement an autocomplete on my textbox with data that comes from a web method. The webmethod works on the browser like:
http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers?SearchString=e
and these are the results:
[{"IssuerID":1,"Name":"test tester","ChequeAccountNumber":"12345678","CurrencyCode":"EUR"}]
Now, I am trying to add on the textbox the Name data from the response but I'm getting an error in the function below:
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers?{ 'SearchString': 'e'}'.","MessageDetail":"No action was found on the controller 'ModuleTask' that matches the request."}
Below, my AJAX call seems to fail for a reason, which I believe comes from passing wrongly the parameters. I do not have experience with ajax so far, so your input will be great.
<script type="text/javascript">
$(function () {
$("[id$=TextBox1]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers")%>',
data: "{ 'SearchString': '" + request.term + "'}",
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("[id$=hfIssuerID]").val(i.item.val);
},
minLength: 1
});
});
</script>
My web method:
public class ModuleTaskController : DnnApiController
{
[AllowAnonymous()]
[HttpGet()]
public HttpResponseMessage GetIssuers(string SearchString)
{
try {
List<Issuers> listIssuers = new List<Issuers>();
IssuersController ic = new IssuersController();
listIssuers = ic.GetIssuers(10, SearchString);
return Request.CreateResponse(HttpStatusCode.OK, listIssuers.ToJson);
} catch (Exception exc) {
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc);
}
}
}
Any ideas?
EDIT:
$(function () {
$("[id$=TextBox1]").autocomplete({
source: function (request, response) {
var qstring = '?' + jQuery.param({ 'SearchString': request.term });
$.ajax({
url: '<%=ResolveUrl("http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers")%>' + qstring,
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("[id$=hfIssuerID]").val(i.item.val);
},
minLength: 1
});
});
Your web method is a GET and accepts a querystring yet your Ajax call is trying to pass a JSON object, which is getting appended to the end of your url. You can see this by reading what the URL actually is, in the error message
There are a bunch of different things you can do. This is just one.
// turn your search object into querystring
var qstring = '?'+ jQuery.param({ 'SearchString': request.term});
// append this querystring to the end of your url
$.ajax({
url: '<%=ResolveUrl("http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers")%>' + qstring ,
// remove data and datatype
type: "GET",
//... etc
Also in this case, it doesn't look like you need the ResolveUrl.
Perhaps try your URL as:
url:'http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers' + qstring;

Get selected item using JQuery AutoComplete

I have the code below working. How do I read and set the item selected to a control on the page (i.e. hidden field). NomineeUserName is a property on the object being returned. Thanks for any help provided.
$(function () {
$(".tb").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Service/NomineeWebService.asmx/GetMatchingActiveDirectoryUsers",
data: "{ 'SearchCharacters': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
id: item.NomineeUserName,
value: item.NomineeLastNameFirstName,
data: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function (event, ui) {
selectedItemData = ui.item.data;
}
});
});
In your select handler, it should be pretty simple:
select: function (event, ui) {
$("hidden-input-selector").val(ui.item.id);
}

Categories

Resources