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.
Related
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" />
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)
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
});
}
})
I am using asp.net datepicker. Then executing a static event when a user clicks on a date through jquery like such:
<script>
$(document).ready(function () {
$("#datepicker").datepicker({
onSelect: function (dateText, inst) {
$("#<%= lblDate.ClientID %>").text("Are available on " + $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' }).val());
$.ajax({
type: "POST",
url: "Schedule.aspx/DisplayAvail",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Do something interesting here.
}
});
}
});
});
</script>
Code behind:
[WebMethod]
public static void DisplayAvail()
{
//Grab data from db to check avail from this date
}
Which works fine. But, from this static method there is no way to access page level objects. How can I send data from this method to the page?
Have a look here. You can get this via NuGet
http://james.newtonking.com/projects/json-net.aspx
Once you have the NewtonSoft Json dll added as a reference to your project which contains the webmethod, you can use JSONConvert to serialize your available dates and send it client side.
public IEnumerable<string> AvailableData {get; set;}
[WebMethod]
public static void DisplayAvail()
{
this.AvailableData = GetRequiredData();
this.AvailableData = JSONConvert.SerializeObject(this.AvailableData);
}
And on the client side, you can do:
$(document).ready(function () {
$("#datepicker").datepicker({
onSelect: function (dateText, inst) {
$("#<%= lblDate.ClientID %>").text("Are available on " + $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' }).val());
$.ajax({
type: "POST",
url: "Schedule.aspx/DisplayAvail",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var arr = <%= this.AvailableData %>;
$.each(arr, function(index, value) {
// Do something with the data
});
});
}
});
}
});
});
I decided the best rout to go is to use JQuery load() function to load an external page into the current page as such:
...Jquery
$("#GetData").load("getData.aspx?GetDate=012420012");
...html
<div id="GetData">
...
</div>
Thanks for all your feedback, but I think that this is the best way to go. Cheers! :)
You could try using PageMethods():
This is a simple tutorial Simple PageMethods example.
And also you need to do this:
<asp:ScriptManager ID="ScriptManager" runat="server" EnablePageMethods="true" />
;)
$(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.