Creating a dependant picklist in Javascript survey monkey api - javascript

I'm using the survey monkey PHP API to retrieve a list of surveys in the account. Passing in a $params variable, I can retrieve the survey ID and the survey name. Using the response, I am building two separate picklists as shown below:
function build_picklist($survey, $name) {
global $workbooks;
$picklist = "<select name=\"{$name}\">";
$picklist. = "<option value=\"\" selected=\"selected\">Select...</option>";
foreach($survey['data']['surveys'] as & $entry) {
if ($name == 'survey_list') {
$entry = $entry['title'];
} else {
$entry = $entry['survey_id'];
}
$label = htmlentities($entry);
$picklist. = "<option value=\"{$entry}\">{$label}</option>";
}
$picklist. = "</select>";
$workbooks - > log('Picklist HTML', $picklist);
return $picklist;
}
This works nicely and my form displays a list of surveys on the account and another list of the id's for those surveys. Using the code below:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#integrate_button").click(function(){
$(this).val("Integrating...")
});
});
</script>
</head>
<link rel="stylesheet" type="text/css" href="https://secure.workbooks.com/resources/=UzN4IDN/survey_monkey.css">
<title>Integrate with Survey Monkey</title>
<body>
<div id="container" align="center">
<div id="header">
<img src="https://secure.workbooks.com/resources/=UzN4IDN/sm_logo.jpg" height="100" width="200"/>
</div>
<div id="nav">
<p>Below is a list of the Surveys on your account. Pick one to integrate with.</p>
</div>
<div id="section1">
<form method="POST" action="https://secure.workbooks.com/process/=gTOwIjN/Survey_Monkey" id="pg2_form">
<p>Which Survey would you like to integrate Workbooks with?<p>
<p>{$survey_picklist}</p>
<p>Survey ID: <p>
<p>{$survey_id}</p>
</form>
</div>
<div id="section2">
<p><input type="submit" name="integrate" id="integrate_button" form="pg2_form" value="Integrate with Survey Monkey"/></p>
</div>
</div>
</body>
</html>
What I'd like to do is link the two together so when I select an option in the survey name field, it shows the corresponding ID for that survey in the other picklist.
My guess is I'd need to use Jquery/JS to achieve this but I can't seem to find any useful examples on the internet.
I'm new to Jquery/JS and don't really know how to use it that much, things I've done in the past have worked by pure fluke! Please be nice! :)

Related

Styling a json list

how do i style my json list to material cards?
My json/javascript:
$(document).ready(function(){
var url="getjson.php";
$.getJSON(url,function(data){
console.log(data);
$.each(data.bananas, function(i,post){
var banana =
"<div>"
+"<h3>"+post.name+"</h3>"
+"<h5>"+post.type+"</h5>"
+"</div>";
$(banana).appendTo("#banana-data");
});
now im trying to display it as a nicelt style list of cards but im struggling:
<div class="row">
<div class="col-md-4">
<div id="banana-data" class="box box-widget widget-user">
<div class="widget-user-header bg-aqua-active">
<h3 class="widget-user-username"></h3>
<h5 class="widget-user-desc"></h5>
</div>
</div>
</div>
</div>
But my content appears outside the style of my
I tried using list as follows:
<ol id="banana-data">
<div class="row">
<div class="col-md-4">
<div class="box box-widget widget-user">
<div class="widget-user-header bg-aqua-active">
<h3 class="widget-user-username"></h3>
<h5 class="widget-user-desc"></h5>
</div>
</div>
</div>
</div>
</ol>
var banana =
"<ol>"
+"<h3>"+post.cname+"</h3>"
+"<h5>"+post.sub_type+"</h5>"
+"</ol>";
$(banana).appendTo("#banana-data");
});
The content displayed inside my style,but the entire list of items in the json file was sitting on the same card,and not separating to create multiple styled cards.
this is my php file that converted the data in the msqli table to json:
<?php
require_once 'dbconfig.php';
$posts = array();
$query = "SELECT * FROM bananas";
$stmt = $db_con->prepare($query);
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
$posts['bananas'][] = $row;
}
echo json_encode($posts);
?>
I think you have not append it.You have to use after() method like this..
$("#banana-data").after(banana);
So change your script:
$(document).ready(function(){
var url="getjson.php";
$.getJSON(url,function(data){
console.log(data);
banana = "";
$.each(data.bananas, function(i,post){
banana +=
"<div>"
+"<h3>"+post.name+"</h3>"
+"<h5>"+post.type+"</h5>"
+"</div>";
});
$("#banana-data").after(banana);
Very Good Question:
There are multiple libraries you can use for parsing and styling json:
Handlebars is a library that allows you to parse your json with ease and include each json object in your html
The other one is Moustache.But my solution for you is handlebars.
First turn your json into an actual jsonfile as follows...
$json_data = json_encode($posts);
file_put_contents('ldt.json', $json_data);
Add those two lines in your php instead of your echo.ldt is the filename,you can call it whatever you want.
Nextstep:parse the json file using handlebars..
var yourRequest = new XMLHttpRequest();
yourRequest.open('GET', 'ldt.json');
Then in handlebars on create a function and..instruct handlebars to generate html(myhtml) of parsed json and assign it to an id called:eg mycontainer:
var rawTemplate = document.getElementById("thisTemplate").innerHTML;
var myContainer = document.getElementById("my-container");
my.innerHTML = ourGeneratedHTML;
Then in your html:
<div id="my-container"></div>
<script id="thisTemplate" type="text/x-handlebars-template">
//And here call your objects:Example
{{#each bananas}}
<div class="col-md-4">
<div class="box box-widget widget-user">
<div class="widget-user-header bg-black" style="background: url('{{img}}'>) center center;">
<h3 class="widget-user-username"><b>{{name}}</b></h3>
<h5 class="widget-user-desc">({{type}})</h5>
Just make sure your css actually creates your so called cards etc..and your card list will populate your page exactly as you have styled it with all the objects youve parsed.
Ive simply added small snippets of code.For more information,check out:
Handlebars
Theres nothing wrong with just using ajax and create your own elements,but if you want to kill two birds with one stone,use libraries.
There are also alot of tuts on youtube you can watch.I hope this helps

Import a variable from one page to another in PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
im making an autocomplete search box that lists different courses, and basically what im trying to do is use a search button next to it to display the results of the selected course on another page using an SQL database. The page looks something like this: index.php
So whatever choice you pick from the autocomplete, I then want the "Search Courses" button to link to another page and immediately display the results of that selected course in the search box from the page before. These results will be pulled from an SQL database.
Im basically having trouble linking everything up and can't figure it out.
This is my search box and button:
<div class="row">
<div class="ui-widget col-md-4 col-md-offset-4">
<label for="tags">Search: </label>
<input id="tags" type="search">
<input type="submit" value="Search Courses">
</div>
</div>
Do I need to set some sort of variable to pass on to the next page?
Appreciate any help, thanks.
This is my autocomplete.php file:
<?php
$mysqli = new mysqli("localhost", "scott", "tiger", "courses");
$term = mysqli_real_escape_string($mysqli,$_REQUEST['term']);
$query = "
SELECT title
FROM course
WHERE title LIKE '$term%'
ORDER BY title";
$return = array();
$result = $mysqli->query($query);
while ($row = $result->fetch_array()){
array_push($return,$row[0]);
}
echo json_encode($return);
?>
index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Edinburgh Napier University</title>
<div class="row">
<div class="col-md-4 col-md-offset-4">
<img id="napierlogo" src="logo.jpg"/>
</div>
</div>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#tags" ).autocomplete({
source: "autocomplete.php",
autoFocus:true
});
});
</script>
<script>
$(function() {
$( "#menu" ).menu();
});
</script>
<style>
.ui-menu { width: 150px; }
</style>
<script>
$(function() {
$( "input[type=submit]" )
.button()
.click(function( event ) {
event.preventDefault();
});
});
</script>
<?php
isset($_GET['res'])?$var=mysql_escape_string($_GET['res']):$res='';
?>
</head>
<body>
<p></p>
<div class="row">
<div class="ui-widget col-md-4 col-md-offset-4">
<label for="tags">Search: </label>
<input id="tags" type="search">
<input type="submit" value="Search Courses">
</div>
</div>
<p></p>
<ul id="menu">
<li><a href="http://socwebtech1.napier.ac.uk/~40171342/course/index.php">Search</li>
<li>myNapier</li>
<li>Contact Us
<ul>
<li><a href="https://www.facebook.com/EdinburghNapierUniversity/">Facebook</li>
<li><a href="https://twitter.com/EdinburghNapier? ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Twitter</li>
<li><a href="https://uk.linkedin.com/edu/edinburgh-napier-university-12617">LinkedIn</li>
</ul>
</li>
</ul>
</body>
</html>
First, if it's not already, your index page needs to be a .php file instead of .html.
Second, you need to modify your search box to be a form that submits when you click the search button. This will send a POST request to the results.php page that can then load the results from the database using the search term that was entered in the textbox.
Your textbox html code should become:
<div class="row">
<form action="results.php" method="post">
<div class="ui-widget col-md-4 col-md-offset-4">
<label for="tags">Search: </label>
<input id="tags" type="search" name="search">
<!-- Added the 'name' attribute ^ here
we'll need this later in the PHP file -->
<input type="submit" value="Search Courses">
</div>
</form>
</div>
And results.php should have some PHP code at the top similar to this:
<?php
$searchTerm = $_POST["search"];
// Key part -> ^ ^
// this needs to match the name of the search box in html
// TODO -- Sanitize this input (NEVER trust user input)
// using mysqli_real_escape_string() or similar.
// Then use it to perform your search
// Just for testing:
echo $searchTerm;
More information on $_POST is available here: http://php.net/manual/en/reserved.variables.post.php
As a side note, you should really be using PDO for database access. It has a load of great features, including "prepared statements" which help prevent against SQL Injections. That, and it's best practise and it's good for future maintainability.
More info here: http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
When using the JQuery autocomplete with AJAX, the source request is a GET. Try changing your variable to $_GET['term'] and giving you input box a name="term". And then change your function to something like this.
$(document).on("ready",function() {
$( "#tags" ).autocomplete({
source: "autocomplete.php",
autoFocus:true
});
});
edit: You are also missing closing tags on some of the links. I would suggest tidying up your HTML code.

jQuery not extracting text values clicked properly

I am using a php script to extract values from the database as follows,
<div class="col-md-4" >
<?php
$qry = "SELECT * FROM upperbit_categories";
$rslt = mysqli_query($dbc,$qry);
while ($output = mysqli_fetch_array($rslt)) {
?>
<li class="nav" id="test" style= "text-decoration: none;">
<a href="postad" >
<?php echo $output['Classify'].'<br/>'; } ?>
</a>
</li>
</div>
<div class="col-md-4" id="testing">
</div>
this code gives me below result:
General equipment
Test equipment
Renewable energy
Engineering Services
Trade services
Below is the jQuery bit:
<script>
$(document).ready(function(){
$("#test").click(function(){
var classprod = $(this).text();
$("#testing").text(classprod);
event.preventDefault();
})
});
</script>
However this only outputs line-1 but nothing else i.e. General equipment.
What changes do I have to make to my javascript code in order to be able to display any item clicked?
Little errors, but easy to solve. Your php loop leave a lot of tags opened, an closes just one, then you should use a Class instead on an Id for multiple elements.
Another tip is that you should open and close the ul tag before your list.
HTML
<div class="col-md-4" >
<ul>
<?php
$qry = "SELECT * FROM upperbit_categories";
$rslt = mysqli_query($dbc,$qry);
while($output = mysqli_fetch_array($rslt)){?>
<li class="nav test" style= "text-decoration: none;"><a href="postad" ><?php echo $output['Classify'];?></a></li>
<?php };?>
</ul>
</div>
<div class="col-md-4" id="testing"></div>
JS
<script>
$(document).ready(function(){
$(".test").on('click',function(event){
event.preventDefault();
var classprod = $(this).text();
$("#testing").text(classprod);
})
});
</script>
Also, I don't know what you're doing, but consider to use $(".test a") instead of $(".test")
In General, id of HTML elements should be unique, this requirements can be realized when using jQuery or JavaScript. In your code, you used id="test" for the li element inside a loop, and then you referenced to them using $("#test") then, only first li works due to uniqueness of id.
you can use class instead of id.

How to add to html <a> tag onclick event with PHP and call the function in JavaScript file

This question maybe is little bit strange but I need to learn it asap.
I have a HTML file which is called upgrade.view.php here is the piece of code that I am on working on:
<form role="form" method="get" action='index.php?action=Frontend_upgradeChosen'>
<div class="col-md-5">
<ul name="S_PRODUCT" id="S_VARIABLE">
<?php
if (isset($oldProduct) && isset($arrayUpgrade)){
foreach ($arrayUpgrade as $value) {
$pro = $value->getnewProduct(); //
echo '<li>'.$pro->getName().'</li>';
}
?>
</ul>
</div>
</form>
</div>
//which closes the main DIV
<script type="text/javascript" language="javascript" src="<?= PATH_VIEWS_INCLUDES_URL ?>js/upgrade/upgrade.js"></script>
On the other hand I am trying to call the JS function from upgrade.js where I have this function:
function searchSN(elem) {
var a = elem.innerHTML;
alert(a);
}
Finally in my separated PHP file I have this function:
public function upgradeChosen() {
$selectedVariable = $_GET['S_PRODUCT'];
echo 'The Price is:'." ". $selectedVariable;
include $this->getPrintedView();
}
As updated version of the question I am getting the on click event from the <A> tag but not the value the value of says undefined value.
I have updated the question so that maybe it makes it more understandable what I am trying to achieve.
Many Thanks in Advance
something like this ?
function searchSN(elem) {
var a = elem.innerHTML;
alert(a);
}
<form class="" role="form" method="get" action='index.php?action=Frontend_upgradeChosen'>
<div class="col-md-5">
<ul name="S_PRODUCT" id="S_VARIABLE" >
<li>test</li>
</ul>
<button id='choose_product' type="submit" class='btn btn-default'><i class='icon-rocket'>Submit</i></button>
</div>
</form>

Updating span with jQuery, fetching it with PHP?

I have a jQuery-script that updates a span when the user clicks on different buttons. It updates and displays as desired.
But I want to fetch this "variable" with PHP and input it into a file.
When the document loads the value of the span is 0, and gets higher as the user click specific buttons. When I write the value of the span to my text file it is always 0. Help?
jQuery:
$(".button").click(function()
{
$(this).addClass("button-clicked");
$(this).siblings(".button").addClass("disabled");
$(this).siblings(".rett").addClass("rett-ved-feil");
$(this).unbind("click");
$(this).siblings(".button").unbind("click");
if($(this).hasClass("rett"))
{
rettVar++;
$("#antall-rett").html(rettVar);
$("#score").html(rettVar);
$(this).addClass("button-clicked-riktig");
}
});
PHP:
if (isset($_POST["submit"]))
{
$doc = new DOMDocument;
$doc->loadHTMLFile('index.php');
$node = $doc->getElementById('score');
$score = $node->nodeValue;
$fil = fopen("score.txt","a");
$loglinje = $_POST["navn"] . ": " . $score;
fwrite ($fil, $loglinje . "\n");
fclose($fil);
}
HTML:
<!doctype html>
<title>Huskampanje Quiz</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="mediaqueries.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<script src="js/jquery-1.11.2.js" type="text/javascript"></script>
<script src="js/myjs.js" type="text/javascript"></script>
<script src="js/scrollToggle.js" type="text/javascript"></script>
<section class="section" id="intro">
<div class="content">
<h1>Huskampanje quiz<br /><span class="handsome">Ta quizen her</span></h1>
</div>
<img src="img/pil.png" id="pil" />
</section>
<section class="section" id="håndverker-section">
<div class="content">
<p>
Når det gis et prisoverslag på en håndverkertejeneste kan endelig pris maks overstige..
</p>
<span class="button">5%</span>
<span class="button">10%</span>
<span class="button rett">15%</span>
<span class="button">20%</span>
<span class="steps">4/10</span>
</div>
</section>
<section class="section" id="naturskade-section">
<div class="content">
<p>
Ved påsketider har snøen ligget en stund på hyttetak, og oppnår høyere egenvekt enn når den er fersk. Om vi har et
hyttetak på 100 kvadratmeter og snødybden er 1 meter vil vekten av snøen være omlag..
</p>
<span class="button rett">30 tonn</span>
<span class="button">10 tonn</span>
<span class="button">5 tonn</span>
<span class="button">20 tonn</span>
<span class="steps">10/10</span>
</div>
</section>
<ul id="sticky">
<li id="header-sticky">Antall rett</li>
<li id="antall-rett">0</li>
</ul>
<section id="resultat">
<div class="content" id="resultat-content">
<div class="score">
<span id="score">0</span>
<form action="index.php" method="post">
<input type="text" name="navn">
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST["submit"]))
{
$doc = new DOMDocument;
$doc->loadHTMLFile('index.php');
$node = $doc->getElementById('score');
$score = $node->nodeValue;
$fil = fopen("score.txt","a");
$loglinje = $_POST["navn"] . ": " . $score;
fwrite ($fil, $loglinje . "\n");
fclose($fil);
}
?>
</div>
</div>
</section>
As they told you, Javascript is client side while PHP is server side.
This means that what in client side happends, stays there and server doesn't care at all. If you want to update your file with the value, you got two ways to do it.
1.AJAX, send the value async to a php file and write the value desired into your file/database...
2.Make a form and retrieve the data and save it where you want. For this, make hidden inputs for example that will increment with every click.
Edit: for number 2, if you have multiple pages, you can have an input hidden with name, for example: "right_answers"
<form>
...
<!-- first page -->
<input type="hidden" name="right_answers" value="0">
...
</form>
Then in the next page, at the start, check if the answer is correct:
<?php
if($_POST['question'] == "answer") {
$goodAnswer = $_POST['right_answers']+1;
}
else {
$goodAnswer = $_POST['right_answer'];
}
?>
<form>
...
<input type="hidden" name="right_answers" value="<?php echo $goodAnswers; ?>">
...
</form>
This way you will always know the correct answers the user made. It's just an idea, sure there are better ways.
Your PHP script (file) will run on your server. The user, who has opened your webpage somewhere in the world, can't and never should see or alter your server-side files, like your PHPs. Every user who opens your webpage sees the same PHP, so if 5 users are browsing your page, they are all see the content that index.php has generated for them. The output of your PHP file (a HTML code) will be in their browsers (in the users computer's memory), and you can modify it with jQuery. It will always remain in the memory of the users' computer. So if you want to save something a user typed, you have to send it back to your server and here a PHP can catch it and save it for you. But it's not a good idea to save it to a file, since if 5 users sending back data, you should save 5 separate files for them (and you have to identify all users). But the basics are here:
You have to make a PHP file that can catch your input, save it as ajax.php:
<?php
$fil = fopen("score.txt","a");
$loglinje = "score:".$score;
fwrite ($fil, $loglinje . "\n");
fclose($fil);
?>
Then you have to send the data back to the server, so your jQuery code should something like that:
<script>
$(".button").click(function()
{
$(this).addClass("button-clicked");
$(this).siblings(".button").addClass("disabled");
$(this).siblings(".rett").addClass("rett-ved-feil");
$(this).unbind("click");
$(this).siblings(".button").unbind("click");
if($(this).hasClass("rett"))
{
rettVar++;
$.ajax({
url: '/ajax.php',
type: 'post',
dataType: 'json',
data: {
score: rettVar
}
})
.always(function() {
})
.fail(function() {
alert('There is an error occured.');
})
.done(function(result) {
$("#antall-rett").html(rettVar);
$("#score").html(rettVar);
$(this).addClass("button-clicked-riktig");
});
}
});
</script>
So this way the jQuery send back the score to the server, which is save it to you.
I hope it helps, but please consider, this code is only an example. I DO NOT recommend it to use in real-world application, since it has some security backdraws and maybe you should save the values to a database rather than a text file.

Categories

Resources