In my rails app, i need to populate 1 field with value that came in json, which was returned by clicking on link. Is there any tutorial on how to correctly use ajax to do such thing?
Here is my plan how to do this:
1.Send get request to my json appname/controller/action.json
2.parse this json on client side
3.set value of field with parsed json
I am assuming your json string is like that
[{"id":"1","name":"test1"},{"id":"2","name":"test2"},{"id":"3","name":"test3"},{"id":"4","name":"test4"},{"id":"5","name":"test5"}]
use the $.getJSON method:
$.getJSON('/appname/controller/action.json', { get_param: 'value' }, function(data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
});
Assuming data is the JSON object, you could use this inside the $.getJSON callback:
var $inputs = $('form input');
$.each(data, function(key, value) {
$inputs.filter(function() {
return key == this.name;
}).val(value);
});
second way
eg: JS fiddle
Related
I have this requirement form business to Save Searches, allowing users to use saved search data and rerun the search. I have saved the search in database as JSON object. Problem is when users select already saved search via using Select - Dropdown, the form should pre populates all the selections that were saved with search. When I am trying to alert the key value within populate function - it always show key as 0 and value as whole JSON object. What am I missing here ?
Sample of returned JSON request from database looks like: {"affects":["153","503","537"],"suspect":["101","108"],"state":[],"zip_code":[],"analysis_date_max":["",""],"last_modified_date_min":["",""]}
Here is my existing code:
//START OF PROBLEM CODE
function populate(frm, data) {
var obj = $.parseJSON(data);
//alert (data);
//alert (frm);
alert (obj);
$.each(obj, function(key, value){
alert(key + ' is ' + value);
$('[name='+key+']', frm).val(value);
});
}
// END OF PROBLEM CODE
$('#search_dataselect').on('change', function()
{
getSearchData(this.value);
});
function getSearchData(search_id) {
if (!isNaN(parseInt(search_id))) {
$.ajax({
type: "GET",
url: "/index.cgi?p=json&t=SavedSearch&search_id="+search_id,
success: function(result){
var data = result;
populate('#formSearch',data);
},
});
}
return false;
}
It appears your data is not serialized.
Try this:
success: function(result) {
var data = JSON.stringify(result);
populate('#formSearch', data);
}
An example for using JSON.stringify()
https://jsfiddle.net/3u6mrft1/
I am confused because I have two functions, one using ajax to get the data and the other getting it from a string.
function loadMenuData() {
$.ajax({
url: "./shoulders.json",
success: function(data) {
dataObj = $.parseJSON(data);
$.each(dataObj, function( key, value) {
$(document).find("#dropDownDest").append($('<option></option>').val(value.id).html(value.name));
});
}
});
}
function loadMenuDataX() {
var str = '[{"id":"A","name":"Bart"},{"id":"B", "name":"Joe"},{"id":"C", "name":"Gomer"}]';
dataObj = $.parseJSON(str);
$.each(dataObj, function( key, value) {
$(document).find("#dropDownDest").append($('<option></option>').val(value.id).html(value.name));
});
}
I created the file shoulders.json buy pasting the str between the single quotes ' into the file. If I call loadMenuX, it fills in the <select></select> correctly. If I call loadMenu, it doesn't fill anything in.
I have tried JSON.parse instead of the above and get the same behavior.
I was unable to use $("#dropDownDest") and had to use $(document).find. Why?
Hitting the DOM each loop seems to be excessive. What would be a better way to do the ajax version THAT WOULD WORK and be better?
What would be a better way to do the ajax version THAT WOULD WORK and be better?
Because you're trying to get JSON file the better way is using jQuery.getJSON(), so you will be sure that the returned result is in json format :
$.getJSON( "./shoulders.json", function( json ) {
$.each(json, function( key, value) {
$("#dropDownDest").append('<option value="+value.id+">'+value.name+'</option>');
});
});
Hope this helps.
I'm trying to use a JSON api and retrieve some data. I'm still new to it though and I can't seem to figure out which value to use. My JSON API looks something like this:
[
{"lang":"english","visual":"<span>Text</span>","weight":0.92},
{"lang":"swedish","visual":"<span>Text</span>","weight":0.22},
//etc
]
and my jQuery is:
$.getJSON(url ,function(data) {
$.each(data.lang, function(i, item) {
dataName = item["visual"];
console.log(dataName);
});
});
but nothing is being logged. How do I navigate through a JSON tree? Thanks
data.lang is undefined. lang is a property of each object in the array of objects that data holds. Simply iterate the data array, each object will contain the visual property (as well as lang);
$.getJSON(url ,function(data) {
$.each(data, function() {
var lang = this["lang"];
var dataName = this["visual"];
console.log(dataName);
});
});
I have to parse my html from and POST it to another script. When I use JSON.stringify to serialize object with parsed data, $_POST array in the receiving script is empty:
$("#addQueryForm").submit(function(event){
event.preventDefault();
result = {}
result['kindArr'];
result['factor'];
$("[rel=my-form]").each(function() {
result[$(this).attr("name")] = $(this).attr("value");
});
var form = JSON.stringify(result);
$.post("add_kind.php", form , function(data) {
alert(data);
//data shows me that $_POST array is empty
});
});
But if I write json string into the query manually, it would be correct:
$.post("add_kind.php", {"kind":"Var1","kindArr":"Var12345","factor":"Var0","synonym1":"Var1","synonym2":"Var2","synonym3":"Var3"} , function(data) {
alert(data);
//data shows me that $_POST contains posted data
});
What am I doing wrong?
P.S: stringify was excess.
Maybe serialize would be better in your situation:
var form = $(this).serialize();
$.post("add_kind.php", form, function(data) {
alert(data);
});
Bit of a vague question, but I'm unsure how I can this to work. Firebug says the Json object (array?) from my ajax request looks like:
{
"jsonResult":
"[
{\"OrderInList\":1},
{\"OrderInList\":2}
]"
}
This is retrieved through through a $.getJSON ajax request:
$.getJSON("/Json/GetOrderSelectList?parentCategoryId=" + postData, testData, function (jsonResult) {
$('#orderInList option').remove();
var map = {
"TestKey1": "TestValue1",
"TestKey2": "TestValue2"
};
$.each(jsonResult, function (key, value) {
$("#orderInList").append($("<option value=" + key + ">" + value + "</option>")
);
});
If I replace $.each(jsonResult) with $.each(map) the select list populates correctly. Otherwise my select list just says 'undefined'.
I serialize the Json in this Action in my MVC Controller:
public JsonResult GetOrderSelectList(int parentCategoryId)
{
var result = Session
.QueryOver<Category>()
.Where(x => x.Parent.Id == parentCategoryId)
.OrderBy(x => x.OrderInList).Asc
.List();
var toSerialize =
result.Select(r => new {r.OrderInList});
var jsonResult = JsonConvert.SerializeObject(toSerialize);
return Json(new
{ jsonResult,
}, JsonRequestBehavior.AllowGet);
}
So I think the problem might be the format of Json the Action is responding with? Any help appreciated!
Edit for answer
Both of the answers below helped me. I couldn't seem to strongly type the variable jsonResult so thanks #JBabey for pointing out my error in reading the json property, and suggesting function (key, value) in the $.each statement.
Thanks #Darin Dimitrov for helping sort my controller out!
Your controller action is wrong. You are manually JSON serializing inside it and then returning this as a JSON result thus ending up with a double JSON serialization. You could directly return the array and leave the JSON serialization plumbing to the ASP.NET MVC framework:
public ActionResult GetOrderSelectList(int parentCategoryId)
{
var result = Session
.QueryOver<Category>()
.Where(x => x.Parent.Id == parentCategoryId)
.OrderBy(x => x.OrderInList)
.Asc
.List();
return Json(result, JsonRequestBehavior.AllowGet);
}
and then:
$.getJSON("/Json/GetOrderSelectList?parentCategoryId=" + postData, testData, function (jsonResult) {
$('#orderInList option').remove();
$.each(jsonResult, function () {
$('#orderInList').append(
$("<option value=" + this.Id + ">" + this.Value + "</option>")
);
});
});
Notice that I am using this.Id and this.Value here. This assumes that the JSON result looks like this:
[{"Id": 1, "Value": "some value"}, {"Id": 2, "Value": "some other value"}]
You will have to adapt those property names based on your actual Category model.
You are confusing a property of your data returned by your ajax with the data itself. $.each will work fine if you correct this.
Your data returned looks like this:
{
"jsonResult": "[
{\"OrderInList\":1},
{\"OrderInList\":2}
]"
}
Which means that is the object passed to your success function. Call it data instead of jsonResult.
function (data) {
...
$.each(data.jsonResult, function (key, value) {
...
});
});
Also, your array is coming through as a string, so you may need to parse it before $.each will be able to iterate it.