my jquery showing this error? - c#

I am trying to get list of user data from a web service file which is called via AJAX. Here is my code :
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript">
var param;
var resultarr;
$(document).ready(function () {
param = document.getElementById('MainCT_dtvJobVac_PIC').value;
// Load countries then initialize plugin:
$.ajax({
type: 'POST',
contentType: 'application/json;',
data: '{keyword:' + JSON.stringify(param) + '}',
dataType: 'json',
url: 'SvcADUser.asmx/GetADUserList',
success: function (result) {
//alert(result.d)
resultarr = result.d;
}
})
// Initialize autocomplete with local lookup:
$('#MainCT_dtvJobVac_PIC').autocomplete({
source: resultarr
});
});
</script>
resultarr will output an array with this values :
[ "Administrator", "Guest", "krbtgt", "phendy" , "Genin" , "Hendra" , "andri" ]
It throws this:
TypeError: this.source is not a function [Break On This Error]
this.source( { term: value }, this._response() );
What do I need to fix here? I am struggling on this for 2 days, some help would be appreciated.

Move the autocomplete initialization inside the ajax success callback:
success: function (result) {
//alert(result.d)
resultarr = result.d;
$('#MainCT_dtvJobVac_PIC').autocomplete({
source: resultarr
});
}

Ajax calls are asynchronous. Lets examine your code:
$.ajax({ .... } ); // (1)
$('#MainCT_dtvJobVac_PIC').autocomplete({ ... } ) // (2)
The autocomplete initialization (2) occurs after calling the service (1), but it is unclear if the AJAX request has succeeded and returned the response. There is a great chance that you are initializing the autocomplete with empty or undefined data - when the connection is slow, or it fails for some reason, the success callback might not get executed at the point of setting the autocomplete (2). The correct way to do this is to initialize the autocomplete in the AJAX callback, because then the response data is guaranteed to be present:
$.ajax({
type: 'POST',
contentType: 'application/json;',
data: '{keyword:' + JSON.stringify(param) + '}',
dataType: 'json',
url: 'SvcADUser.asmx/GetADUserList',
success: function (result) {
resultarr = result.d;
$('#MainCT_dtvJobVac_PIC').autocomplete({
source: resultarr
});
}
})

Related

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" />

JQuery Autocomplete on .NetCore 2 MVC

I'm working on an autocomplete that calls a method on my home controller, the javascript calls the method and returns the array. However the values do not display on the text box drop down, nothing does.
If I use a straight array as the source and don't call the home controller then it works just fine.
I don't see what I'm missing here, so I narrowed down the home controller method just to return an array using no logic until I figure this problem out.
Home Controller Method:
public string[] GetPatientName()
{
var names = new List<string> { "Bent","Boon","Book", "Al", "Cat", "Doe", "Ed", "Fox", "George" };
return names.ToArray();
}
Javascript:
<script language="javascript" type="text/javascript">
$(function() {
$('#tags').autocomplete({
source: function(request, response) {
$.ajax({
url: "/Home/GetPatientName",
data: "{ 'pre':'" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function(data) {
response($.map(data.d,
function (item) {
alert(item);
return { value: item }
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
delay: 0
});
});
</script>
HTML
<form>
<input id="tags" type="text" />
</form>
2 things:
1. From the top of my mind, if it wirked with a regular array and didnt work with the result of jQuery map function you probably need to ad .get() in order to get a clean array. To be precise
$.map(data.d,function (item) {
alert(item);
return { value: item }
}).get();
2. If that doesnt work, you would really have to share more data like what is the "response" function and exactly what response you are getting from the server (you could get that from the web browser's dev tools)

JQuery button is not triggering service call via ajax

I have a JSON service and i am trying to execute this service via ajax call through jquery in webpage. When i have created button and trying to execute click event but i am not able to get any alert message as well as service call also not triggering that means click event itself is not firing at all . please help!
below is code
<title></title>
<script src="JavaScript.js"></script>
<script type="text/javascript">
$(document).ready(function () { });
$('#buttonnew').click(function () {
alert("Hi");
$.ajax({
url: 'service2.svc/GetRestriction',
method: 'post',
contentType: 'application/json',
data: ({ property: '99883', code: 1 }),
dataType: 'json',
success: function (DATA) {
alert("hi");
},
error: function (err) {
alert(err);
}
});
});
</script>
You need to wire up the click event when the DOM has been loaded.
$(document).ready(function(e) {
$('#buttonnew').click(function () {
alert("Hi");
$.ajax({
url: 'service2.svc/GetRestriction',
method: 'post',
contentType: 'application/json',
data: ({ property: '99883', code: 1 }),
dataType: 'json',
success: function (DATA) {
alert("hi");
},
error: function (err) {
alert(err);
}
});
});
});
I think the only error you have in your code is that you are asigning tht click event on the button before document is ready. So you can just Try this :
<title></title>
<script src="JavaScript.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#buttonnew').click(function () {
alert("Hi");
$.ajax({
url: 'service2.svc/GetRestriction',
method: 'post',
contentType: 'application/json',
data: ({ property: '99883', code: 1 }),
dataType: 'json',
success: function (DATA) {
alert("hi");
},
error: function (err) {
alert(err);
}
});
});
});
</script>
I've tested it with Jquery 2.2.2.
I hope it helps !

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

Ajax Autocomplete using jQuery

I have the following code to retrieve departments names from db I have problem formatting CSS of data like background and font color
<script type="text/jscript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/AjaxLoad.asmx/GetBrands",
dataType: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
success: function(data) {
var datafromServer = data.d.split(":");
$("[id$='tbBrands']").autocomplete({
source: datafromServer
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
</script>
<div id="ajaxbrands">
<input id="tbBrands" runat="server" />
</div>
Any idea how to add text, like <p > or <div> to each list item?
I can think on 2 options:
1.Add it in your php code (like rdlowrey aadvised),
for instance:
$query = mysql_query("SELECT * FROM brands");
while($brand = mysql_fetch_array($query))
{
echo "<p>".$brand['name']."</p>";
}
2.Use jquery to do it.
"Split" converts your string to an array of sub-strings.
You should edit the autocomplete function so it will add each sub-string the desirable code. Add the function's code for more help.
Well, i assume you are using .NET, so, i wont mess around with server side code.
You can add this to your success callback function:
success: function(data) {
var datafromServer = data.d.split(":");
for(var item in datafromServer){
datafromServer[item] = '<p class="whatever">' + datafromServer[item] + '</p>';
}
$("[id$='tbBrands']").autocomplete({
source: datafromServer
});
},
The for loop added will surround every item in the array, with a p, or div, or whatever.

Categories

Resources