jquery json to select issues - php

I'm having the below output from an ajax script:
{"DATA":[{"COUNTRYCODE":"1","DESCRIPTION":"USA","COUNTRYID":"211"}, {"COUNTRYCODE":"1","DESCRIPTION":"Canada","COUNTRYID":"37"},{"COUNTRYCODE":"1","DESCRIPTION":"Dominican Republic","COUNTRYID":"224"},
I am trying to populate a select menu with info from this JSON data:
<script type="text/javascript" charset="UTF-8">
$.getJSON(
'getcountries.php',
function(data) {
var items = [];
$('#country').append(data);
$.each(data['DATA'], function(key, val) {
$.each(val, function(key, value) {
console.log(value);
});
});
}
);
Issue with it is that the $('#country').append(data) (or append(data['DATA']) always returns error "Value does not implement interface Node."
Could anyone point out how I could get the specific JSON data I have into the select script?

.append() only accepts HTML string, DOM Element, or jQuery Object
See: http://api.jquery.com/append/
I assume this is the result you actually want.
var data = {"DATA":[{"COUNTRYCODE":"1","DESCRIPTION":"USA","COUNTRYID":"211"},{"COUNTRYCODE":"1","DESCRIPTION":"Canada","COUNTRYID":"37"},{"COUNTRYCODE":"1","DESCRIPTION":"Dominican Republic","COUNTRYID":"224"}]};
var $select = $('#country').empty();
$select.append(
data.DATA.map(function (el, i) {
return $('<option>')
.val(el.COUNTRYID)
.text(el.DESCRIPTION)
.data('DATA', el); // in case you also want to access its COUNTRYCODE
})
);
jsFiddle: http://jsfiddle.net/terryyounghk/ZshG4/

DEMO: http://jsfiddle.net/q5Q3d/
var a = {
"DATA":[
{"COUNTRYCODE":"1","DESCRIPTION":"USA","COUNTRYID":"211"},
{"COUNTRYCODE":"1","DESCRIPTION":"Canada","COUNTRYID":"37"},
{"COUNTRYCODE":"1","DESCRIPTION":"Dominican Republic","COUNTRYID":"224"}
]
}
$.each(a.DATA, function(idx, val){
var option = "<option value='" + val.COUNTRYID + "'>" + val.DESCRIPTION + "</option>";
$('select').append(option);
});

Related

Jquery .serializeArray() not processing value of dynamically appended combobox

I am trying to serialize value of form elements, where my combox is dynamicall added after user click.
I'm getting value from static combobox bt nt from dynamic combobox.
my code:
<script>
//submit data
$(function (a) {
$("form").submit(function (event) {
console.log($(this).serializeArray());
event.preventDefault();
});
});
// populate entree item to select menu
function populate() {
// only declare the variables once
var json = <?php echo $json; ?>, obj, option = ' ', i;
for (var i = 0; i < json.length; i++) {
obj = json[i];
option += '<option value="' + obj.id + '">' + $.trim(obj.title) + '</option>';
}
return option;
}
//add more select box when addmore click
$(function (b) {
var i = 0;
$("a#addmore").click(function () {
i++;
$("p#entree").append('<select name="entree' + i + '">' + populate() + '<select><br>');
});
});
</script>
i got the value when i put my form outside the table. I dnt know why table is blocking the process to get value.

state and city combobox with jquery UI plugin

I'm trying to select state and cities according to the state (category and subcategory) but is giving a problem with the jquery ui plugin to search the value.
<script type="text/javascript">
$(function(){
$('#cod_estados').change(function(){
if( $(this).val() ) {
$('#cod_cidades').hide();
$('.carregando').show();
$.getJSON('cidades.ajax.php?search=',{cod_estados: $(this).val(), ajax: 'true'}, function(j){
var options = '<option value=""></option>';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].cod_cidades + '">' + j[i].nome + '</option>';
}
$('#cod_cidades').html(options).show();
$('.carregando').hide();
});
} else {
$('#cod_cidades').html('<option value="">– Escolha um estado –</option>');
}
});
});
</script>
http://imageshack.us/g/10/99913872.jpg/
remembering that I am using other javascript code that will be is conflicting?
lap
'jQuery.noConflict () '
instead of $ and then comes the
'(function () {'
but the code ceases to function.
If you want to use jQuery in noConflict mode, you can remap $ within your shortcut domReady call.
jQuery.noConflict();
jQuery(function($) {
// Your code here, access $ as usual
});

Jquery Select list items in loop using keyup and key down

I am trying to make autosuggest in Jquery,ajax and json to search cities when user register to website.
So far I am able to get results from database.And i appended to list.but now i need to select data using up down and enter keys.
Key down event is adding class to first city. But I want to loop through all results using key up and down and add value to city textbox if user hits enter. I limit data by 5 in php so 5 results are coming in list item.
Here is my code:
$('#city').keyup(function (event) {
var input_query = $(this).val();
$.post("get_city.php", {
"query": input_query
}, function (data) {
$('#cityres').html("");
$.each(data, function (i, item) {
$('#cityresults').append("<li>" + item.city + "</li>");
});
}, "json");
//below code is for key event
var key = gtKeycode(event);
if (key == 40) {
// I am not sure i need to do this way
$('li').first().addClass('SelectedCity');
}
});
function gtKeycode(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
return code;
}
i think i have now the solution for your problem hope this will help you..!
I made a php file that echo out json encode just list this:
//PHP "action.php?action=show"
e.g $option[] = array(
'option0'=>".Choose an option",
'option1'=>'somepage1',
'option2'=>'somepage2',
'option3'=>'somepage3');
echo json_encode(array('options'=>$option));
I made up html that will be the handler of the output, then will append
<select class="myoptions">
</select> | <span class="optcap"></span>
JS
function selectedOption()
{
var myoptions = $(".myoptions");
$.ajax({
type:'GET',
url:'action.php?action=show',
dataType:'JSON',
success:function(data){
if(data.s==1){
myoptions.empty();
$.each(data.options, function(x,val){
myoptions.append("<option class='option' value='"+val.option0+"'>"+val.option0+"</option>"
+"<option class='option' value='"+val.option1+"'>"+val.option1+"</option>"
+"<option class='option' value='"+val.option2+"'>"+val.option2+"</option>"
+"<option class='option' value='"+val.option3+"'>"+val.option3+"</option>");
});
}
}
});
}
$(document).ready(function(){
selectedOption();
$(".myoptions").keyup(function(){
var option = [];
$("option.option:selected").each(function(x){
option[x] = $(this).val();
});
$(".optcap").html("["+option+"]");
});
});

jQuery Json + jQuery onChange

I am using php to talk to a mysql database then encoding the associative array with json_encode. That much I know is working, I can call the php directly and see the json result.
With jQuery I am using onChange on a dropdown to call the php function and to get the results.
I think I have problems with the jQuery and json, but I have looked through multiple posts and cannot find a good answer.
Here is the code I am using. How do I get to the json array? I have tried data['ele'], data.ele, data[0] and all return undefined.
$('#itemDD').change(function(data){
alert("Changing");
askServer(function(data){
alert("!" + data['retailListPrice']);
//spin through the data and put the results in workingQuote
});
});
function askServer(callback)
{
var selItem = $('#itemDD').val();
var strUrl = "getItemList.php?item=" + selItem + "&action=itemInfo";
alert(strUrl);
jQuery.ajax({
url:strUrl,
success:callback,
dataType: "json"
});
}
});
PHP
$sql="SELECT *
FROM items
WHERE modelNum='" . $selectedModel . "'";
$result = mysql_query($sql,$conn) or die("Error" . mysql_error());
while(($resultArray[] = mysql_fetch_assoc($result)) || array_pop($resultArray));
echo json_encode($resultArray);
You using array and mysql_fetch_assoc. So to get the data, use data[0]['rowName'] or data[0].rowName
try this (note: object/array format is diffrent in JS):
function askServer()
{
var selItem = $('#itemDD').val();
var strUrl = "getItemList.php?item=" + selItem + "&action=itemInfo";
alert(strUrl);
$.get(strUrl, function(data){
alert(data.retailListPrice);
});
}
Inside change event just call the askServer() function and declare it outside of change event, like
$('#itemDD').change(function(data){
//...
askServer();
});
and your askServer() function
function askServer()
{
var selItem = $('#itemDD').val();
var strUrl = "getItemList.php?item=" + selItem + "&action=itemInfo";
$.get(strUrl, function(data){
$.parseJSON(data);
alert(data.retailListPrice);
});
}

AutoSuggest from JSON with Link

Hy!
I want to make a autosuggest from my php file that returns a Json Object.
I parse it in js to get a link with the right id (look at the json)
JSON from search_new.php:
{"Data":{"Recipes":{"Recipe_5":{"ID":"5","TITLE":"Spaghetti Bolognese"},"Recipe_7":{"ID":"7","TITLE":"Wurstel"},"Recipe_9":{"ID":"9","TITLE":"Schnitzel"},"Recipe_10":{"ID":"10","TITLE":null},"Recipe_19":{"ID":"19","TITLE":null},"Recipe_20":{"ID":"20","TITLE":"Hundefutter"},"Recipe_26":{"ID":"26","TITLE":"Apfelstrudel"},"Recipe_37":{"ID":"37","TITLE":null},"Recipe_38":{"ID":"38","TITLE":"AENDERUNG"},"Recipe_39":{"ID":"39","TITLE":null},"Recipe_40":{"ID":"40","TITLE":"Schnitzel"},"Recipe_42":{"ID":"42","TITLE":"Release-Test"},"Recipe_43":{"ID":"43","TITLE":"Wurstel2"}}},"Message":null,"Code":200}
Calling in JS:
<script type="text/javascript">
$(function() {
var allRecipes = (<?php include("php/search_new.php"); ?>).Data.Recipes;
var recipeNames = [];
for(var i in allRecipes) {
recipeNames.push("" + allRecipes[i].TITLE) + "");
}
var arr = new Array();
for(var k in recipeNames){
arr.push(" " + recipeNames[k]);
}
$("#searchrecipes").autocomplete({
minLength: 3,
source: arr
});
});
</script>
Firebug Error:
missing ; before statement recipeNames.push("" +
allRecipes[i].TITLE) + "");
Before i had recipeNames.push("allRecipes[i].TITLE)"); everything worked well
Please help.
Yes I see your problem.
Here is the code you need:
$(function() {
var data = (<?php echo file_get_contents("php/search_new.php"); ?>).Data.Recipes;
var source = [];
for (var i in data) {
source.push({"href": "/php/get_recipe_byID.php?id=" + data[i].ID, "label": data[i].TITLE});
}
$("#searchrecipes").autocomplete({
minLength: 3,
source: source,
select: function(event, ui) {
window.location.href = ui.item.href;
}
});
});
You can find an example here: http://jsfiddle.net/dFApV/
there is for sure an extra bracket right to allRecipes[i].TITLE that must be erased! :D
I would say, you could achieve the same result, but with a much nicer solution by using the .result method.
Tell me what do you think about it!
JQuery API Autocomplete Result

Categories