$ajax is being send but is missing a value - ajax

Ok, so my script tries to request from php results from mysql and load them into a div. The results are based on nid value which is has to send this value is extracted from id="record-#" the record- is removed and the # is left to be used by ajax as id for the nid.
here is the ajax data function
$(document).ready(function() {
$(".note").live('click',function() {
$("#note_utm_con").show();
$("#note_utm_nt").html("<img src='http://www.ajaxload.info/images/exemples/4.gif' />");
$.ajax({
type: "GET",
url: "_class/view.php",
data: "ajax=1&nid=" + parent.attr('id'),
success: function(html){
$("#note_utm").html(html);
$("#note_utm_nt").html("");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {$("#note_utm_nt").html(errorThrown);}
});
});
$("#note_utm_con_cls").click(function() {
$("#note_utm_con").hide();
});
});
and here is the rest of the page
<div id="note_utm_con" style="display: none;">
<button id="note_utm_con_cls" style="width: 20px;float: right; padding: 2px;clear: both;">X</button>
<div id="note_utm"></div>
<div id="note_utm_nt"></div>
</div>
<?php
class notes {
var $host;
var $username;
var $password;
var $table;
public function display_notes() {
$q = "SELECT * FROM `notice` ORDER BY nid ASC LIMIT 12";
$r = mysql_query($q);
if ( $r !== false && mysql_num_rows($r) > 0 ) {
while ( $a = mysql_fetch_assoc($r) ) {
$nid = stripslashes($a['nid']);
$note = stripslashes($a['note']);
$type = stripslashes($a['type']);
$private = stripslashes($a['private']);
$date = stripslashes($a['date']);
$author = stripslashes($a['author']);
if($type == 1) {
$type = "posted a comment."; $icon = "http://cdn1.iconfinder.com/data/icons/Basic_set2_Png/16/megaphone.png";
} elseif($type == 2) {
$type = "raised a support ticket."; $icon = "http://cdn1.iconfinder.com/data/icons/basicset/help_16.png";
} elseif($type == 3) {
$type = "added new photo."; $icon = "http://cdn1.iconfinder.com/data/icons/Basic_set2_Png/16/photo.png";
} elseif($type == 4) {
$type = "updated profile details."; $icon = "http://cdn1.iconfinder.com/data/icons/Basic_set2_Png/16/user_info.png";
} else { }
$entry_display .= <<<ENTRY_DISPLAY
<ul class="list">
<li id="$nid">
<a href="javascript:;" id="$nid" onClick="retun false;" class="note">
<img src="$icon" />
$author,
$type
</a>
</li>
</ul>
ENTRY_DISPLAY;
}
} else {
$entry_display = <<<ENTRY_DISPLAY
<ul class="list">
<li>
<p>
<img src="http://cdn1.iconfinder.com/data/icons/basicset/monitor_16.png" />
Nothing to display
</p>
</li>
</ul>
ENTRY_DISPLAY;
}
return $entry_display;
}
public function connect() {
mysql_connect($this->host,$this->username,$this->password) or die("Could not connect. " . mysql_error());
mysql_select_db($this->table) or die("Could not select database. " . mysql_error());
return $this;
}
private function note_type() {
if($type == 1) { $type = "posted a comment!"; } elseif($type == 2) { $type = "raised a support ticket!"; } else { }
return $type;
}
}
?>
so when a LI with a class="note" is clicked it triggers AJAX call. The call then uses the ID in the href to extract the $nid from the id="record-
In my case it seems as AJAX is sending the request since view.php returns the fields where the data should be but it does not seem to pass much needed nid so PHP is uable to select proper nid from MySQL to use.
Can some one tell me whats wrong with it and how it can be fixed to get the id?enter code here

Your quotation marks are wrong. Try this:
data: "ajax=1&nid=" + parent.attr('id').replace('record-',''),
Edit: Unless you haven't posted the full code still, you don't actually set parent anywhere. This means that you will use the window.parent object, which surprisingly enough doesn't have an id. You should use this.parentNode.id instead:
data: "ajax=1&nid=" + this.parentNode.id,

From what you've written it looks as if you're passing the parent.attr("id") replace call as a string rather than extracting the variable:
data: "ajax=1&nid=" + parent.attr('id').replace('record-',''),

Related

Unable to change button UI on AJAX getJSON .done

After creating add post to favorite and posted at codereview i had to improve my code as bellow,
And after changing code the button UI doesn't change when clicked
post_page.php
<?php
$email = 'user#mail.com';
// Query to get the user_id
$stmt = $conn->prepare('SELECT memberID FROM members WHERE email = :email AND active="Yes" ');
$stmt->execute(array(':email' => $email));
$row = $stmt->fetch();
$mbid = $row['memberID'];
$pid = '4';
// Query to Get the Director ID
$stmt = $conn->prepare('SELECT * FROM allpostdata WHERE id =:id');
$stmt->execute(array(':id' => $pid));
$result = $stmt->fetchAll();
foreach ($result as $row) {
echo "<p>Director: " . $row['tit'] . "</p> ";
$fav_image = checkFavorite($mbid, $pid, $conn);
echo "Favorite? : " . $fav_image . "";
}
function checkFavorite($mbid, $pid, $conn) {
$stmt = $conn->prepare("SELECT * FROM favorite WHERE memberID=:mid AND id=:id");
$stmt->execute(array(':mid' => $mbid, ':id' => $pid));
$count = $stmt->rowCount();
if ($count == 0) {
echo "<div class='button btn btn-block btn-outline-danger' method='Like' data-user=" . $mbid . " data-post=" . $pid . "> Add<i class='mi mi_sml ml-2' id=" . $pid . ">favorite_border</i></div>";
} else {
echo "<div class='button btn btn-block btn-outline-danger' method='Unlike' data-user=" . $mbid . " data-post=" . $pid . ">Remove<i class='mi mi_sml ml-2' id=" . $pid . ">favorite</i></div>";
}
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {
$('.button').click(function (e) {
e.preventDefault();
$.getJSON('favs.php',
{user_id: $(this).attr('data-user'),
director_id: $(this).attr('data-post'),
method: $(this).attr('method')})
.done(function (json) {
switch (json.feedback) {
case 'Like' :
$(this).attr('method', 'Unlike');
$(this).html('<i class="mi mi_sml text-danger" id="' + json.id + '">favorite</i>Remove Favorite').toggleClass('button mybtn'); // Replace the image with the liked button
break;
case 'Unlike' :
$(this).html('<i class="mi mi_sml" id="' + json.id + '">favorite_border</i>Add Favorite').toggleClass('mybtn button');
$(this).attr('method', 'Like');
break;
case 'Fail' :
alert('The Favorite setting could not be changed.');
break;
}
})
.fail(function (jqXHR, textStatus, error) {
alert("Error Changing Favorite: " + error);
});
});
});
</script>
favs.php
<?php
include("$_SERVER[DOCUMENT_ROOT]/include/config.php");
include("$_SERVER[DOCUMENT_ROOT]/classes/function.php");
$method = clean_input($_GET['method']);
$user_id = clean_input($_GET['user_id']);
$director_id = clean_input($_GET['director_id']);
switch ($method) {
case "Like" :
$query = 'INSERT INTO favorite (memberID, id) VALUES (:mID, :pID)';
break;
case "Unlike" :
$query = 'DELETE FROM favorite WHERE memberID=:mID and id=:pID';
break;
}
$feedback = 'Fail'; // start with pessimistic feedback
if (isset($query)) {
$stmt = $conn->prepare($query);
$stmt->bindParam(':mID', $user_id, PDO::PARAM_INT, 12);
$stmt->bindParam(':pID', $director_id, PDO::PARAM_INT, 12);
if ($stmt->execute()) {
$feedback = $method;
} // feedback becomes method on success
}
echo json_encode(['id' => $director_id,
'feedback' => $feedback]);
?>
My problem is when button is clicked and when ajax return success the button should change its UI.
where else in my case its not changing when on page load it show Add even after clicking on button and ajax return success still it is same.
The problem with your code is $(this) i.e: In ajax success function jquery is not able to find which element is clicked and where to apply required changes. To solve this you can store $(this) in some variable and use the same. Like below :
$('.button').click(function(e) {
//getting current element which is clicked
var button = $(this);
e.preventDefault();
$.getJSON('favs.php', {
user_id: $(this).attr('data-user'),
director_id: $(this).attr('data-post'),
method: $(this).attr('method')
})
.done(function(json) {
switch (json.feedback) {
case 'Like':
button.attr('method', 'Unlike');
button.html('<i class="mi mi_sml text-danger" id="' + json.id + '">favorite</i>Remove Favorite').toggleClass('button mybtn'); // Replace the image with the liked button
break;
case 'Unlike':
button.html('<i class="mi mi_sml" id="' + json.id + '">favorite_border</i>Add Favorite').toggleClass('mybtn button');
button.attr('method', 'Like');
break;
case 'Fail':
alert('The Favorite setting could not be changed.');
break;
}
})
.fail(function(jqXHR, textStatus, error) {
alert("Error Changing Favorite: " + error);
});
});

Call to undefined method Product_filter_model::fetch_data() | 500 Internal Server Error | Codeigninter

I am new to CodeIgniter and I have been struggling with this error for the past 3 hours.
Call to undefined method Product_filter_model::fetch_data() error in the following code.
You can view the error in Inspect > Network Tab at the following link:
http://admin.millionkidstoschool.org/index.php/product_filter
I have confirmed the names of the model, controller, and functions. I have also tried putting $this->load->model('product_filter_model'); inside the function fetch_data() and it did not help.
Controller
class Product_filter extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->model('product_filter_model');
$this->load->helper('url');
}
function fetch_data(){
$minimum_price = $this->input->post('minimum_price');
$maximum_price = $this->input->post('maximum_price');
$brand = $this->input->post('brand');
$ram = $this->input->post('ram');
$storage = $this->input->post('storage');
$output = array(
/*'pagination_link' => $this->pagination->create_links(),*/
'product_list' => $this->product_filter_model->fetch_data($minimum_price, $maximum_price, $brand, $ram, $storage)
);
echo json_encode($output);
}
View
$(document).ready(function(){
filter_data();
function filter_data(){
$('#filter_data').html("<div id='loading'></div>");
var action = 'fetch_data';
var minimum_price = $('#hidden_minimum_price').val();
var maximum_price = $('#hidden_maximum_price').val();
var brand = get_filter('brand');
var ram = get_filter('ram');
var storage = get_filter('storage');
$.ajax({
url:"<?php echo base_url(); ?>index.php/product_filter/fetch_data",
method:"POST",
dataType:"JSON",
data:{action:action, minimum_price:minimum_price,maximum_price:maximum_price, brand:brand, ram:ram, storage:storage},
success:function(data){
$('.filter_data').html(data.product_list);
/*$('#pagination_link').html(data.pagination_link);*/
}
})
}
}
Model
function fetch_data($minimum_price, $maximum_price, $brand, $ram, $storage)
{
$query = $this->make_query($minimum_price, $maximum_price, $brand, $ram, $storage);
/*$query .= ' LIMIT '.$start.', ' . $limit;*/
$data = $this->db->query($query);
$output = '';
if($data->num_rows() > 0)
{
foreach($data->result_array() as $row)
{
$output .= '
some data
';
}
}
else
{
$output = '<h3>No Data Found</h3>';
}
return $output;
}
Thank you for your time.
UPDATE:
I copied both the model methods' code in controller function where ajax request is posted. It worked. But I am unable to understand why the Controller function is unable to access Model Methods?
public function fetch_data(){
$this->load->model('product_filter_model');
$minimum_price = $this->input->post('minimum_price');
$maximum_price = $this->input->post('maximum_price');
$brand = $this->input->post('brand');
$ram = $this->input->post('ram');
$storage = $this->input->post('storage');
//$output = array(
/*'pagination_link' => $this->pagination->create_links(),*/
// 'product_list' => $this->product_filter_model->fetch_data//($minimum_price, $maximum_price, $brand, $ram, $storage)
//);
/*$query = $this->product_filter_model->make_query($minimum_price, $maximum_price, $brand, $ram, $storage);*/
/*$query .= ' LIMIT '.$start.', ' . $limit;*/
$query = "
SELECT * FROM product
WHERE product_status = '1'
";
if(isset($minimum_price, $maximum_price) && !empty($minimum_price) && !empty($maximum_price))
{
$query .= "
AND product_price BETWEEN '".$minimum_price."' AND '".$maximum_price."'
";
}
if(isset($brand)){
$brand_filter = implode("','", $brand);
$query .="
AND product_brand IN('".$brand_filter."')
";
}
if(isset($ram)){
$ram_filter = implode("','", $ram);
$query .="
AND product_ram IN('".$ram_filter."')
";
}
if(isset($storage)){
$storage_filter = implode("','", $storage);
$query .="
AND product_storage IN('".$storage_filter."')
";
}
/*
return $query;*/
$data = $this->db->query($query);
$result = '';
if($data->num_rows() > 0)
{
foreach($data->result_array() as $row)
{
$result .= '
<div class="col-sm-4 col-lg-3 col-md-3">
<div style="border:1px solid #ccc; border-radius:5px; padding:16px; margin-bottom:16px; height:450px;">
<img src="'.base_url().'images/'. $row['product_image'] .'" alt="" class="img-responsive" >
<p align="center"><strong>'. $row['product_name'] .'</strong></p>
<h4 style="text-align:center;" class="text-danger" >'. $row['product_price'] .'</h4>
<p>Camera : '. $row['product_camera'].' MP<br />
Brand : '. $row['product_brand'] .' <br />
RAM : '. $row['product_ram'] .' GB<br />
Storage : '. $row['product_storage'] .' GB </p>
</div>
</div>
';
}
$output = array('product_list' => $result);
}
else
{
$result = '<h3>No Data Found</h3>';
}
echo json_encode($output);

Retrieve data using Ajax Php laravel 5.3

According to my scenario when I select a doctor whose id is #slmc, I want to retrieve data relevant to the doctor I have chosen..
This is my blade File -> Admin/channel.blade
<label id="lslmc" for="slmc" class="control-label">Choose a Doctor </label><br />
<select class="form-control" id="slmc" name="slmc" onchange=" getPatient()" >
<option value="">----Select the Doctor----</option>
#foreach($Doctors as $Doctor)
<option value ="{{$Doctor-> slmc}}">{{$Doctor->fname}} {{$Doctor->sname}} </option>
#endforeach
</select>
</div>
<div id ="dd"></div>
Then this is my getPatient() function in the controller
public function getPatient($slmc){
$patients = DB::table('channel')->where('slmc', $slmc)->get();
return $patients;
}
This is the Ajax call in the script function.
function getPatient() {
var patient = $("#slmc").val();
$.ajax(
{
type: 'get',
url: ('/Admin/channel/getPatient'),
data: {'patients': patient},
success: function (data) {
$('#dd').html("");
$('#dd').html(data);
}
}
);
}
This is web.php
Route::get('/Admin/channel/getPatient{slmc}', 'channelController#getPatient' );
Is there something wrong with my Ajax call. I'm new to it.
Route :
Route::get('/Admin/channel/getPatient', 'channelController#getPatient' );
Controller :
ChannelController.php :
use Illuminate\Http\Request;
class ChannelController extends Controller
{
public function getPatient(Request $request){
$patients = \DB::table('channel')->where('slmc', $request->patients)->get();
return $patients;
}
}
I was able to do it
The ajax function goes like this
function getPatient() {
var patient = $("#slmc").val();
$.ajax({
type: 'get',
url: ('/Admin/channel/getPatient'),
data: {'slmc': patient},
success: function (data) {
$('#dd').html("");
var divHtml = "";
divHtml += "<table class='table table-bordered table-hover'>";
divHtml += "<tr>";
divHtml += "<td>" + data[0].pname + "</td>";
divHtml += "<td>" + data[0].address + "</td>";
divHtml += "</tr>";
divHtml += "</table>";
$('#dd').html(divHtml);
console.info(data);
},
error: function (data) {
console.error(data);
}
});
}
And my controller function is
public function getPatient(Request $request) {
$slmc = $request->get('slmc');
$patients = \DB::table('channel')->where('slmc', $slmc)->get();
return $patients;
}
web.php
Route::get('/Admin/channel/{slmc}', 'channelController#getPatient' );

yii2: call controller action in sortable jquery with ajax

I am using jquery sortable plugin to drag and drop items and setting their order. But I am unable to get the response from Ajax. I want to call the controller action from the js so that when I drag the item and drop it, then a response should come. The drag and drop functionality is working fine.
I tried this:
My View:
<div class="status-index info">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Status', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<ul class="sortable_status">
<?php
$items = StatusType::find()->orderBy('order')->all();
//var_dump($items);exit;
//$content = array();
foreach ($items as $item) {
echo '<li class="text-items"><label for="item'.$item->order.'"><span class="items-number">'.$item->order.'</span></label>
<label id="item'.$item->order.'" />'.$item->title.'</label>
<br/>
</li>';
}
?>
</ul>
</div>
JS:
$(function () {
var LI_POSITION = 'li_position';
$("ul.sortable_status").sortable({
update: function(event, ui) {
//create the array that hold the positions...
var order = [];
//loop trought each li...
$('.sortable_status li').each( function(e) {
//add each li position to the array...
// the +1 is for make it start from 1 instead of 0
order.push( $(this).attr('id') + '=' + ( $(this).index() + 1 ) );
});
// join the array as single variable...
var positions = order.join(';')
//use the variable as you need!
alert( positions );
// $.cookie( LI_POSITION , positions , { expires: 10 });
}
/*handle : '.handle',
update : function () {
var order = $('.sortable_status').sortable('serialize');
$(".info").load("process-sortable.php?"+order);
} */
});
});
Controller:
public function actionSortable()
{
/* foreach ($_GET['text-items'] as $position => $item)
{
$sql[] = "UPDATE `status_type` SET `order` = $position WHERE `id` = $item";
}*/
if ( isset( $_COOKIE['li_position'] ) ) {
//explode the cockie by ";"...
$lis = explode( ';' , $_COOKIE['li_position'] );
// loop for each "id_#=#" ...
foreach ( $lis as $key => $val ) {
//explode each value found by "="...
$pos = explode( '=' , $val );
//format the result into li...
$li .= '<li id="'.$pos[0].'" >'.$pos[1].'</li>';
}
//display it
echo $li;
// use this for delete the cookie!
// setcookie( 'li_position' , null );
} else {
// no cookie available display default set of lis
echo '
empty
';
}
}
why don't use an ajax call on stop ?
$("ul.sortable_status").sortable({
stop: function(event, ui) {
$.ajax({
type: "POST",
url: myUrl
data: {my-data: "any-value"}
})
.success(function(data) {
//your logic here
})
.fail(function() {
//your logic here
});
}
});
I used to define in my layout on the head tag of my html my variables as following
<head>
<script>
var myUrl = "<?php echo Url::to(['controller/action']); ?>";
</script>
</head>

Need help debugging Asynchronous AJAX call from a form in a div element to update same div with processed results based on form data

I am using a Mediawiki based website. The site is http://www.DragonFallRPG.com The widget in question is the 'Orion's Dice Box' in the left column of the site.
Not sure if that has any bearing on this but here goes. I have a custom div called 'dice' with a content destination div called 'result'. Below the 'result' div is a form for selecting a number of dice, and the number of sides for those dice. There is a processing script, which is tested working to provide a randomized result as if those dice were thrown. The problem is in the calling of one or more functions, I think. I found the AJAX method for getting the user input via 'get' somewhere on the web and no longer have any idea where it came from. I will include the files below.
dice_header.php (include file for <head> portion of webpage)
<style>
<!--[if IE] -- long buttons / button width in IE fix>
<style>.button{width:1;}</style>
<![endif]-->
</style>
<?php $javafile = dirname(__FILE__).'/ajax_engine.js'; ?>
<script type="text/javascript" src= "<?php echo $javafile ?>" ></script>
<script type="text/javascript">
function submit_dice() {
// Get form values
var no_of_dice = document.getElementById('dice').value;
var no_of_sides = document.getElementById('sides').value;
// Construct URL
<?php $handlerfile = dirname(__FILE__).'/handler.php' ?>
url = '<?php echo $handlerfile; ?>' + '?no_of_dice=' + escape(no_of_dice) + '&no_of_sides=' + escape(no_of_sides);
var xend = url.lastIndexOf("/") + 1;
var base_url = url.substring(0, xend);
alert('Handlerfile URL = ' + url + '\r\n\r\n Escape URL = ' + escape(url) + '\r\n\r\n # of dice = ' + no_of_dice + '\r\n # of Sides = ' + no_of_sides);
alert('url for ajax_get = ' + url);
ajax_get (url, 'result');
}
</script>
The above code is an include in the header of the index.php
The function call for ajax_get seems to be where it breaks down in the process in the above code. I don't know if it requires the http portion of the url or not. I don't know if the escape url is required or not. I'm hesitant to monkey with the script any further without guidance.
The code that follows is the div block for the widget I'm trying to create
dice.php (include file for my widget / div block)
<div id="result" style="text-align:center;
word-wrap: break-word;
width:100px;
font-weight:bold;
font-size:large;
border:1px blue solid;
margin:0;">
<?php
//$filename = dirname(__FILE__).'/ajax_engine.js';
//$handlerfile = dirname(__FILE__).'/handler.php';
if (file_exists($handlerfile)) {
echo "Handler file path OK";
echo 'alert(\'Handler file path = "' . $handlerfile . '"\');';
die();
} else {
echo "BAD handler file path!";
}
?>
</div>
<table border="0" cellspacing="0" cellpadding="0" style="margin:0; padding:0px;" >
<tr>
<td><select name="dice" id="dice" size="1" style="margin:0px;">
<?php
for ($i = 1; ; $i++) {
if ($i > 20) {
break;
}
if ($i == 1) {
echo "<option value=$i selected>$i</option>\n";
} else {
echo "<option value=$i>$i</option>\n";
}
}
?>
</select></td>
<td><select name="sides" id="sides" size="1" style="margin:0px;">
<option value="4">d4</option>
<option value="6">d6</option>
<option value="8">d8</option>
<option value="10">d10</option>
<option value="12">d12</option>
<option value="20" selected>d20</option>
<option value="100">d100</option>
</select>
</td>
</tr><tr>
<td colspan="2">
<input type="button" onclick="submit_dice();" value="Roll Dice" style="width:100px;" />
</td></tr>
</table>
<!--
Psuedo vs. True Random Numbers
http://www.phpfive.net/pseudo-random_php_functions_and_truly_random_number_generators_article2.htm
-->
Next follows the javascript engine I'm using to begin the AJAX functionality... Mediawiki has it's own built in AJAX - but I have no familiarity with it and tried finding a less complicated working version else where that I could tweak - resulting in this headache.
Several alert popup calls made to help with debugging, but I'm lost, and none of these alerts are actually being called... I can't tell why.
// JavaScript Document "javascript_engine.js"
// Get base url
url = document.location.href;
var base_url = "http://";
alert('base_url = ' + base_url);
xend = url.lastIndexOf("/") + 1;
var base_url = url.substring(0, xend);
var ajax_get_error = false;
alert('ajax_engine.js called');
function ajax_do (url) {
// Does URL begin with http?
alert('url.substring(0, 4) = ' + url);
if (url.substring(0, 4) != 'http') {
url = base_url + url;
}
// Create new JS element
var jsel = document.createElement('SCRIPT');
jsel.type = 'text/javascript';
jsel.src = url;
// Append JS element (therefore executing the 'AJAX' call)
document.body.appendChild (jsel);
return true;
}
function ajax_get (url, el) {
// Has element been passed as object or id-string?
if (typeof(el) == 'string') {
el = document.getElementById(el);
}
// Valid el?
if (el == null) { return false; }
alert(url.substring(0, 4));
// Does URL begin with http?
if (url.substring(0, 4) != 'http') {
url = base_url + url;
}
// Create getfile URL
getfile_url = base_url + 'getfile.php?url=' + escape(url) + '&el=' + escape(el.id);
// Do Ajax
ajax_do (getfile_url);
return true;
}
Following is getfile.php
<?php //getfile.php -- used for addressing visual part of code
// Get URL and div
if (!isset($_GET['url'])) { die(); } else { $url = $_GET['url']; }
if (!isset($_GET['el'])) { die(); } else { $el = $_GET['el']; }
// echo 'alert(\'URL in getfile.php = \'); $url';
// Make sure url starts with http
if (substr($url, 0, 4) != 'http') {
// Set error
echo 'alert(\'Security error; incorrect URL!\');';
die();
}
// Try and get contents
$data = #file_get_contents($url);
if ($data === false) {
// Set error
echo 'alert(\'Unable to retrieve "' . $url . '"\');';
die();
}
// Escape data
$data = str_replace("'", "\'", $data);
$data = str_replace('"', "'+String.fromCharCode(34)+'", $data);
$data = str_replace ("\r\n", '\n', $data);
$data = str_replace ("\r", '\n', $data);
$data = str_replace ("\n", '\n', $data);
?>
el = document.getElementById('<?php echo $el; ?>');
el.innerHTML = '<?php echo $data; ?>';
Following is the form processor, generating the random numbers result for the AJAX output/update.
<?php // handler.php
/////////////////////////////////////////////////////////////////
// Random Dice Value Generator v1.0 //
// http://www.dragonfallrpg.com //
// Orion Johnson Copyright 2007 //
// //
// This script is used to create a random number based //
// values from the user's input //
/////////////////////////////////////////////////////////////////
/* double rolldice(int, int)
* - generates a random value based on the numbers passed as an argument
* - maximum iterations = 20 (can be changed in the user form)
* - maximum number of sides per function call = 4, 6, 8, 10, 12, 20, or 100 (can be changed)
*
* Usage: To generate a random total value as if one had thrown that many dice:
* Note: Future revisions may include the ability to add additional lines to the user form
* to mix types of simulated dice being thrown.
*
* array $no_of_dice(x-1); array value "x" taken from user form
* var $no_of_sides; value taken from user form
* var $total_value; sum of values from entire array
* echo $total_value;
*/
// Check variables
if (empty($_GET['no_of_dice'])) {
die ('<span style="color:red;">Number of dice value invalid!</span>');
}
if (empty($_GET['no_of_sides'])) {
die ('<span style="color:red;">Number of sides value invalid!</span>');
}
// seed with microseconds
function make_seed()
{
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 1000003);
}
function rolldice()
{
$total_value = 0; /* sum of values from entire array */
srand(make_seed()); /* seed random number generator // 1,000,003 is a prime number */
/* start loop structure from 0 to $no_of_dice */
for($i = 0; $i < $_GET['no_of_dice']; $i++)
{
$randnum = rand(1, $_GET['no_of_sides']);
$total_value = $total_value + $randnum;
}
/* end loop */
/* print/return results to the screen */
// echo 'Total value for dice: ' + rolldice();
return $total_value;
}
// Taken from http://www.sebflipper.com/?page=code&file=password.php
// for array iteration see also: http://www.php-scripts.com/php_diary/122799.php3
?>
If there is a simpler way to perform a div update with a random result based on form input, I'm all ears. This has been a headache for too long for me. I'm no code-head, just know enough to tinker and make some things work and understand most things when explained.
I haven't read through all the code, but since MediaWiki 1.17.0 there's a feature called ResourceLoader (if you have older version you should upgrade), which you can use for this purpose.
You can make the whole code into an extension to have it organized in a directory (let's say extensions/DiceBox). The DiceBox.php file in that folder would then be along these lines:
<?php
if( !defined( 'MEDIAWIKI' ) ) {
die();
}
$wgExtensionFunctions[] = 'DiceBoxInit';
$wgHooks['SkinTemplateToolboxEnd'][] = 'DiceBoxOnSkinTemplateToolboxEnd';
$wgResourceModules['ext.DiceBox'] = array(
'localBasePath' => dirname( __FILE__ ),
'remoteExtPath' => 'DiceBox',
'scripts' => 'ext.DiceBox.js',
'dependencies' => 'jquery'
);
function DiceBoxInit() {
global $wgOut;
$wgOut->addModules( 'ext.DiceBox' );
}
?>
<?php
function DiceBoxOnSkinTemplateToolboxEnd() {
$sides = array( 4, 6, 8, 10, 12, 20, 100 );
?>
</ul>
</div>
</div>
<div class="portlet" id="p-dicebox">
<h5>Orion's Dice Box</h5>
<div class="pBody">
<div id="dice-result" style="display: none;"></div>
<form id="dice-form">
<select name="no_of_dice">
<?php
for( $i = 1; $i <= 20; $i++ ) {
echo '<option value="', $i, '">', $i, '</option>';
}
?>
</select>
<select name="no_of_sides">
<?php
foreach( $sides as $n ) {
echo '<option value="', $n, '">d', $n, '</option>';
}
?>
</select>
<input type="button" value="Roll Dice" id="dice-roll" />
</form>
<?php
return true;
}
This code outputs the code box HTML in the sidebar and registers the following JavaScript file (ext.DiceBox.js) to be available on the page:
jQuery( document ).ready( function( $ ) {
$( '#dice-roll' ).click( function() {
$.get( mw.config.get( 'wgExtensionAssetsPath' ) + '/DiceBox/handler.php',
$( '#dice-form' ).serialize(), function( data )
{
$( '#dice-result' ).html( data ).append( '<hr />' ).show();
} );
} );
} );
This code simply uses jQuery (which is bundled with MediaWiki as of 1.16.0) to send a request to the server when the button is clicked and displays the result in the box.
In the handler.php file, there's no place where the random number gets output, so you need to add echo rolldice(); before the ?>.
Finally, to make the extensions fully work, add require_once $IP . '/extensions/DiceBox/DiceBox.php'; to the bottom of LocalSettings.php.

Resources