Issue loading data into a dropdown via ajax - javascript

Encountering an issue loading a dropdown dynamically using JQuery AJAX.
The php is returning a valid JSON response. But when I attempt to load the data, I'm getting back either undefined, [object Object] or a single option with all my values comma separated. Nothing I've tried yields the correct answer.
This is the AJAX code block:
$.ajax({
type: "GET",
url:"data/getdata_codes.php",
dataType: "json",
success: function (data) {
alert("Success section");
alert(data);
$.each(data,function(key,value) <--Fails here
{
alert(key);
alert(value);
var option="<option value="+key+">"+value+"</option>";
alert(option);
$(option).appendTo('#myList');
});
},
error: function(xhr) {
alert("An error occured: "+ xhr.status + " " + xhr.statusText);
}
});
This is the JSON which is returned from the PHP, it validates.
{"data":[[{"0":"-1","CODE":"-1"}],
[{"0":"0","CODE":"0"}],
[{"0":"12","CODE":"12"}],
[{"0":"213","CODE":"213"}],
[{"0":"357","CODE":"357"}],
[{"0":"364","CODE":"364"}],
[{"0":"501","CODE":"501"}],
[{"0":"661","CODE":"661"}]]}

First of all your array is filled with arrays with 1 object. That makes it overly complicated.
Try something like this:
$(data.data).each(function(index, element) <- I guess your data variable also has a data attribute?
{
var array = element;
var objectInArray = array[0];
var key = objectInArray.0;
var value = objectInArray.CODE;
alert(key);
alert(value);
var option="<option value="+key+">"+value+"</option>";
alert(option);
$(option).appendTo('#myList');
});

Related

How to parse this JSON result in Javascript?

I am trying to read this JSON that I get as a result of an AJAX get function. I seem to successfully get the data since when I console.log(result) I get the data in the console but I cannot seem to handle this result as a JSON object.
var isbnURL = "https://openlibrary.org/api/books?jscmd=data&format=json&bibkeys=ISBN:9780739332122"
$.ajax({
type: 'GET',
url: isbnURL,
dataType: 'json',
success: function(result){
console.log(result);
console.log(result.length);
},
error: function(message){
console.log(message);
}
});
I am expecting that console.log(result.length); returns the length and not undefined in the console.
The result of this is an object, not an array. Maybe you want to get, for example, the list of links inside the object. In this case you can do that:
result["ISBN:9780739332122"].links.length
var isbnURL = "https://openlibrary.org/api/books?jscmd=data&format=json&bibkeys=ISBN:9780739332122";
var isbnURL = "https://openlibrary.org/api/books?jscmd=data&format=json&bibkeys=ISBN:9780739332122";
$.getJSON({
url: isbnURL,
success: function(data) {
$.each(data, function(index, value) {
console.log("Small cover: " + value.cover.small);
console.log("Title: " + value.title)
});
}
});
This works. getJSON obtains the JSON and parses it, then the each function loops through each book.

JQUERY - JSON Result assign it to pre populate form fields on when select is selected

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/

GeoJson "Not Well Formed" message in console, and appears undefined

Ive included the very end of my script below, where I'm trying to put a JSON file into a website using Ajax callback function. When I inspect the page, I'm seeing that the JSON file is not well formed and I can't seem to find an answer. The webpage is also just showing that the JSON file is "undefined".
function debugCallback(response){
var mydata;
$("#mydiv").append('GeoJSON data: ' + JSON.stringify(mydata));
};
function debugAjax(){
var mydata;
$.ajax("data/MegaCities.GeoJSON", {
dataType: "json",
success: function(response){
//mydata = response;
debugCallback(mydata);
}
});
$("#mydiv").append('<br>GeoJSON data:<br>' + JSON.stringify(mydata));
};
//$("#mydiv").append('GeoJSON data: ' + JSON.stringify(mydata));
if(typeof mydata === 'undefined') {
console.log("undefined data")
} else {
console.log("not undefined")
}
$(document).ready(debugAjax());
Avoid defining several functions and try just using this:
$(document).ready(function(){
$.ajax("data/MegaCities.GeoJSON", {
dataType: "json",
success: function(response){
$("#mydiv").append('<br>GeoJSON data:<br>' + JSON.stringify(response));
}
});
});
Note that after we get response/data from ajax call, we proceed formatting as JSON.
You are using var mydata and it is not defined so it is showing correct message undefined when you are passing it as value.
You should probably modify your code like this.
$(document).ready(function(){
$.ajax({
url: "data/MegaCities.GeoJSON",
method: 'GET' ,
aysnc: false,
success: function(response){
$("#mydiv").append('GeoJSON data:' +response);
}
});
});

Return String From XHRGet

I'm creating a tree using Dojo and two seperate sets of data. One set of data makes up the main tree structure. The second set of data is dependent on a value from the first set. I'm using xhrGet and Dojo 1.7.3 to get the data.
Once the second set of data has been returned, I'm looking at the values of the JSON to determine a value of a variable, that's then passed into the tree. The variable displays a "!" if an "alert" value is present in the JSON returned and blank if there isn't.
var theAlert = dojo.xhrGet({
url: proxy + serviceurl + targetId,
handleAs: 'json',
load: function(data){
if(typeof data.alerts[0] != 'undefined'){
var hello = "!";
return hello;
}
else{
console.log("There is nothing there");
},
error: function(error){
console.log(error)
}
});
The problem I'm having is that when I write "theAlert" variable where I need to, it appears as "[object Object]" and not as "!".
I feel like I'm doing something wrong, but I can't figure out what.
I have already tried using theAlert.valueOf(); to no success. Help?
The data is received correctly as well, I can view it via console log.
dojo.xhrGet() returns a Deferred - http://dojotoolkit.org/reference-guide/1.9/dojo/Deferred.html
You need to do something like:
var deferred = dojo.xhrGet({
url: proxy + serviceurl + targetId,
handleAs: 'json'
});
deferred.then(
function(data){
if(typeof data.alerts[0] != 'undefined'){
processAlert("!");
} else{
console.log("There is nothing there");
}
},
function(error){
console.log(error)
}
);
function processAlert(a) {
alert(a);
}
Look at the docs.
You need to return data, not hello.

Getting typeError:e is undefined in firebug while running a script

I am not able to figure out what is wrong with my code.I am getting data from post as an array and I am then displaying that data in box.
function worker() {
var a = $("#BeeperBox");
var delay =2000;
$.ajax({
url: '/index.php/admin/getLatest',
success: function(data) {
$.each(data.upda,function(i, v){
var out = v.name + v.mob ;
$('span.blueName').html(out);
$("#BeeperBox").show();
timerId = setTimeout(function () {
a.hide();
}, delay);
});
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 50000);
}
});
}
When i run it firebug shows error: TypeError: e is undefined.
since your sending the response as JSON.. its better to specify your dataType as JSON (though If none is specified, jQuery will try to infer it based on the MIME type of the response ) so that you don't have to parse it manaully..i think the problem here is you havn't parsed the json that you got as response
try this
$.ajax({
url: '/index.php/admin/getLatest',
dataType: 'json',
success: function(data) {
$.each(data.upda,function(i, v){
var out = v.name + v.mob ;
......
},
Check if data.upda is undefined, I think the problem is that that variable doesn't exist and you're trying to iterate over a undefined element.

Categories