I am implementing a genetic algorithm. I take the classes from here,
but I don't understand how to give input to these classes. I have dynamic inputs. I have three inputs that need to be optimized. If any one knows kindly provide me the guidelines.
Here is the code
<?php
class GA {
var $population; //Objects array (same classes)
var $fitness_function; //The fitness function name (string)
var $crossover_functions; //The crossover function name (string) or array
var $mutation_function; //The mutation function name (string)
var $mutation_rate; //Mutation rate per child (%)
var $generations; //Number of generations
var $num_couples; //Number of couples for each generation
var $death_rate; //Number of killed objects for each generation
function crossover($parent1,$parent2,$cross_functions)
{
$class = get_class($parent1);
if ($class != get_class($parent2))
return false;
if (!is_array($cross_functions)) {
$cross_function = $cross_functions;
$cross_functions = array();
}
$child = new $class();
$properties = get_object_vars($parent1);
foreach ($properties as $propertie => $value)
{
if ($cross_function) $cross_functions[$propertie] = $cross_function;
if (function_exists($cross_functions[$propertie]))
$child->$propertie = $cross_functions[$propertie]($parent1->$propertie,$parent2->$propertie);
}
return $child;
}
function mutate(&$object,$mutation_function) {
$properties = get_object_vars($object);
foreach ($properties as $propertie => $value) {
$object->$propertie = $mutation_function($object->$propertie);
}
}
function fitness($object,$fitness_function) {
return $fitness_function($object);
}
//PRIVATE
function best($a, $b) {
if ($a[1] == $b[1]) return 0;
return ($a[1] < $b[1]) ? 1 : -1;
}
function select($objects,$fitness_function,$n=2) {
foreach ($objects as $object) {
$selection[] = array($object,$fitness_function($object));
}
usort($selection,array("GA", "best"));
$selection = array_slice($selection,0,$n);
foreach ($selection as $selected) {
$winners[] = $selected[0];
}
return $winners;
}
//PRIVATE
function worst($a, $b) {
if ($a[1] == $b[1]) return 0;
return ($a[1] < $b[1]) ? -1 : 1;
}
function kill(&$objects,$fitness_function,$n=2) {
foreach ($objects as $object) {
$selection[] = array($object,$fitness_function($object));
}
usort($selection,array("GA", "worst"));
$selection = array_slice($selection,0,count($selection)-$n);
$objects = array();
foreach ($selection as $selected) {
$objects[] = $selected[0];
}
}
//PRIVATE
function mass_crossover($objects,$cross_functions) {
foreach ($objects as $object) {
if (!$obj1) $obj1 = $object;
else {
$children[] = $this->crossover($obj1,$object,$this->crossover_functions);
$obj1 = null;
}
}
return $children;
}
//PRIVATE
function mass_mutation(&$objects) {
foreach($objects as $key => $object) {
if (rand(1,100) <= $this->mutation_rate) $this->mutate($objects[$key],$this->mutation_function);
}
}
function evolve() {
for ($i=0;$i<$this->generations;$i++) {
$couples = $this->select($this->population,$this->fitness_function,2*min($this->num_couples,floor(count($this->population)/2)));
$children = $this->mass_crossover($couples,$this->crossover_functions);
$this->mass_mutation($children);
$this->population = array_merge($this->population,$children);
$this->kill($this->population,$this->fitness_function,min($this->death_rate,count($this->population)-2));
}
}
}
?>
here gaexample2.php
<?php
require_once('ga.php');
class Human {
var $strength;
var $dexterity;
var $resistance;
var $intelligence;
function Human($strength=0,$dexterity=0,$resistance=0,$intelligence=0)
{
$this->strength = $strength;
$this->dexterity = $dexterity;
$this->resistance = $resistance;
$this->intelligence = $intelligence;
}
}
function debug($x) {
echo "<pre style='border: 1px solid black'>";
print_r($x);
echo '</pre>';
}
//This will be the mutation function. Just increments the property.
function inc($x) {
return $x+1;
}
//This will be the crossover function. Is just the average of all properties.
function avg($a,$b) {
return round(($a+$b)/2);
}
//This will be the fitness function. Is just the sum of all properties.
function total($obj) {
return $obj->strength + $obj->dexterity + $obj->resistance + $obj->intelligence;
}
$adam = new Human(4,2,3,1);
$eve = new Human(1,4,2,3);
$ga = new GA();
$ga->population = array($adam,$eve);
debug($ga->population);
$ga->fitness_function = 'total'; //Uses the 'total' function as fitness function
$ga->num_couples = 1; //4 couples per generation (when possible)
$ga->death_rate = 0; //No kills per generation
$ga->generations = 100; //Executes 100 generations
$ga->crossover_functions = 'avg'; //Uses the 'avg' function as crossover function
$ga->mutation_function = 'inc'; //Uses the 'inc' function as mutation function
$ga->mutation_rate = 10; //10% mutation rate
$ga->evolve(); //Run
debug($ga->population);
debug(GA::select($ga->population,'total',1)); //The best
?>
can someone help in showing the sepearte outputs of every step
The way to send values to a class is using the constructor of the class in which you can retrieve the parameters and assign it to the class variables.
Read more about constructors here.
It would be something like:
class GA {
var $population; //Objects array (same classes)
var $fitness_function; //The fitness function name (string)
var $crossover_functions; //The crossover function name (string) or array
var $mutation_function; //The mutation function name (string)
var $mutation_rate; //Mutation rate per child (%)
var $generations; //Number of generations
var $num_couples; //Number of couples for each generation
var $death_rate; //Number of killed objects for each generation
//$params would be the array of params to receive
function __construct($params) {
$this->population = $params['population'];
$this->fitness_function = $params['fitness_function'];
...
}
...
}
Related
I'm working on a function to recursively remove arrays and objects recursively. The problem is that certain recursions may be inside private properties of objects.
below is what I tried as well as the entries I tried to use.
this is my entrie
class TestOBJ{
private $fooClosure = null;
public $bar = 5;
private $myPrivateRecursion = null;
private $aimArrayAndContainsRecursion = [];
public function __construct()
{
$this->fooClosure = function(){
echo 'pretty closure';
};
}
public function setMyPrivateRecursion(&$obj){
$this->myPrivateRecursion = &$obj;
}
public function setObjInsideArray(&$obj){
$this->aimArrayAndContainsRecursion[] = &$obj;
}
}
$std = new stdClass();
$std->std = 'any str';
$std->obj = new stdClass();
$std->obj->other = &$std;
$obj = new TestOBJ();
$obj->bar = new TestOBJ();
$obj->bar->bar = 'hey brow, please works';
$obj->bar->setMyPrivateRecursion($std);
my entrie is var $obj
and this is my function / solution
function makeRecursionStack($vector, &$stack = [], $from = null)
{
if ($vector) {
if (is_object($vector) && !in_array($vector, $stack, true) && !is_callable($vector)) {
$stack[] = &$vector;
if (get_class($vector) === 'stdClass') {
foreach ($vector as $key => $value) {
if (in_array($vector->{$key}, $stack, true)) {
$vector->{$key} = null;
} else {
$vector->{$key} = $this->makeRecursionStack($vector->{$key}, $stack, $key);
}
}
return $vector;
} else {
$object = new \ReflectionObject($vector);
$reflection = new \ReflectionClass($vector);
$properties = $reflection->getProperties();
if ($properties) {
foreach ($properties as $property) {
$property = $object->getProperty($property->getName());
$property->setAccessible(true);
if (!is_callable($property->getValue($vector))) {
$private = false;
if ($property->isPrivate()) {
$property->setAccessible(true);
$private = true;
}
if (in_array($property->getValue($vector), $stack, true)) {
$property->setValue($vector, null);
} else {
//if($property->getName() === 'myPrivateRecursion' && $from === 'bar'){
//$get = $property->getValue($vector);
//$set = $this->makeRecursionStack($get, $stack, $property->getName());
//$property->setValue($vector, $set);
//pre_clear_buffer_die($property->getValue($vector));
//}
$property->setValue($vector, $this->makeRecursionStack($property->getValue($vector), $stack, $property->getName()));
}
if ($private) {
$property->setAccessible(false);
}
}
}
}
return $vector;
}
} else if (is_array($vector)) {
$nvector = [];
foreach ($vector as $key => $value) {
$nvector[$key] = $this->makeRecursionStack($value, $stack, $key);
}
return $nvector;
} else {
if (is_object($vector) && !is_callable($vector)) {
return null;
}
}
}
return $vector;
}
The place where I have comments is where I noticed the problem. if the If is not commented there $get would receive a stdClass that has recursion and this works perfectly and $set would receive the stdClass without recursion. In that order.
$get =
$set =
After this lines
$property->setValue($vector, $set);
pre_clear_buffer_die($property->getValue($vector));
i obtain this
I try to put other value like an bool or null inside property and after set the $set but it's not works.
P.S: pre_clear_buffer_die kill php buffer, init other buffer and show var inside a <pre> after exit from script. Is an debugger function.
Actually after fetching the data from the Database, i want to create a new Object and insert this object to the array but when i check the array it shows the NULL value
here is my code:
<?php
$query = "sql query";
$filter_Result = mysqli_query($con, $query);
$newOrders = Array();
while ($row = mysqli_fetch_array($filter_Result)) {
$order;
$orderId = $row['order_id']; //fetch row id
$temp = check_id($newOrders, $orderId);
if ($temp != null) {
$order = $temp;
} else {
echo " <br>";
$order = new Order($row['order_id'], $row['status'], $row['created_Date']);
$newOrders[] = $order;
}
$item = new Item($row['status'], $row['quantity']);
$order->AddItem($item, null);
}
function check_id($newOrders, $orderId) {
$length = count($newOrders);
for ($i = 0; $i < $length; $i++) {
if ($newOrders[$i]->$orderId == $orderId)
return $newOrders[$i];
}
return null;
}
foreach ($newOrders as $order) {
}
?>
You have a variable in your Order class
var $order_Id;
But then you try to assign value to $orderId which does not exist
$this->orderId = $orderId;
I would suggest turning all PHP errors on while developing. You can include this in your php code to see if you get any errors. It is very hard to see all the small errors with naked eye :) Let PHP do it for you.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
More about error reporting here.
You have several small mistakes, e.g. using "this" incorrectly, using different name for "orderId", plus a wrong name for the constructors. The constructor name should be "Order" or "__construct", same for "Item" constructor.
class Order {
/* Member variables */
var $orderId;
var $status;
var $createdDate;
var $items = array();
function Order($orderId, $status, $createdDate)
{
$this->orderId = $orderId;
$this->status = $status;
$this->createdDate = $createdDate;
}
function AddItem($itemId,$quantity)
{
$item = new Item($itemId,$quantity);
$items[] = $item;
}
}
$c = new Order(1, 'OK', 'today');
print_r($c);
Now i found the Solution in the PHP we have to use __construct() for the creating a Constructor....
So use it __construct instead of class name for more info visit:
__construct() vs SameAsClassName() for constructor in PHP
new_order.php
<?php
class Order {
/* Member variables */
var $order_Id;
var $status;
var $createdDate;
var $items = array();
function __Order($order_Id, $status, $createdDate)
{
$this->order_Id = $order_Id;
$this->status = $status;
$this->createdDate = $createdDate;
}
function AddItem($itemId,$quantity)
{
$item = new Item($itemId,$quantity);
$items[] = $item;
}
}
class Item {
var $productId;
var $productName;
var $quantity;
var $personalization;
function __Item($productId, $quantity)
{
$this->productId = $productId;
$this->productName = $productName;
$this->quantity = $quantity;
$this->personalization = $personalization;
}
}
?>
I have setup magmi with item disabler. And i got PHP notice: Undefined index: ITEM_SID in /home/mywebsite/www/public_html/magmi/plugins/extra/itemprocessors/itemdisabler/magmi_itemdisabler_plugin.php on line 65
This is the my code for item disabler
<?php class Magmi_ItemdisablerPlugin extends Magmi_GeneralImportPlugin {
protected $_dcols=array();
protected $magentoSortableAttributes = array();
public function getPluginInfo()
{
return array("name"=>"Magmi Magento Item Disabler",
"author"=>"RIS",
"version"=>"1.0.0");
}
public function afterImport()
{
$this->log("Running Item Disabler Plugin","info");
$this->disableItems();
return true;
}
public function getPluginParams($params)
{
return array();
}
public function isRunnable()
{
return array(true,"");
}
public function initialize($params)
{
}
public function disableItems()
{
$this->datasource = $this->getDataSource();
$nitems=$this->lookup();
if($nitems>0)
{
$datasource_item_sids = array();
$this->resetSkuStats();
//intialize store id cache
$this->callPlugins("datasources,itemprocessors","startImport");
//initializing item processors
$cols=$this->datasource->getColumnNames();
$this->log(count($cols),"columns");
//$this->callPlugins("itemprocessors","processColumnList",$cols);
//Pack the datasource sids into an array
$i = 0;
while(($item=$this->datasource->getNextRecord())!==false && $i++ <= $nitems)
{
if (isset($item['STYLE_SID']) && $this->isConfigurable($item['ATTR']))
{
array_push($datasource_item_sids, $item['STYLE_SID']);
}
array_push($datasource_item_sids, $item['ITEM_SID']);
if($i == $nitems) {
break;
}
}
if(count($datasource_item_sids) > 0) {
//Convert skus to comma seperated values.
//$datasource_item_sids = "'" . implode("','",$datasource_item_sids) . "'";
//Load in Database Helpers
require_once(realpath(dirname( __FILE__ ) )."/../../../../inc/dbhelper.class.php");
//var_dump($this->_magmiconfig->load()->get("DATABASE","host","localhost"));
$db = new DBHelper();
$host=$this->_magmiconfig->load()->get("DATABASE","host","localhost");
$dbname=$this->_magmiconfig->load()->get("DATABASE","dbname","magento");
$user=$this->_magmiconfig->load()->get("DATABASE","user");
$pass=$this->_magmiconfig->load()->get("DATABASE","password");
$debug=$this->_magmiconfig->load()->get("DATABASE","debug");
$conn=$this->_magmiconfig->load()->get("DATABASE","connectivity","net");
$port=$this->_magmiconfig->load()->get("DATABASE","port","3306");
$socket=$this->_magmiconfig->load()->get("DATABASE","unix_socket");
$prefix=$this->_magmiconfig->load()->get("DATABASE","table_prefix");
$db->initDb($host,$dbname,$user,$pass,$port,$socket,$conn,$debug);
//Setup tables
$ea = $prefix!=""?$prefix."eav_attribute":"eav_attribute";
$cpe = $prefix!=""?$prefix."catalog_product_entity":"catalog_product_entity";
$cpei = $prefix!=""?$prefix."catalog_product_entity_int":"catalog_product_entity_int";
//Get "status" attribute_id
$status_attr_id = "SELECT attribute_id FROM $ea WHERE attribute_code = 'status'";
$result = $db->selectAll($status_attr_id);
if (count($result) == 1) {
$attribute_id = $result[0]['attribute_id'];
}
unset($result);
//Get all active items
$sql = "SELECT e.sku, e.entity_id FROM $cpei i
INNER JOIN $cpe e ON
e.entity_id = i.entity_id
WHERE attribute_id=?
AND i.value = 1";
$all_magento_items = $db->selectAll($sql, array($attribute_id));
//Setup the magento_skus array for easy processing.
$magento_skus = array();
foreach($all_magento_items as $item)
{
$magento_skus[$item['sku']] = $item['entity_id'];
}
//process the array, move anything thats in the datasource.
foreach($datasource_item_sids as $sku)
{
if(isset($magento_skus[$sku]))
{
unset($magento_skus[$sku]);
}
}
if(!empty($magento_skus))
{
foreach($magento_skus as $sku => $id)
{
$this->log("Disabling Item Id $id with SKU: $sku", "info");
$this->update("
UPDATE $cpei i
INNER JOIN $cpe e ON
e.entity_id = i.entity_id
SET VALUE = '2'
WHERE attribute_id = ?
AND i.value = 1
AND e.sku=?", array($attribute_id, $sku));
}
}
else
{
//If the Datasource contains all Magento's items.
$this->log('All items present in datasource. No items to disable.', "info");
}
$db->exitDb();
unset($db);
}
}
}
public function isConfigurable($field) {
$attributes = explode('|',$field);
$conf_attributes = '';
foreach($attributes as $attribut) {
$att = explode(':',$attribut);
if(count($att) != 2) {
return false;
break;
}
if($att[1] == '') {
return false;
break;
}
}
return true;
}
}
Any idea how i can resolve this?
You can check if that element is set before using it:
while(($item=$this->datasource->getNextRecord())!==false && $i++ <= $nitems)
{
if (isset($item['STYLE_SID']) && $this->isConfigurable($item['ATTR']))
{
array_push($datasource_item_sids, $item['STYLE_SID']);
}
if (isset($item['ITEM_SID']){
array_push($datasource_item_sids, $item['ITEM_SID']);
}
if($i == $nitems) {
break;
}
}
I'm trying to develop a Php Photo Gallery only for my personal use and I put a Php System Rating using a modified script that I found on the web... all works fine except for one thing, I cannot stop users from posting several votes in the same day! I'd like that users vote the photos (several photos as well) but voting one time in the same day (one vote for each photo)... I post here the script that I have modified.
ratings.php:
<?php
$rating = new ratings($_POST['widget_id']);
isset($_POST['fetch']) ? $rating->get_ratings() : $rating->vote();
class ratings {
var $data_file = './ratings.data.txt';
private $widget_id;
private $data = array();
function __construct($wid) {
$this->widget_id = $wid;
$all = file_get_contents($this->data_file);
if ($all) {
$this->data = unserialize($all);
}
}
public function get_ratings() {
if ($this->data[$this->widget_id]) {
echo json_encode($this->data[$this->widget_id]);
} else {
$data['widget_id'] = $this->widget_id;
$data['number_votes'] = 0;
$data['total_points'] = 0;
$data['dec_avg'] = 0;
$data['whole_avg'] = 0;
echo json_encode($data);
}
}
public function vote() {
# Get the value of the vote
preg_match('/star_([1-5]{1})/', $_POST['clicked_on'], $match);
$vote = $match[1];
$ID = $this->widget_id;
# Update the record if it exists
if ($this->data[$ID]) {
$this->data[$ID]['number_votes'] += 1;
$this->data[$ID]['total_points'] += $vote;
} else { # Create a new one if it doesn't
$this->data[$ID]['number_votes'] = 1;
$this->data[$ID]['total_points'] = $vote;
}
$this->data[$ID]['dec_avg'] = round($this->data[$ID]['total_points'] / $this->data[$ID]['number_votes'], 1);
$this->data[$ID]['whole_avg'] = round($this->data[$ID]['dec_avg']);
file_put_contents($this->data_file, serialize($this->data));
$this->get_ratings();
}
# ---
# end class
}
?>
ratings.js:
$(document).ready(function() {
$('.rate_widget').each(function(i) {
var widget = this;
var out_data = {
widget_id : $(widget).attr('id'),
fetch: 1
};
$.post(
'ratings/ratings.php',
out_data,
function(INFO) {
$(widget).data('fsr', INFO);
set_votes(widget);
},
'json'
);
});
$('.ratings_stars').hover(
function() {
$(this).prevAll().andSelf().addClass('ratings_over');
$(this).nextAll().removeClass('ratings_vote');
},
function() {
$(this).prevAll().andSelf().removeClass('ratings_over');
set_votes($(this).parent());
}
);
$('.ratings_stars').bind('click', function() {
var star = this;
var widget = $(this).parent();
var clicked_data = {
clicked_on : $(star).attr('class'),
widget_id : $(star).parent().attr('id')
};
$.post(
'ratings/ratings.php',
clicked_data,
function(INFO) {
widget.data('fsr', INFO);
set_votes(widget);
},
'json'
);
});
});
function set_votes(widget) {
var avg = $(widget).data('fsr').whole_avg;
var votes = $(widget).data('fsr').number_votes;
var exact = $(widget).data('fsr').dec_avg;
window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').number_votes);
$(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote');
$(widget).find('.total_votes').text( votes + ' votes (' + exact + ' rating)' );
}
I tried to implement IP mechanism in ratings.php as below without lucky
<?php
$rating = new ratings($_POST['widget_id']);
isset($_POST['fetch']) ? $rating->get_ratings() : $rating->vote();
class ratings {
var $data_file = './ratings.data.txt';
private $widget_id;
private $data = array();
function __construct($wid) {
$this->widget_id = $wid;
$all = file_get_contents($this->data_file);
if ($all) {
$this->data = unserialize($all);
}
}
public function get_ratings() {
if ($this->data[$this->widget_id]) {
echo json_encode($this->data[$this->widget_id]);
} else {
$data['widget_id'] = $this->widget_id;
$data['number_votes'] = 0;
$data['total_points'] = 0;
$data['dec_avg'] = 0;
$data['whole_avg'] = 0;
echo json_encode($data);
}
}
public function vote() {
# Get the value of the vote
preg_match('/star_([1-5]{1})/', $_POST['clicked_on'], $match);
$vote = $match[1];
$ID = $this->widget_id;
# Update the record if it exists
if ($this->data[$ID]) {
$this->data[$ID]['number_votes'] += 1;
$this->data[$ID]['total_points'] += $vote;
$this->data[$ID]['remote_ip'] = $_SERVER['REMOTE_ADDR'];
} else { # Create a new one if it doesn't
$this->data[$ID]['number_votes'] = 1;
$this->data[$ID]['total_points'] = $vote;
$this->data[$ID]['remote_ip'] = $_SERVER['REMOTE_ADDR'];
}
if ($this->data[$ID]['remote_ip'] != $_SERVER['REMOTE_ADDR']) {
$this->data[$ID]['dec_avg'] = round($this->data[$ID]['total_points'] / $this->data[$ID]['number_votes'], 1);
$this->data[$ID]['whole_avg'] = round($this->data[$ID]['dec_avg']);
file_put_contents($this->data_file, serialize($this->data));
$this->get_ratings();
}
}
# ---
# end class
}
?>
The simplest way is to notify in a data table who vote and which day.
For example : Toto vote on 2014-07-04, so he can't vote twice today.
In data table user you add a colum date to notify the last day of vote.
You can use cookies but it's very very ugly !
Here is the php code.In this code station name and ids and random passengers are produced.
<?php
include_once('RestUtils.php');
include_once('Passengers.php');
class Station implements JsonSerializable
{
private $id;
private $name;
private $passengers;
public function __construct($id, $name)
{
$this->setId($id);
$this->setName($name);
$this->passengers = array();
}
//getters and setters
public function jsonSerialize()
{
$data = array();
$data['id'] = $this->id;
$data['name'] = $this->name;
$data['passengers'] = $this->passengers;
return $data;
}
}
$stations = generateStations();
$data = RestUtils::processRequest();
switch($data->getMethod())
{
// Get item
case 'get':
if(isset($data->getRequestVars()['stationId']))
{
// Prepare information for a specific station
$station = getStationWithId($stations, $data->getRequestVars()
['stationId']);
if($station != null)
{
echo RestUtils::sendResponse(200, json_encode($station),
'application/json');
}
else
{
echo RestUtils::sendResponse(404, 'Station not found!');
}
}
else
{
// Prepare station list
echo RestUtils::sendResponse(200, json_encode($stations),
'application/json');
}
break;
}
function generateStations()
{
$stations = array();
for($i = 1; $i <= 5; $i++)
{
$stations[] = new Station($i, 'İstasyon ' . $i);
$passengerIds = array();
foreach(generatePassengers() as $j)
{
$passengerIds[] = $j->getId();
}
$stations[$i - 1]->setPassengers($passengerIds);
}
return $stations;
}
function generatePassengers()
{
$passengers = array();
$numberOfPassengers = rand(0, 20);
for($i = 0; $i < $numberOfPassengers; $i++)
{
$from = rand(0, 5);
$to = rand(0, 5);
$arrivalTime = rand(0, 100);
$waitingTime = rand(0, 100);
$passengers[] = new Passenger($i, $from, $to, $arrivalTime, $waitingTime);
}
return $passengers;
}
function getStationWithId($stations, $id)
{
foreach ($stations as $i)
{
if($i->getId() == $id)
{
return $i;
}
}
return null;
}
?>
I want to fill the combobox with the produced station name and station ids when the page is loaded using document ready function.After that when the user selects a station with name and id, he can see how many passengers are there in that station and the ids of the passengers also should be returned from Station.php.
Normally I have had this select options in html code, it just showing the stations not doing anything when choosing any of them.
<select name="selectStation" id="selectStation" ></select>
I tried the following;
$(document).ready(function() {
$.getJSON("Stations.php", function(jsonData){
$.each(jsonData, function(key,value) {
$('#selectStation')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
});
});
I got the combobox values as object Object.Why does this happen?
How can fill the combobox when the page is loaded, according to Stations.php.Thanks.Any response will be appreciated.
Okay, here's some sample code that will do what I think you want.
Note: You still have to add an Event Listener to handle the change event of the select-box. I'll leave that to you.
File 1: ajaxAfterLoad.html
<!DOCTYPE html>
<html>
<head>
<script src="script/AjaxRequest.js"></script>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
window.addEventListener('load', mInit, false);
function mInit()
{
AjaxRequest.get( { 'url':'makeJSON.php', 'onSuccess': onAjaxRequestDone } );
}
function makeSelectElementFromJSON(elemId, jsonText)
{
var srcData = JSON.parse(jsonText);
var result = newEl('select');
result.setAttribute('id', elemId);
var i, curOpt;
for (i=0; i<srcData.length; i++)
{
curOpt = newEl('option');
curOpt.setAttribute('value', srcData[i].value);
curOpt.appendChild( newTxt( srcData[i].text ) );
result.appendChild(curOpt);
}
return result;
}
function onAjaxRequestDone(req)
{
var span = newEl('span');
span.innerHTML = req.responseText;
byId('rawOutput').innerHTML = req.responseText;
byId('ajaxOutput').appendChild( makeSelectElementFromJSON('jsonSelectBox1', req.responseText) );
}
</script>
<style>
</style>
</head>
<body>
<h2>Below will be loaded by ajax</h2>
<div id='rawOutput'></div>
<div id='ajaxOutput'></div>
</body>
</html>
File 2: makeJSON.php
<?php
$resultList = null;
for ($i=0; $i<10; $i++)
{
$curItem = null;
$curItem->value = $i;
$curItem->text = "Item " . ($i+1);
$resultList[] = $curItem;
}
printf("%s", json_encode($resultList) );
?>
File 3: AjaxRequest.js
Download this file from http://ajaxtoolbox.com/request/source.php