I'm having trouble finding my exact question so I'll post it here. I'm working with an oracle database and I'm linking it to an HTML website via javascript and php. I got the php file to display properly. Essentially what's supposed to happen is I have 4 button, each one generates a specific query and displays the results in a new html page. It's a movie database, so one of our queries is Budgets vs. Genre. It works the way I have it, but it doesn't generate it via the html file, it displays the PHP file. My goal is to retrieve the output of the PHP file via javascript and set it to the HTML file for output. I'm new to php and javascript working together, so maybe someone can tell me what's happening here and what needs to be changed for it to work properly. I got the javascript code from oracles website for connecting a database to a website.
Here's my PHP first:
<?php
// Connect to the database=
$c = oci_connect ("user101", "pass101", "localhost:1521/XE");
// Define the query.
$q = 'SELECT distinct m.title, f.budget FROM movies m, finance f WHERE m.imdb_id = f.imdb_id AND budget > 100000000 ORDER BY budget DESC';
// Parse the query.
$s = oci_parse($c, $q);
$didbv = 60;
oci_bind_by_name($s, ':budget', $budget);
oci_bind_by_name($s, ':title', $title);
// Execute the query.
oci_execute($s);
$i = 1;
print '<table border="1"><tr><th>Rank</th><th>Title</th><th>Budget</th>';
while (($row = oci_fetch_array($s, OCI_ASSOC)) != false) {
$table[i++] = array("title" => $row['TITLE'], 'budget' => $row['BUDGET']);
}
oci_free_statement($s);
// Close the connection.
oci_close($c);
header('Content-Type: application/json');
echo json_encode($table);
?>
and here's my javascript :
$(function() {
$("button#genBudg").click(function() {
$.getJSON("ajaxCopy.php", function(data) {
var reportTable = $("<table>", {
border: 1
});
reportTable.append("<thead><th>Rank</th><th>Title</th><th>Budget</th></thead><tbody></tbody>");
$.each(data, function(k, v) {
reportTable.find("tbody").append("<tr><td>" + k + "</td><td>" + v.title + "</td><td>" + v.budget + "</td></tr>");
});
$("#bud_gro").append(reportTable);
window.location.replace("generate_report.html");
});
});
});
and here's my html:
(select_report.html)
<html lang ="en">
<head>
<title>Movie Analysis</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/CSS" href="movies.CSS">
</head>
<body>
<h2>Reports</h2>
<div class="input_options">
<div>
<button type="button" class="option" style="padding:10px 30px" id="genBudg">Genre vs Budget</button>
<button type="button" class="option" style="padding:10px 30px">Rating vs Budget</button>
</div>
<div>
<button type="button" class="option" style="padding:10px 30px">Budget vs Gross</button>
<button type="button" class="option" style="padding:10px 30px">Actor vs Rating</button>
</div>
</div>
<script src ="jquery-1.4.4.js"></script>
<script src="movies.js"></script>
</body>
</html>
(generate_report.html)
<html lang ="en">
<head>
<title>Movie Analysis</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/CSS" href="movies.CSS">
</head>
<body>
<h2>Name of report</h2>
<div id = "bud_gro"></div>
<script src="movies.js"></script>
<script src="jquery-1.4.4.js"></script>
</body>
</html>
As discussed, it may be better to pass JSON data back to an AJAX call and build the table based on the results. This might look like this:
PHP
<?php
// Connect to the database= oci_connect ("user101", "pass101", "localhost:1521/XE");
// Define the query.
$q = 'SELECT distinct m.title, f.budget FROM movies m, finance f WHERE m.imdb_id = f.imdb_id AND budget > 100000000 ORDER BY budget DESC';
// Parse the query.
$s = oci_parse($c, $q);
$didbv = 60;
oci_bind_by_name($s, ':budget', $budget);
oci_bind_by_name($s, ':title', $title);
// Execute the query.
oci_execute($s);
$i = 1;
$table = array();
while (($row = oci_fetch_array($s, OCI_ASSOC)) != false) {
$table[i++] = array("title" => $row['TITLE'], "budget" => $row['BUDGET']);
}
oci_free_statement($s);
// Close the connection.
oci_close($c);
header('Content-Type: application/json');
echo json_encode($table);
?>
You can then make use of a jQuery solution like so:
HTML
<button id="getReport">
Get Report
</button>
<h2>Name of report</h2>
<p id="bud_gro"></p>
JavaScript
$(function() {
$("button#getReport").click(function() {
$.getJSON("ajax.php", function(data) {
var reportTable = $("<table>", {
border: 1
});
reportTable.append("<thead><th>Rank</th><th>Title</th><th>Budget</th></thead><tbody></tbody>");
$.each(data, function(k, v) {
reportTable.find("tbody").append("<tr><td>" + k + "</td><td>" + v.title + "</td><td>" + v.budget + "</td></tr>");
});
$("#bud_gro").append(reportTable);
});
});
});
Related
I have a form which takes a student name, subject and age. When submitted, it saves the data as an array in txt file. Next time, when I put new data and submit it, it creates a new array in that txt file instead of appending it to the previous array.
<?php
if(!empty($_GET)){
$student = [];
$student['name'] = $_GET['name'];
$student['subject'] = $_GET['subject'];
$student['age'] = $_GET['age'];
$studentArray = [];
array_push($studentArray, $student);
$str = print_r($studentArray, true);
file_put_contents('student.txt', $str, FILE_APPEND);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="" method="GET">
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<label for="name">Subject:</label>
<input type="text" name="subject" id="subject">
<label for="name">Age:</label>
<input type="number" name="age" id="age">
<input type="submit" name="submitButton">
</form>
</body>
</html>
output looks like this:
however I want to save it like below:
How could I do that?
If you really have to see your nice array in text use this:
if(!empty($_GET)){
$student = array();
$int = 0;
$txtfile = "student.txt";
if (file_exists($txtfile)) {
$fgc = file_get_contents($txtfile);
$expl = explode("[".$int."] => Array", $fgc);
while (count($expl) > 1) {
$expl2 = (count($expl) > 1) ? explode("[".($int+1)."] => Array", $expl[1])[0] : $expl[1];
$m = preg_match_all("#\\[([\d\w]+)\\] => ([^\n]*)#imus", $expl2, $matches);
if ($m == 0) { break; }
foreach ($matches[1] as $key => $val) {
$student[$int][$val] = $matches[2][$key];
}
$int++;
$expl = explode("[".$int."] => Array", $fgc);
}
}
$student[$int]['name'] = $_GET['name'];
$student[$int]['subject'] = $_GET['subject'];
$student[$int]['age'] = $_GET['age'];
$str = print_r($student, true);
file_put_contents('student.txt', $str);
print_r($student);
}
But please use a serialized version like this:
if(!empty($_GET)){
$student = array();
$int = 0;
$txtfile = "student.txt";
if (file_exists($txtfile)) {
$fgc = file_get_contents($txtfile);
$student = unserialize($fgc);
$int = count($student);
}
$student[$int]['name'] = $_GET['name'];
$student[$int]['subject'] = $_GET['subject'];
$student[$int]['age'] = $_GET['age'];
file_put_contents('student.txt', serialize($student));
print_r($student);
}
print_r for debug only.
Have fun ;)
You have to use JSON in order to update your array constantly.
the important point is you have to load your students in a variable and then push the new student to that variable so, in the end, you can save your students variable which contains all students in one array like you want.
Requirements to make this code works:
Create a file named student.json and put [] inside the file
Also, I highly suggest go and learn about JSON in PHP so you can have a better understanding of how this code is working now
if(!empty($_GET)){
$student = [];
$student['name'] = $_GET['name'];
$student['subject'] = $_GET['subject'];
$student['age'] = $_GET['age'];
$studentArray = json_decode( file_get_contents('student.json'), true);
array_push($studentArray, $student);
$str = print_r($studentArray, true);
file_put_contents('student.json', json_encode($studentArray));
}
I am trying to obtain the values of dynamically created select dropdowns from my php page. The dropdowns were added via javascript to the page.
The error that I get is Notice: Undefined index: daySelect in C:\wamp\www\responsive2\select.php on line 7
I would like to know how to access posted select dropdowns values with php.
Thanks in advance.
Code follows
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST"){
echo "We have something";
echo ($_POST['daySelect']); // error here
}
else
{
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dynamic Select</title>
</head>
<body>
<form id="theform" style="display: none" method="POST" name="theform" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="placeHere"></div>
<button type="submit">Submit</button>
</form>
<button onclick="createSelect()">Create</button>
<script>
var elem = document.getElementById('placeHere');
var daySelect = new Array();
var theForm = document.getElementById('theform');
var numSelects = 0;
var days = ['01','02','03','04','05','06','07','08','09','10',
'11','12','13','14','15','16','17','18','19','20',
'21','22','23','24','25','26','27','28','29','30',
'31'];
function createSelect()
{
numSelects++;
daySelect.push(document.createElement('select'));
daySelect[daySelect.length -1].setAttribute('id',
daySelect[daySelect.length -1]);
daySelect[daySelect.length -1].name = daySelect[daySelect.length -1];
var opt = document.createElement('option');
opt.text = "Select";
opt.value = "";
//myArray[myArray.length - 1];
daySelect[daySelect.length -1].appendChild(opt);
for (var i = 0; i < 31; i++)
{
var opt = document.createElement("option");
opt.text = days[i];
opt.value = days[i];
//opt.className = i;
//optarr.push(opt[i]);
daySelect[daySelect.length -1].appendChild(opt);
}
elem.appendChild(daySelect[daySelect.length -1]);
theForm.style.display = "block";
//alert("HI");
}
</script>
</body>
</html>
<?php
}
?>
You need to set your select "name" and "id" to a string name. Right now you are setting those 2 attributes to the daySelect object value, which is getting interpreted as a string, so you have:
<select id="[object HTMLSelectElement]" name="[object HTMLSelectElement]">
Update the the .setAttribute and .name lines to:
daySelect[daySelect.length - 1].setAttribute('id',
'daySelect' + (daySelect.length - 1));
daySelect[daySelect.length - 1].name = 'daySelect[]';
The name is set to an array because of the [], so you could just loop through $_POST['daySelect'], with PHP, using a foreach.
Change the echo to print_r to view array values in the browser.
Hope that helps.
I've got the following problem:
I'm uploading a survey on amazon mturk using Python and the survey is done via HTML and javascript. I show one of three different versions of the survey to participants, which I select by generating a random number via javascript. I store the number in local storage to prevent refreshing the website from resetting it. The problem I find is that more people seem to get versions 1 than version 3. But I cannot recreate the problem for myself when running the code in Tryit Editor online.
Could you please help me understand (and fix) why this happens? The following is the (trimmed) HTML code that I upload. I replaced text and removed fluff.
<HTMLQuestion xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2011-11-11/HTMLQuestion.xsd">
<HTMLContent><![CDATA[
<!-- YOUR HTML BEGINS -->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
<script type='text/javascript' src='https://s3.amazonaws.com/mturk-public/externalHIT_v1.js'></script>
<script>
function test(){
document.getElementById('txt-field').value = "1";
}
</script>
</head>
<body>
<form name='mturk_form' method='post' id='mturk_form' action='https://www.mturk.com/mturk/externalSubmit'><input type='hidden' value='' name='assignmentId' id='assignmentId'/>
<span>
<INPUT TYPE="text" NAME="link_click" id='txt-field' value="0" style="display: none">
<div><h3><a href="www.google.com" target="_blank" id='report420' onclick="test()" >link</a></h3>
Instructions</div>
<div><table border="1" style="height: 258px;" width="196"><tbody>Table</tbody></table></div>
</span>
<!--I think the relevant part starts here-->
<script>
document.write("Miscellaneous question");
var i = localStorage.getItem('i') || Math.floor(3*Math.random());
localStorage.setItem('i',i);
if (i==0){
document.write("Version 1");
}
if (i==1){
document.write("Version 2");
}
if (i==2){
document.write("Version 3");
}
document.write("Miscellaneous question");
</script>
<p><input type='submit' id='submitButton' value='Submit' /></p></form>
<script language='Javascript'>turkSetAssignmentID();</script>
</body></html>
<!-- YOUR HTML ENDS -->
]]>
</HTMLContent>
<FrameHeight>600</FrameHeight>
</HTMLQuestion>
The random function Math.floor(3*Math.random()) has uniform distribution, but I don't think that 400 samples are enough so that you can see it in action (as #desoares mentioned).
Testing code:
var count = [0, 0, 0];
var n = 1000000;
document.write('Testing for ' + n + ' samples : ');
for (var i = 0; i < n; i++) {
count[Math.floor(3*Math.random())]++;
}
document.write(JSON.stringify(count));
var count = [0, 0, 0];
var n = 400;
document.write('Testing for ' + n + ' samples : ');
for (var i = 0; i < n; i++) {
count[Math.floor(3*Math.random())]++;
}
document.write(JSON.stringify(count));
Also, if you want to be sure that people from the same computer are not forced to take the same version, you should clear the saved variable localStorage.removeItem('i'); on submit. You may also add an expiration mechanic.
First of all,i'm sorry for my english. I've created a simple wishlist system for an online store i'm building using jquery. But now i don't know how to store the items in local storage so the user can see them the next time he visit the store. I'm new to jquery and my coding abilities are very poor. Here's what i built:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<style>
body{background:#333;font-family:"Open sans", sans-serif;font-size:100%;text-align:center;font-size:62.5%;}
button{padding:5px 20px;border-radius:4px;margin:10px auto;border:0;background-color:#fff;font-weight:600;cursor:pointer;color:#c12267;}
#wish_list{margin:100px auto;min-height:300px;width:100%;background:#fff;}
#wish_list .wish_list_heading{margin:0;color:#fff;height:30px;background-color:#c12267;overflow:hidden;padding:5px;font-weight:600;}
#wish_list_item{width:100%;text-align:center;border-spacing:0px;border-collapse:separate;}
.wishlist-item{position:relative;clear:both;width:100%;margin:2px 0;padding:0;float:left;display:block;height:80px;border-bottom:1px solid #EEE;}
.w-premove{position:absolute;width:20px;display:block;height:20px;top:30px;left:0;text-align:center;font-weight:900;font-size:140%;line-height:20px;color:red;}
.w-pimage{top:0;left:25px;width:75px;height:25px;display:block;position:absolute;}
.w-pimage img{width:100%;}
.w-pname{top:5px;left:100px;width:calc(100% - 100px);width:-o-calc(100% - 100px);width:-webkit-calc(100% - 100px);width:-moz-calc(100% - 100px);height:40px;padding:0;text-align:left;font-size:140%;font-weight:600;line-height:1em;position:absolute;}
.w-pname a{text-decoration:none;color:#333;}
.w-price{top:50px;left:100px;height:20px;width:75px;color:#c12267;font-weight:600;font-size:150%;text-align:center;line-height:20px;display:block;position:absolute;}
</style>
</head>
<body>
<button class='wishlist' product_name='Product 1' product_id='product1' product_link="PRODUCT PAGE URL" product_price='90' product_image="IMAGE LINK">DESEJAR</button>
<div id='wish_list'>
<p class="wish_list_heading">
<span id='listitem'>0</span>
<span id='p_label'>Product</span>
</p>
<table id='wish_list_item' border='0'></table>
</div>
<script type='text/javascript'>
var wish_list = new Array();
jQuery(function(){
jQuery(".wishlist").on("click",function(){
$data = "";
$product_id = jQuery(this).attr("product_id");
$product_name = jQuery(this).attr("product_name");
$prduct_price = jQuery(this).attr("product_price");
$product_link = jQuery(this).attr("product_link");
$product_image = jQuery(this).attr("product_image");
if(jQuery.inArray($product_id,wish_list)==-1){
$product_str = "<tr class='wishlist-item' id='list_id_"+$product_id+"'><td class='w-premove' wpid='"+$product_id+"'>x</td><td class='w-pimage'><img src='"+$product_image+"' /></td><td class='w-pname'><a href='"+$product_link+"'>"+$product_name+"</a></td><td class='w-price'>"+$prduct_price+"€</td></tr>";
jQuery("#wish_list_item").append($product_str);
wish_list.push($product_id);
}
count_items_in_wishlist_update();
});
jQuery("#wish_list_item").on("click",".w-premove",function(){
$product_id = jQuery(this).attr("wpid");
jQuery("#list_id_"+$product_id).remove();
wish_list = jQuery.grep( wish_list, function( n, i ) {
return n != $product_id;
});
count_items_in_wishlist_update();
});
});
function count_items_in_wishlist_update(){
jQuery("#listitem").html(wish_list.length);
if(wish_list.length>1){
jQuery("#p_label").html("Products");
}else{
jQuery("#p_label").html("Product");
}
}
</script>
</body>
</html>`
Is it possible to store the strings $product_str in local Storage and present them when the user comes back? How can this be done?
Use
localStorage.setItem("lastname", "Smith");
to set a value with lastname as key and "Smith" as value
Use,
var result = localStorage.getItem("lastname");
to get the value of key lastname
The localStorage object stores the data with no expiration date.
You might want to look into cookies.
SO I have code that I'm trying to implement from my jsfiddle into an actual working website/mini-app. I've registered the domain name and procured the hosting via siteground, and I've even uploaded the files via ftp so I'm almost there...
But I'm thinking there's something wrong with my HTML code or JS code or how I implemented my JS code into my HTML code, because all of the HTML and CSS elements are present, but the javascript functionality is absent.
Here is my fiddle:
jsfiddle
^^ Click on start to see the display in action (which doesn't work in the actual website, which leads me to believe there's an issue with my JS file - whether it be code-related or whether that's because I integrated the file incorrectly) (or maybe even uploaded to the server incorrectly, perhaps?)...
And here is the actual site:
http://www.abveaspirations.com/index.html
And here's my HTML code uploaded to the server via FTP:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id='frame'>
<div id='display'>
<h1 id='output'></h1>
</div>
</div>
<div class="spacer">
</div>
<div id="main"> <!-- 11main -->
<h1 id='consoleTitle'>Control Board</h1>
<h5 id='consoleSub'><i>Double-click on an entry to remove. And add entries to your heart's desire...</i></h5>
<div id="controlbox"> <!-- ##controlbox -->
<div id="controlpanel"></div>
<div class="spacer"></div>
<div id="formula"> <!--formula -->
<form id="frm" method="post">
<input id="txt" type="text" placeholder="Insert your own entry here..." name="text">
<input id='submitBtn' type="submit" value="Start">
<input id='stop' type="button" value="Stop">
<select id="load1">
<option id='pre0' value="Preset 0">Preset 0</option>
<option id='pre1' value="Preset 1">Preset 1</option>
<option id='pre2' value="Preset 2">Preset 2</option>
</select>
<!-- These are for buttons as opposed to OPTION...
<input id="load" type="button" value="Preset 1">
<input id="load2" type="button" value="Preset 2"-->
</form>
</div> <!-- formula -->
</div> <!-- ##controlbox -->
</div> <!-- 11main -->
</body>
And my JS code, also uploaded to server via FTP (I didn't include the accompanying CSS file, but if that would help, I can provide ):
$(document).ready(function () {
var txtBox = $('#txt');
var frm = $('#frm');
var output = $('#output');
var subBtn = $('#submitBtn');
var stopBtn = $('#stop');
var loadBtn = $('#load');
var loadBtn2 = $('#load2');
var loadBtnA = $('#load1');
var pre0 = $('#pre0');
var pre1 = $('#pre1');
var pre2 = $('#pre2');
var txt = $('#display');
var preset1 = ["1", "2", "3"];
var preset2 = ["a", "b", "c"];
var container = ["What we do in life echoes in all eternity.", "Find your purpose and give it life.", "When you work your hardest, the world opens up to you."];
var console = $('#controlpanel');
var oldHandle;
function loadPreset0() {
container = [];
console.empty();
container = ["What we do in life echoes in all eternity.", "Find your purpose and give it life.", "When you work your hardest, the world opens up to you."];
updateConsole();
};
function loadPreset1() {
container = [];
console.empty();
container = preset1;
updateConsole();
};
function loadPreset2() {
container = [];
console.empty();
container = preset2;
updateConsole();
};
$(pre0).data('onselect', function() {
loadPreset0();
});
$(pre1).data('onselect', function() {
loadPreset1();
});
$(pre2).data('onselect', function() {
loadPreset2();
});
$(document).on('change', 'select', function(e) {
var selected = $(this).find('option:selected'),
handler = selected.data('onselect');
if ( typeof handler == 'function' ) {
handler.call(selected, e);
}
});
function updateConsole() {
for (var z = 0; z < container.length; z++) {
var resultC = container[z];
var $initialEntry = $('<p>' + '- ' + resultC + '</p>');
console.append($initialEntry);
};
};
updateConsole();
frm.submit(function (event) {
event.preventDefault();
if (txtBox.val() != '') {
var result = txtBox.val();
container.push(result); //1.
var resultB = container[container.length-1];
var $entry = $('<p>' + '- ' + resultB + '</p>');
console.append($entry); //2.
}
var options = {
duration: 5000,
rearrangeDuration: 1000,
effect: 'random',
centered: true
};
stopTextualizer();
txt.textualizer(container, options);
txt.textualizer('start');
txtBox.val('');
});
$("#controlbox").on('dblclick', 'p', function() {
var $entry = $(this);
container.splice($entry.index(), 1);
$entry.remove();
});
function stopTextualizer(){
txt.textualizer('stop');
txt.textualizer('destroy');
}
$(stopBtn).click(function() {
stopTextualizer();
});
});
Any help would be appreciated. I guess I'm just not sure what to do after uploading the html file to the server via ftp. Or maybe I did that correctly and there's something wrong with my code that I'm overlooking. Basically I'm lost. So help please!
You forgot to load jQuery. Make sure that you use <script src="../path-to-jquery/jquery.js"></script> before you load your script.js script.
Also, I noticed that you're loading your scripts in the head tag. This is bad practice, load them right before </body>.
I believe your site is missing jQuery. Add this to the top of your code to hotlink to google's jQuery.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>