Pass JSON array from c# to jQuery - c#

I'm doing jQuery autocomplete. Works fine if I put hard codded JSON array. But it fails when I pass the array from c#. Please help, I spend enough time with it and I'm stuck!
Here is my jQuery code in AutoComplete.aspx
<script type="text/javascript">
$(document).ready(function () {
var msgbox = $("#status");
$.ajax({
type: "POST",
//Page Name (in which the method should be called) and method name
url: "AutoControl.aspx/GetData",
//else If you don't want to pass any value to server side function leave the data to blank line below
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#status").val(msg.d);
}
});
$('#<%=tags.ClientID%>').autocomplete(["c++", "java", "php", "coldfusion"], {
width: 320,
max: 4,
highlight: false,
multiple: true,
multipleSeparator: " ",
scroll: true,
scrollHeight: 300
});
});
</script>
Here is my C# code in AutoComplete.aspx.cs
[System.Web.Services.WebMethod]
public static string GetData()
{
return "\"c++\", \"java\", \"php\"";
}
How do I pass the JSON array from C# to jQuery. With this code I could retrieve the values from c# but some reason JSON is not reading the values.
I want to change this code:
$('#<%=tags.ClientID%>').autocomplete(["c++", "java", "php", "coldfusion"]
to
$('#<%=tags.ClientID%>').autocomplete([ jsonArray_from_C# ]

Have you tried returning an string array?
http://encosia.com/2011/04/13/asp-net-web-services-mistake-manual-json-serialization/
don't try to parse Json, pass the object directly.

Related

How to get data from POST url ajax

Using ajax POST a url http://test/jy/post.php will get some value below
People,1220,temperature,26C,CO2 concentration,30ppm,3.jpg
Want to put each of them separately into my input text.
Trying to alert data, but it show [object],don't know how to do.
Here is my js:
window.onload = load();
function load() {
$.ajax({
url: 'http://test/jy/post.php',
type: 'POST',
success: function (data) {
},
error: function (data) {
alert(data);
console.log(data);
}
});
}
Hope someone can tell me how to do it or hint me , thanks!
I am assuming that the data in the POST response is JSON.
As mentioned by #Kaushik you can use JSON.stringify(data) to convert the JSON data to a string.
First of all, I would recommend that you take a look at the content at the following link which explains JSON objects and how to work with them. JSON Objects - W3 Schools
For my examples, I have used https://jsonplaceholder.typicode.com/todos to return example JSON data.
If you wish to only access certain properties of the JSON object then you could accomplish this using the following code. Please bear in mind that the following code snippet assumes that the JSON object consists of a single record.
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/1',
dataType: 'json',
success: (data) => {
console.log('User ID: ' + data.userId);
console.log('Title: ' + data.title);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
If the JSON data consists of an array of JSON objects then you could approach this with the following code.
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos',
dataType: 'json',
success: (data) => {
data.forEach((record) => {
console.log('User ID: ' + record.userId);
console.log('Title: ' + record.title);
})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
If you simply just want to display all JSON data as a string then the following code would accomplish this.
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/1',
dataType: 'json',
success: (data) => {
console.log(JSON.stringify(data));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

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)

Pnotify Post message via webservice

I'm fairly new to the programming world of Jquery.
I am trying to get data from a web service to be viewed on a notification via Pnotify.
However, on each page load the script does not view the notification bar. I really don't understand what I'm doing wrong. Hope you can help.
NOTE: the web service does retrieve the data correctly in JSON format.
UPDATED: I am able to do a msg.d but it retrieves the JSON but does not parse the information how I would like it to.
<script type="text/javascript">
$(function () {
$.ajax({ //DATA REQUEST
type: 'POST',
url: 'WebServices.asmx/getNote',
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (msg) {
$.pnotify({ //CALL PNotify
title: msg.NoteTitle,
text: msg.NoteText
});
}
});
});
</script>
I reviewed your code and if you do the following you should be able to get the data you need.
You need to be aware that object that always need to be parsed before passing the array to a view.
In your case you didn't do that.
success: function (msg) {
var Obj= eval(msg["d"]); or // $.parseJSON(msg["d"]) Method to evaluate Json
$.pnotify({ //CALL PNotify
title: Obj["0"].NotificationText, // The pared arrays
text: Obj["0"].NotificationDescription

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.

Jquery ajax autocomplete calling a method for data

$(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.

Categories

Resources