Populate textbox with ajax call to server - json

I have first and last name text boxes, last name on blur triggers an ajax call to get additional data to fill in other textboxes. The call is made and I can see in the Chrome dev tool (network tab) that a json string is coming back with all the data, but I can't figure out how to populate the text fields.
ajax function:
$(function() {
$("#LastName").on('blur', function () {
var first = $("#FirstName").val();
var last = $("#LastName").val();
$.ajax({
url: '#Url.Action("SearchEmployee", "Employee")',
type: "GET",
datatype: 'json',
data: { 'firstName': first, 'lastName': last },
success: function (data) {
alert(data.ManagerFirst);
$("#ManagerFirst").val(data.ManagerFirst);
$("#ManagerLast").val(data.ManagerLast);
},
error: function () { alert("Huh? What? What did you need?.") }
});
})
})
returns something like this:
{"EmployeeId":0,"FirstName":"Bob","LastName":"Smith","EmailAddress":null,"ManagerEmail":"Boss.Man#work.org","ManagerId":null,"ManagerFirst":"Boss","ManagerLast":"Man"}
The 'alert' shows "undefined".

You may just have a typo. Try changing "datatype" to "dataType"

You are trying to alert a data member of the response string, which does not exist. Instead, you should try to convert the string to object, like this:
$(function() {
$("#LastName").on('blur', function () {
var first = $("#FirstName").val();
var last = $("#LastName").val();
$.ajax({
url: '#Url.Action("SearchEmployee", "Employee")',
type: "GET",
datatype: 'json',
data: { 'firstName': first, 'lastName': last },
success: function (data) {
//converting it to object, since further rows expect this
data = $.parseJSON(data);
alert(data.ManagerFirst);
$("#ManagerFirst").val(data.ManagerFirst);
$("#ManagerLast").val(data.ManagerLast);
},
error: function () { alert("Huh? What? What did you need?.") }
});
})
})
EDIT:
As Bryan Lewis pointed out, it was a typo. This has led to the behavior about which I have written my answer.

Turns out the problem was the server was returning an array of employee objects, so had to access it like:
data[0].ManagerFirst ... etc.
There was no way to tell that from the data I posted, so my apologies.
fyi, once I added that fix, I changed the the dataType param back to 'datatype' and it still worked fine.

Related

Trying to pass list of ids to the M-V-C Action through Ajax Function

I am trying to get and store the Ids of all the selected check-boxes in the JavaScript object. And then passing this object as a data to my JSON Action. I am able to successfully get the Ids of all the selected check-boxes, but when I am passing this object to my action I am getting null. Following is my code:
$("#btnSave").on('click', function () {
var selected = [];
$('input:checked').each(function () {
selected.push($(this).attr('id'));
});
$.ajax({
url: '#Url.Action("SaveRecords", "Users")',
data: { ids: selected },
cache: false,
type: "GET",
success: function (data) {}
});
});
My Action:
public JsonResult SaveRecords(List<int> ids) //Here I'm getting Null.
{
return Json(true, JsonRequestBehavior.AllowGet);
}
As suggested in the comments, since you are saving data POST is more appropriate than GET. Also, I think you will save yourself some trouble by using JSON as input - you're already using it as output format from the action. This means your AJAX call will look like this:
$.ajax({
type: 'POST',
url: '#Url.Action("SaveRecords", "Users")',
contentType: 'application/json',
data: JSON.stringify(selected),
success: function (data) { /* ... */ }
});
When I say "save yourself trouble by using JSON as input" I mean that model binding collections and complex types in MVC can be a bit tricky when sending data as a form post - google it and you'll see that there are several implementation characteristics to be aware of. In my experience, using JSON for structured data posted with AJAX just works much more like what you would expect.

AJAX/JSON MVC method not being called

The MVC controller method is not being called with the following code and the issue isn't clear. $("#screeners").val() returns a list of strings:
<script>
$(document).ready(function () {
$("#submitScreeners").click(function () {
var selected = $("#screeners").val();
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Applicant/PassScreeners',
data: "selected=" + JSON.stringify(selected),
success: function () {
$('#result').html('"PassScreeners()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
});
</script>
Method in controller:
public void PassScreeners(List<string> selected)
{
Session["SelectedApplicants"] = selected.Select(e => Int32.Parse(e.ToString())).ToList();
}
If I understand you correctly, the "selected" parameter is being passed in as a null value. I believe this is because you are using an incorrect data format. You tell the server to expect JSON formatted data, but then pass it something more akin to a form value with '='.
Try removing the "selected=" bit from your data line and just pass the stringified list.
If that doesn't work, check the trace and post it. If the string you are posting is just comma separated or something it needs to be an array in order for the POST to work correctly.
Apologies if I've misunderstood.

Select2 ajax is correctly calling webservice, but then doing nothing after

I'm setting up a select2 with the following JavaScript
$j("#" + name).select2({
placeholder: "",
width:"300px",
minimumInputLength: 3,
ajax: {
url: "/MyService.asmx/ServiceMethod",
dataType: 'json',
data: function (term) {
return {
q: term // search term
};
},
results: function (data) {
alert('results');
return {results: data};
},
success: function() {
alert('success');
},
error: function () {
alert('error');
},
},
});
The method I'm calling is the following:
<WebMethod(enableSession:=True)>
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Function ServiceMethod(q as String) As String
Dim temp As String = "[{'id':'35','text':'Drew'}]"
Return temp
End Function
I also have <ScriptService()> around the class. The enableSession is there because eventually I'm going to be running a lot of logic in the service that requires it, but for now I'm just trying to return a simple string with JSON.
I've put a breakpoint in the webservice, and I know it is being called. I know it is returning the JSON. I also know that the select2 expects "id" and "text" in the JSON return
My problem is the following: after I input 3 characters, the data function calls (I put an alert in it), the webservice breakpoint is hit, but none of the results, success, or error events fire afterwards. The select2 just spins and nothing ever happens. No javascript errors are entered in the console, and I'm at a loss about even where to look for information as to why the ajax isn't handling the returned value from the service.
Can anyone point me in the direction of at least where to look to see why this isn't working?
So I fixed this myself after getting a hint to look at the network log. The service was returning correctly, but it was returning XML, not JSON. I had to make 2 modifications and everything worked.
My working ajax:
ajax: {
url: "/MyService.asmx/ServiceMethod",
type: 'POST',
params: {
contentType: 'application/json; charset=utf-8'
},
dataType: 'json',
data: function (term, page) {
return JSON.stringify({ q: term, page_limit: 10 });
},
results: function (data) {
return {results: data};
},
},
The important changes were the type, putting the contentType in the params wrapper, and JSON.stringify-ing the data. I'm going to change what's passed and how its passed, but things are at least communicating now. Hope this helps anyone else who was looking for a similar solution.

Jquery Autocomplete with json and using parameters

I am trying to do an autocomplete input field. Everytime a user type a letter in that field, the value of the field is sent to the server and the server answer with words that match.
var acOptions = {
source:function (request, response) {
$.ajax({
url: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw",
type: "GET", dataType: "json",
data: { expr: request.term},
success: function (data) {
response($.map(data, function (item) {
return item.value;
}))
}
})
},
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);
This is an example of data from the server:
[{"value":"Greater"},{"value":"great"},{"value":"greatly"},{"value":"Greater-Axe"}]
The previous code do the right request to the server (and the server answer right) but it does not display anything in the text field.
I tried to do the autocomplete without an explicit ajax object but then I couldn't send the current value of the field (parameter "expr" of the request) to the server:
var acOptions = {
source: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw&expr=",
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);
Thank you for your help!
You can use jQuery to pull the value of your field to add it to URL parameter string.
var acOptions = {
source: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw&expr=" + $('#ID_OF_YOUR_TEXTBOX').val(),
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);

How can I fetch json values and display in html

I have been killing myself over this for some time. I am looking to use the causes API to fetch some data from some of our causes we have active and display that via html.
I have created a facebook app and i'm trying to use jquery ajax. This is what I have:
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Fapi.causes.com%2Fbeneficiaries%2F1239.xml'&format=json&callback=cbfunc",
dataType: "json",
success: function(cbfunc) {
$(cbfunc).find('count').each(function(){
var total = $(this).find('total-raised').text();
$(this).html('<p>'+total+'</p>').appendTo('#listTotalDollor');
});
}
});
});
Problem is that I am not getting anything to display. Is this a crossdomain issue or is there something I missed.
Thanks!
Updated code:
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Fapi.causes.com%2Fbeneficiaries%2F1239.json%22&format=json",
dataType: "json",
success: function(data) {
$.each(data.query.results, function(i, key) {
var total = key['total_raised'];
$("#listTotalDollar").html('<span>' + total + '</span>');
});
}
});
});
One last question to ask:
If I wanted to format one of the returning values as currency.
In my updated code I get a return of 5000 I would like it to read $5,000. Is there a good tut you can point me to?
You are mixing DOM and JSON access in you cbfunc. Assuming, that you want that total-raised number for each of the elements returned by that query, you can simple request JSON (as you do) and iterate over it accordingly.
$.ajax({
// !wrapped only for readability!
url: "http://query.yahooapis.com/v1/public/yql?
q=select%20*%20from%20xml%20where%20url%3D'\
http%3A%2F%2Fapi.causes.com%2Fbeneficiaries%2F1239.xml'\
&format=json",
dataType: "json",
success: function(data) {
// `data` is actually a json structure (as requested)
// if you want to see it as a whole, just use
// console.log(data);
// now iterate over the json structure
// (see also: http://stackoverflow.com/q/1078118/89391)
// and set your target dom element as you like
// (this is just a dummy ...)
$.each(data.query.results, function(i, key) {
var total = key['total-raised'].content;
$("target").html('<p>' + total + '</p>');
});
}
});
Here's the code I used for debugging: https://gist.github.com/850148.
For reference, here's a sketch of the response:
Object
query: Object
count: 1
created: "2011-03-01T23:24:18Z"
lang: "en-US"
results: Object
beneficiary: Object
id: Object
name: "INTERNATIONAL FELLOWSHIP OF CHRISTIANS & JEWS"
recent-facebook-donors: "time1297716630facebook_id0nameRobert \
Alan Schoonoveramount200time1297372019facebook_id0nameCurtis En…"
total-causes: Object
total-donors: Object
total-members: Object
total-raised: Object
__proto__: Object
__proto__: Object
__proto__: Object
__proto__: Object