How to fill the combobox from php with document ready function? - php

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

Related

Assign the value to the Object in php

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

Php system rating for photo gallery that allows 1 vote/day for each photo

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 !

how to insert inputs to genetic algorithm classes in php

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'];
...
}
...
}

Execution of mySQL query in jQuery.Post method

I have created a javascript file that contains js to trigger an event onchange of a drop down list. The JS is below:
// /public/js/custom.js
jQuery(function($) {
$("#parent").change(function(event){
event.preventDefault();
var parentID = $('#parent').val();
var id = $('#id').val();
$.post("/menu/GetMenuChildren", {pID: parentID, thisID: id },
function(data){
if(data.response === true){
var $el = $("#Position");
$el.empty(); // remove old options
$.each(data.newOptions, function(key, value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
} else {
// print error message
alert("something went wrong in Post");
}
}, 'json');
alert("After Post");
});
});
In my Controller.php I have an function GetMenuChildrenAction as shown below:
public function GetMenuChildrenAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
if ($request->isPost())
{
$post_data = $request->getPost();
$parent_id = $post_data['pID'];
$id = $post_data['thisID'];
//$this->form->get('Position')->SetOptionValues(
$newOptions = $this->getMenuTable()->GetPositionsByID($parent_id, $id);
if(isset($newOptions))
{
$response->setContent(\Zend\Json\Json::encode(array('response' => true, 'newOptions' => $newOptions)));
}
else
{
$response->setContent(\Zend\Json\Json::encode(array('response' => false)));
}
}
return $response;
}
In the MenuTable.php there is a Method GetPositionsByID as shown below:
public function GetPositionsByID($parentID, $id)
{
if($parentID == 0)
{
$menu = $this->getMenu($this->id);
$parentID = $menu->parent_id;
}
if(isset($parentID))
{
$sql = "Select ID,Label from Menu Where parent_ID = " . $parentID . " and id > 1 and id <> " . $id . " Order by Position,Label";
try
{
$statement = $this->adapter->query($sql);
}
catch(Exception $e) {
console.log('Caught exception: ', $e->getMessage(), "\n");
}
$res = $statement->execute();
$rows = array();
$i = 0;
foreach ($res as $row) {
$i = $i + 1;
$rows[$i] = array (
$i => $row['Label']
);
}
return $rows;
}
return array();
}
It all seems to be hooked up correctly, when I debug the code, I get the this line:
$statement = $this->adapter->query($sql);
and then nothing happens. If I replace all the code in the GetPositionsByID method, and simply return an array like the following:
return array('1' => 'one', '2' => 'two');
it works great, however i want to get the data from the DB. Does anyone know why the execute would fail on this line?
$statement = $this->adapter->query($sql);
Thanks in advance
The issue was that the adapter was null.

Checking a cookie in a PHP script

Hey i still need a little bit of help with the rating system but i have a problem checking if the cookie exist this is
<?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
# doesn't update if it already exists
if (!isset($_COOKIE[$id])) {
if($this->data[$ID]) {
$this->data[$ID]['number_votes'] += 1;
$this->data[$ID]['total_points'] += $vote;
}
# Create a new one if it doesn't
else {
$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();
}
} //ends if isset
# ---
# end class
}
?>
The part that should check if the cookie exist is this:
if (!isset($_COOKIE[$id])) {
but for some reason nothing in the script works when i add that.
if (!isset($_COOKIE[$id])) {
You declared everything as $ID, but you're using $id. Try switching that out and see if it works.
if (!isset($_COOKIE[$ID])) {
i think what you wanted to do is isset (if exist) intead of !isset (if doesn t exist)
if (isset($_COOKIE[$id])) {

Categories