Populate select list from JSON - php

I've been looking around for a solution to what appears to be a simple problem, but am unable to find the solution...any guidance would be appreciated.
I am attempting to build a select box using JSON object retrieved from a PHP script. The PHP script (versions.php) is running a query against a database table; code is as follows:
$posts = array();
if(mssql_num_rows($result)) {
while($post = mssql_fetch_assoc($result)) {
$posts[] = $post;
}
}
header('Content-type: application/json');
echo json_encode($posts);
...and returns the following json structure:
[{"version":"3.3.0"},{"version":"1.5.0"}]
The PHP file is being called from a central JS file, which is structured as follows:
jQuery(function($){
$.getJSON('versions.php', function(data) {
var select = $('#release-list');
$.each(data, function(key, val){
var option = $('<option/>');
option.attr('value', val)
.html(data)
.appendTo(select);
});
});
});
Looking at firebug, I see lists of objects, but not the values in the array. I guess this is related to the code in the javascript file above - just not sure how to access the values from the json object.
Thanks in advance.

You're almost there. Based on your JSON structure, It should look something like this:
jQuery(function($){
$.getJSON('versions.php', function(data) {
var select = $('#release-list');
$.each(data, function(key, val){
$('<option/>').attr('value', val.version)
.html('version ' + val.version)
.appendTo(select);
});
});
});

Related

Wordpress ajax call is returing the html of the page

I am getting the data from the sql table and storing the results inside the associative array after that i have encoded into json but the problem is that it is returning the html of the page along with the results
this is my php code
<?php
add_action('wp_ajax_nopriv_my_loadmore','my_loadmore');
add_action('wp_ajax_my_loadmore','my_loadmore');
function my_loadmore(){
global $wpdb;
$table_name="wpnn_tweets";
$paged=$_POST['page'];
$page=$paged*10;
$results = $wpdb->get_results("SELECT * FROM $table_name LIMIT 1 OFFSET $page");
$arr = array();
foreach($results as $row){
$arr['userScreen']=$row->userScreen;
$arr['userName']=$row->userName;
$arr['tweetCreated']=$row->tweetCreated;
$arr['tweetText']=$row->tweetText;
$arr['tweetRetweetCt']=$row->tweetRetweetCt;
$arr['tweetFavoriteCt']=$row->tweetFavoriteCt;
}
echo json_encode($arr);
wp_die();
}
?>
this is how i am retrieving the json in the front end
$ = jQuery;
function scroller() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 200) {
$(this).off("scroll.ajax");
var page=parseInt($(this).data('page'));
var ajaxurl=$(this).data('url');
$.ajax({
url:ajaxurl,
type:"POST",
data:{
page:page,
action:"my_loadmore"
},
error:function(response){
console.log("error");
},
success:function(data){
for(i = 0; i < data.length; i++) {
console.log(data[i]);
}
}
});
}
}
$(window).on("scroll.ajax", scroller);
var ajaxurl = $(this).data('url');
This returns null unless you explicitly set it in your HTML. The easiest solution is to replace it with something like the following.
var ajaxurl = 'my-cool-endpoint';
This was not the solution to this particular problem, but I feel like it's a good thing to check for others coming to this page with the same problem. Replace wp_die() with die(). See the documentation for more details, but here is the relevant line.
A call to this function complements the die() PHP function. The difference is that HTML will be displayed to the user in the case of a typical web request.

jQuery Array to PHP

I have a little bit of a problem, I have a JavaScript with jQuery where I work with an Array I got from PHP, in the script I add some data to two new arrays and here comes my problem, how can I work with those two arrays in my PHP file? I need to save the data from the two new arrays in a database. In the PHP I have a form where I enter some data about a User. Does someone knows a easy way to send my data back to the PHP?
Some information about the script: I have a table with the names of schools, and a checkbox with the id of the school as a value. when i check or uncheck one of the checkboxes the script checks if it is a school already saved in the database for this specific user or if it's a new user.
<script>
var schools = [];
var oldschools = [];
var uncheckedschools = [];
oldschools = <?php echo json_encode($oldschoolids); ?>;
$(".checkbox").change(function() {
if(this.checked) {
var additem = $(this).val();
for (var i=0; i<oldschools.length; i++) {
if (additem == oldschools[i]) {
uncheckedschools = jQuery.grep(uncheckedschools, function(value) {
return value != additem;
});
}
}
schools.push(additem);
} else {
var removeitem = $(this).val();
for (var i=0; i<oldschools.length; i++) {
if (removeitem == oldschools[i]) {
uncheckedschools.push(removeitem);
}
}
schools = jQuery.grep(schools, function(value) {
return value != removeitem;
});
}
});
</script>
I hope someone can help me with this problem!
You'll need to use AJAX to send your updates back to your server. Using jQuery's ajax() method, it would looks something like this:
$.ajax({
url: 'path/to/serverside/file.php',
dataType: 'json',
data: {schools: schools},
success: function(dataFromServer) {
//after the save is successful, you can do something here
},
error: function(dataFromServer) {
//if there was an error handle it here
}
});
EDIT: As mentioned by a few commentors, you'll need to use json_decode on the server-side to decode the JSON Object you're sending back: http://php.net/manual/en/function.json-decode.php

jquery json to select issues

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);
});

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);
});
}

autocomplete source from php file

I'm quite newbie in JSON, just started it the last night, I'm very close to the deadline of a project, I used xml, and tried now to switch to json.
I started with the simplest representation of a json object, let me go to code:
PHP Code:
<?php
//phpPage.php
$json = array();
$json[]='Jquery';
$json[]='AJAX';
$json[]='JSON';
//for example
echo json_encode($json);
?>
js code:
$(document).ready(function(){
$.post('phpPage.php', { /*no matter*/ }, showResult, "text");
});
function showResult(res){
var obj = JSON.parse(res);
$("input#autocomplete").autocomplete({
source: function() {
var rows = new Array();
for(var i=0; i<3; i++){//Assume that I know array size, skip it
//what to do here?
}
return rows;
}
});
}
I don't know how to convert the sent object to an array ready to be used in the 'source' of the autocomplete.
Thanks for your time,
Regards!
The solution:
<script type="text/javascript">
$(document).ready(function(){
$.post('phpPage.php', { /**/ }, showResult, "text");
});
function showResult(res){
var obj = JSON.parse(res);
$("input#autocomplete").autocomplete({
source: obj
});
}
</script>
use jquery's getJSON() function (if you can GET).
OR
$.post('phpPage.php', { /*no matter*/ }, showResult, "json");
function showResult(data){
$("input#autocomplete").autocomplete({
source: data;
});
}
Well there are a couple things that I would change and a couple things you are doing right. First your post request can encode the json all by it's self. Take a look at your line
$.post('phpPage.php', { /*no matter*/ }, showResult, "text");
and change it to
$.post('phpPage.php', { /*no matter*/ }, showResult, "json");
jQuery will parse the json and turn it into an object.
Now for an explanation, when you use encode_json() with php it does not create a json object all php does is format at an array like an object for JS to then turn into json.
What you are doing with JSON.parse is taking the string that php returns that will probably look like this
{"1":"jquery", "2":"AJAX","3":"JSON"}
with your example, and turning it into an object in JS.
Now for the important part. Objects in JS can be treated as an associative array, this means that they are array where the key is the index. So manipulation of an object or traversing an object can be very easy.
So you have the function showResult(res) if you want to traverse the json object and print results to the screen its pretty darn easy. First I want to change your for loop to a for...in then we just use your json object like an array
function showResult(res){
var obj = JSON.parse(res);
$("input#autocomplete").autocomplete({
source: function() {
var rows = new Array();
for (x in obj){//Assume that I know array size, skip it
$('body').append(obj[x]+'<br>');
}
return rows;
}
});
}
The only thing I changed in your code is
for (x in obj){//Assume that I know array size, skip it
$('body').append(obj[x]+'<br>');
}
This will traverse the array and plug in the correct key where x is to use every single value of the json object and add it to the body on a new line.
Now to use it with autocomplete is what ever those plugin docs say. I hope this helps you a little.

Categories