Jquery ajax autocomplete calling a method for data - c#

$(function () {
$("#tbNominalAccounts").autocomplete({
source: function (request, response){
$.ajax({
url: "TestPage3.aspx/GetUserNominalAccounts",
type:"POST",
datatype:"json",
data :{ searchText : request.term},
success: function(data)
{
response(
$.map(data, function(item)
{
return { label: item.NominalAccount, value:item.NominalAccount, id:item.NominalAccount}
}))
}
})
}
});
});
Added breakpoints and it hits the ajax call but when i put a breakpoint on the method GetUserNominalAccounts it doesent even reach it!! Any ideas of why its not posting?!
I have a textbox with an ID of #tbNominalAccounts just for background information

Reformat your data like so:
pString = '{"searchText":"' + request.term + '"}';
$.ajax({
data: pString,
...
and your server side code should have been properly "decorated" to allow page access.
Thought I would add some code from a working sample using asp.net: you might need this converter for generic handling of the asp.net data:
dataType: "jsond",
type: "POST",
contentType: "application/json",
converters: {
"json jsond": function(msg)
{
return msg.hasOwnProperty('d') ? msg.d : msg;
}
},
EDIT: And for the use of the return value:
focus: function(event, ui)
{
return false; // return "true" will put the value (label) from the selection in the field used to type
},

try putting a contentType in the ajaxRequest:
contentType: "application/json; charset=utf-8",
I've noticed that when using jQuery Ajax the default content Type application/x-www-form-urlencoded doesn't work well enough.

Related

Ajax method always goes to error function

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

Ajax POST Request when Leave the TextBox ASP.NET

I Need Send to send a POST request , Every-time User leaves the text Box. Need some guidance and calling procedures.
This is my script
<script type="text/javascript">
function getReferenceNo() {
var postData = { id: "test" };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "xyz/test",
data: JSON.stringify(postData),
datatype: "json",
success: function (result) {
//do something
alert("SUCCESS");
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert("failed");
}
});
}
or any other possible way to just send a request to controller. Actual reason is i need to do some background calculation and store the result in the session with a value of view for further use.
use onblur with input tag as below:
<input onblur="getReferenceNo()" type="text" />

$.post or $. ajax post in c# .net

I have implemented the following $.Post Jquery function in my asp.net page MAIN Page.aspx
the
$.post({ url: "MAIN Page.aspx",
data: { "Status":ddl },
contentType: "application/json; charset=utf-8",
dataType: "json",
});
where ddl is my data to be posted ...i have placed this $.post in the document.ready() and i tried accessing the posted value in the code behind as
var status= Request.Form.Get["Status"]...
but when i run the code the value of the status is null..
please help and guide if i am correct in my implementation of the logic
Try like this:
$.post('MAIN Page.aspx', { status: ddl }, function(result) {
alert('success');
});
and on your server:
var status= Request.Form["Status"];
Also you haven't shown what this ddl javascript variable is and how you assigned it a value but make sure that it is not a complex object but it contains some simple type.
Alternatively if you want to use the $.ajax method:
$.ajax({
url: 'MAIN Page.aspx',
type: 'POST',
data: { status: ddl },
success: function(result) {
alert('result');
}
});

What is wrong with this JQuery AJAX code

I was facing some problem with AJAX code. I was using MVC3 for our project. My requirement is bind the dropdown value using AJAX when page load. What happens when loading the page, the AJAX request send to the controller properly and return back to the AJAX function and binds the exact values in dropdown. But sometimes (When page refreshed or first time load) its not binding retrieved value. Rather its showing default value. Pls see my code and suggest me where i am doing wrong.
Edit: Even i tried to use async property to false. Its not at all send to the controller action method for getting the data.
Code
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetUser", "Invoices")',
data: "{'id':" + JSON.stringify(currval) + "}",
dataType: "json",
async: true,
success: function (data) {
$("#User-" + curr).select2("data", { id: data.Value, Name: data.Text });
$(this).val(data.Value);
}
});
Thanks,
Let's say your Action method is below
public JsonResult hello(int id)
{
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
and JQuery should be like below
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var currval = 2;
$.ajax({
url: 'URl',
async: true,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ id: currval }),
success: function (data) {
}
});
});
</script>
You are declaring your data property incorrectly. Try this:
data: { id: currval },

Data Format Jquery Ajax Post Cross Domain Call Asp.Net MVC method

I am trying $.ajax post MVC call from http to https cross domain.
Client Side
enter code here
$.ajax({
type: 'post',
crossDomain: true,
url: 'https://localhost/views/Member/VerifyEmail',
beforeSend: function () { alert('I am sending'); },
data: '{name:"John"}',
dataType: "json",
success: function (data) { pdata = data; }
});
Server Side
[RequireHttps]
[HttpPost]
public string VerifyEmail(string name){
return "got it"
}
I have added Access-Control-Allow-Origin to web.config so the call can be established fine. Now the problem is on server side I got variable name = null
I have also checked debugging and found the data has actually been send to server
HttpContext.Request.Form
{%7bname%3a%22hello%22%7d}
[System.Web.HttpValueCollection]: {%7bname%3a%22hello%22%7d}
The question is how I could retrieve it from the web method?
%7bname%3a%22hello%22%7d This is HTML entity String please Decode the String then parse for JSON.
I think you can change your call to
$.ajax({
type: 'post',
crossDomain: true,
url: 'https://localhost/views/Member/VerifyEmail',
beforeSend: function () { alert('I am sending'); },
data: 'John',
dataType: "text",
success: function (data) { pdata = data; }
});

Categories

Resources