Asp.net Webform page implementing jQuery Autocomplete Widget - asp.net

I want to incorporate jquery autocomplete widget to my aspx page. The "source" for the autocomplete comes from a webservice method.
My script looks like this:
$(".paisProc").autocomplete({
minLength: 0,
source: function (request, response) {
$.ajax({
type: "POST",
url: "/ManifestService.asmx/GetPaises",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'term': request.term }),
success: function (data) {
console.log("reading results...");
response($.map(data, function (item) {
console.log(item.CodigoAduana);
return {
label: item.Descripcion,
value: item.CodigoAduana
};
}));
},
error: function (err, status, error) {
console.log(status);
console.log(error);
}
});
With this setup, as users type in the input control, the expected values are returned from the webservice but the autocomplete does not seem to work. Inspecting the page with Firebug i see the ajax call to the service returns data with this format:
{"d":[{"__type":"dhl.domain.Pais","PaisId":1,"CodigoDHL":"AR","CodigoAduana":"528","Descripcion":"ARGENTINA"},
{"__type":"dhl.domain.Pais","PaisId":481,"CodigoDHL":"DZ","CodigoAduana":"208","Descripcion":"ARGELIA"}]}
I cannot see what the problem with my code, I have followed the indications from the many questions with the same issue in this site with no success yet.
If it can help, the line console.log(item.CodigoAduana) from success callback write "undefined" to the console.

.Net web services returning JSON do so by embedding the payload into a "d" property (as you can see in your capture of the JSON).
Try changing your processing of the response to read from data.d instead of just data, to get to the array you want to map, like this:
response($.map(data.d, function (item) {
console.log(item.CodigoAduana);
return {
label: item.Descripcion,
value: item.CodigoAduana
};
}));

Related

webservice not returning values to on jquery ajax request

I would like consume cross-domain web-service from client with jquery.here is my code
function getId() {
var testid = ($('#<%=PreviousTest.ClientID %> OPTION:selected').val());
jQuery.support.cors = true;
jQuery.ajax({
type: "POST",
url: "../FalconWebService.asmx/minlatency",
data: "{'testId':" + testid + "}",
contentType: "application/json; charset=utf-8",
dataType:"json",
success: function (data) {
alert("catch");
var msg = jQuery.parseJSON(data.Table);
return msg;
},
Error: function () {
alert("error");
}
my webservice returns values in this format
{"Table":[{"minlatency":16.0,"Time":"/Date(1328248782660+0530)/"},{"minlatency":7.0,"Time":"/Date(1328248784677+0530)/"},{"minlatency":13.0,"Time":"/Date(1328248786690+0530)/"},{"minlatency":6.0,"Time":"/Date(1328248788690+0530)/"},{"minlatency":20.0,"Time":"/Date(1328248790707+0530)/"},{"minlatency":12.0,"Time":"/Date(1328248792723+0530)/"},{"minlatency":26.0,"Time":"/Date(1328248794723+0530)/"},{"minlatency":18.0,"Time":"/Date(1328248796723+0530)/"}]}
Calls in cross-domain work in a different way. They create dynamic javascripts that are inserted to the page using a callback function. This function is used to handle the response from the service. The Jquery calls add a "?callback=?" to the URL of the service, where "callback" is the name of the function that will be inserted.
To call cross-domain services with JQuery you have to do the following:
jQuery.ajax({
type: "POST",
url: "../FalconWebService.asmx/minlatency",
data: "{'testId':" + testid + "}",
contentType: "application/json; charset=utf-8",
dataType: "jsonp", //The data type that you must use is JSONP. Basically tells JQuery that the request is cross-domain
success: function (data) {
alert("catch");
var msg = jQuery.parseJSON(data.Table);
return msg;
},
Error: function () {
alert("error");
},
jsonpCallback: 'callback' //Dude to the fact that the JS is being generated dynamicaly, this tells JQuery to use the name "callback" for the function that will handle the result, as it adds "?callback=?" to the URL
});
You could also use "jsonp" instead of "jsonpCallback" if you want to "override the callback function name in a jsonp request" (from JQuery).
It worked for me (in WCF REST services which communicate with JSON messages, but it should work the same way in your case). This is all explained in the JQuery Ajax documentation.
Hope this helps.

$.ajax success not executing

I have in my .js file a function that call a webservices method called getStudents:
[WebMethod(Description = "white student list")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Job> getStudents(long classId)
{
return (new classManager()).getStudents(classId);
}
the method is callled like:
function loadStudents() {
var parameters = JSON.stringify({ 'classId': 0 });
alert(parameters);
$("#ProcessingDiv").show('fast', function() {
$.ajax({
type: "POST",
url: "myWebService.asmx/getStudents",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
$("#ProcessingDiv").hide();
var students= response.d;
alert('yes');
},
error: function(request, status, error) {
alert(request.responseText);
}
,
failure: function(msg) {
alert('somethin went wrong' + msg);
}
});
});
}
$(document).ready(function() {
loadStudents();
});
when i debug,the service web method is executed successfully but i don't get my alert('yes') and neither msg error.
What's wrong?
If you're returning (serialized to JSON) List of objects, then in response you will get JS array of JS objects, so (assuming Job has property p) try response[0].p for p value from first element.
note: I don't know ASP.NET, so maybe response is serialized in another way, thats where tools like Firebug (or other browsers Dev tools) are extremely useful - because you can look how exactly you'r http requests and responses looks like.
ps. And change alert to console.log and look for logs in Firebug console - its better than alert in many, many ways ;]

jQuery + ASP.NET 4.0 ajax page method not working

I have used whole lots of options resolving this, but it is not working.
My breakpoint is not hit in the Web Method. Also, the success function is being called, however, entire page content is returned not the string "hello".
My page does not at all use asp.net ajax scriptmanager. It uses plain jQuery only. I am using ASP.NET 4.0.
In brief, my page method is defined as:
[WebMethod]
public static string Populate()
{
return "hello";
}
The ajax call is:
$.ajax({
url:'WebForm3.aspx/Populate',
data:{},
dataType:"json",
type:"GET",
success: function(msg) {
alert("success");
},
error: function(msg, text) {
alert(text);
}
});
Page methods only work when POSTed to, like this:
$.ajax({
url:'WebForm3.aspx/Populate',
data: '{}',
dataType:"json",
type:"POST",
contentType: 'application/json; charset=utf-8',
success: function(msg) {
alert("success"); },
error: function(msg, text) {
alert(text);
}
});
Don't forget to quote the data argument: data: '{}'.

JsonResult shows up a file download in browser

I'm trying to use jquery.Ajax to post data to an ASP.NET MVC2 action method that returns a JsonResult. Everything works great except when the response gets back to the browser it is treated as a file download instead of being passed into the success handler. Here's my code:
Javascript:
<script type="text/javascript">
$(document).ready(function () {
$("form[action$='CreateEnvelope']").submit(function () {
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (envelopeData) {
alert("test");
}
});
});
return false;
});
</script>
Action method on controller:
public JsonResult CreateEnvelope(string envelopeTitle, string envelopeDescription)
{
//create an envelope object and return
return Json(envelope);
}
If I open the downloaded file the json is exactly what I'm looking for and the mime type is shown as application/json. What am I missing to make the jquery.ajax call receive the json returned?
You are missing a "return false" in the handler of your submit event. If you don't return false, then JQuery will still pass the submit as it would do normally.
<script type="text/javascript">
$(document).ready(function () {
$("form[action$='CreateEnvelope']").submit(function () {
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (envelopeData) {
alert("test");
}
});
// IMPORTANT: return false to make sure the normal post doesn't happen!
return false;
});
return false;
});
</script>
You were almost there!
I have just started using ajax similar to this and first impressions looking at your code would indicate that you dont need to call submit on the form? You only need to do the ajax call. I may be wrong but it might be that the ajax is returning the data and the page is doing a refresh where the page data is replaced with the json data?

How to post data using jQuery in ASP.NET?

I have an ASP.NET application in which i want to post data using jQuery to another page. It means i want post the data of page.
How can i do this with jQuery or AJAX?
Please help me.
$(document).ready(function() {
alert("start");
$("#btnSave").click(function() {
alert("start1");
var aa = 'bb';
var json = "{'ItemName':'" + aa + "'}";
alert("start2");
var ajaxPage = "Default3.aspx?Save=1"; //this page is where data is to be retrieved and processed
alert("start3");
var options = {
type: "POST",
url: ajaxPage,
data: json,
contentType: "application/json;charset=utf-8",
dataType: "json",
async: false,
success: function(response) {
alert("success: " + response);
},
error: function(msg) { alert("failed: " + msg); }
};
alert("start4");
});
});
I am using this code I am getting all alert response but its posting page.
Jquery and JSON works great with ASP.NET. You can call a code behind method directly from javascript and return complex objects, not just string. (for this example to work you need json2.js found here https://github.com/douglascrockford/JSON-js)
//javascript
function postMethod(text){
var jsonText = JSON.stringify({ name:text });
$.ajax({
type: "POST",
url: "yourpage.aspx/GetPerson",
contentType: "application/json; charset=utf-8",
data: jsonText,
dataType: "json",
success: function(response) {
var person = response.d;
alert(person.Name);
}
});
}
//aspx code behind
[WebMethod]
public static Person GetPerson(string name)
{
Person person = new Person(name);
return person;
}
There is load function.
You may use it like this:
$('#somediv').load('http://someaddress',{key:value}, function callback(){});
Second parameter is important - only written in this way performs post.(if you pass array then it performs get)
PS> This is good when you want to read the data, if you want to just do the POST and don't care about what comes back then you may want to use:
http://docs.jquery.com/Ajax/jQuery.post#urldatacallbacktype
Look at $.post() - http://docs.jquery.com/Ajax/jQuery.post
Add all your relevant data, and post away, handling the response with the supplied callback method.
There is a post function in jQuery:
$.post("test.php", { name: "John", time: "2pm" } );
This is copied directly from the jQuery API, so for more details and examples you can look there.
jQuery api
choose Ajax > Ajax Requests > $.post

Resources