Updating span with jQuery, fetching it with PHP? - javascript

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.

Related

PHP Session loses value after SECOND redirect

After combing through SO and trying the approved suggestions found here, my related problem persists. My page starts with a simple login and then you navigate to other potential pages through drop down menus. When I redirect from the index page to a welcome page, I can recall values from my $_SESSION array on to the welcome page. The problem is when you navigate to another page after after that point. The content of the $_SESSION array gets erased. Even if I reload the same page that already has a return from the $_SESSION array, the array gets erased.
I use XAMPP OSX, php 7.9.2 and localhost on my own computer. I've restarted XAMPP. I've emptied cache and restarted my browser. I've tried other browsers. I've rebooted my computer.
Is there something I can do with my server settings? What could be the source of my problem?
What is very strange is that the issue came out of the blue. I was able to preserve $_SESSION with no problems weeks before and all of a sudden it began to drop its values.
Update 1
So I've made some changes to my code below to have a separate AJAX page and php pages to really clarify what I'm doing. The problem seems to have improved with what I did. HOWEVER, there still remains some mysteries:
1) On log out, I get a warning from my AJAX output that the SESSION variable doesn't exist. This is strange as I am able to print out my session content from my php pages when I've logged in and I navigate to other pages.
2) I am unable to make a simple function call (an alert popup) when my footer loads for every page. This alert popup is on the same page as AJAX functions (which seem to work), but the popup doesn't pop.
Header
<?php session_start() ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>test site</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet "href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="row">
<div class="container col-xs-12" id="OPheader">
<div id="logoText">
<p>
Test Pages
</p>
</div>
Navigation Menus
<div class="btn-group menuButton ">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
So what you wanna do? <span class="caret"></span>
</button>
<ul class="dropdown-menu" id="daMenu">
<li>Continue procrastination</li>
</ul>
</div>
<!-- ============ user personal menu ====== -->
<div class="btn-group userMenuButton ">
<button type="button" class="btn btn-default dropdown-toggle" id="userMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<label id="user-name-icon" >Your name</label>
<!-- Insert user name from database here -->
<span class="caret"></span>
</button>
<ul class="dropdown-menu" id="daUserMenu">
<li>Order another pizza</li>
<li role="separator" class="divider"></li>
<li><a onclick="javascript: killSession();" >Log Out</a></li>
</ul>
</div>
Index page
<?php include("testHeader.php"); ?>
<?php include("testIndexTools.php"); ?>
</div>
</div>
<!--
====================== Login Fields ======================================
-->
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="well" id="loginBox">
<div>
<div id="loginErrorMsg" ></div>
<form method="POST" action="">
<div class="enterBox">User: <input type="text" name="user_name" placeholder="uh... who?" >
</div>
<br>
<div class="enterBox">Password: <input type="text" name="user_pw" placeholder="Don't mess this up" >
</div>
<br>
<div >
<input class="btn btn-primary submitText" type="submit" name="login_submit" value="Submit your soul">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var error = "Login unsuccessful. Please re-enter credentials.";
var disp = document.getElementById('loginErrorMsg');
function showError(){
disp.innerHTML = error;
}
</script>
<?php include("testFooter.php"); ?>
</body>
</html>
PHP Tools for Index page
<?php
$errors = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
list($errors) = validate_form(); // check for blank input fields
if ($errors) { // If validate_form() returns errors,
show_errors($errors); // show error messages
} else {
process_form();
}
}
// on succesful login, this function is called to redirect page
function process_form(){
session_start();
$_SESSION['logged_user'] = htmlentities($_POST['user_name']);
if (isset($_SESSION['logged_user'])){
session_regenerate_id(true);
header("Location: /OPsite/SOmock/testHomePage.php");
exit();
} else {
echo "Session wasn't set so not redirecrting";
exit();
}
}
function show_errors($errors){
echo '<script type="text/javascript"> showError(); </script>';
}
// validate your data
function validate_form(){
$errors = array();
$userCu = trim($_POST['user_name'] ?? '');
$userPw = trim($_POST['user_pw'] ?? '');
if (strlen($userCu) == 0){
$errors[] = "Please enter name";
return $errors;
} else if (strlen($userPw) == 0) {
$errors[] = "Please enter password";
return $errors;
}
}
?>
Welcome page
<?php include("testHeader.php"); ?>
<?php include("testMenu-bar.php"); ?>
<?php include("testWelcomePageTools.php"); ?>
</div>
</div>
<!-- ================================= welcome Page =============== -->
<div class="row" id="homePage">
<div class="container ">
<h1> Stop procrastinating and get back to work</h1><br>
</div>
</div>
<?php include("testFooter.php") ?>
</body>
</html>
PHP tools for Welcome Page
<?php
// AJAX call to set name from HomePage
if (isset($_POST['sessName'])){
// $_SESSION['logged_user'] = htmlentities($_POST['user_name']); // user-icon name set here
$userName = $_SESSION['logged_user'];
// echo $_SESSION['logged_user'];
echo "Session data exists<br>";
echo $userName;
// print_r($_SESSION); // when homePage loads, this is to check array
// echo "sessName";
} else {
$noSession = "No session data<br>";
echo $noSession;
print_r($_SESSION);
}
?>
other page to navigate to
<?php include("testHeader.php"); ?>
<?php include("testMenu-bar.php"); ?>
<?php
echo "this is the testSession Page<br>";
print_r($_SESSION);
?>
<?php include("testFooter.php") ?>
</body>
</html>
Footer
<script type="text/javascript" src="testFooterJS.js">baba();</script>
<!-- === log out behavoiur ============== -->
<?php
// AJAX call to kill session
if (isset($_POST['killSess'])){
unset($_SESSION['logged_user']);
session_destroy();
$_SESSION = array();
exit();
}
?>
javascript/AJAX page for logging in/out
//====== AJAX log in behaviour ==========
function sessionName(){
alert("name calling");
$.ajax({
type: 'post',
url: 'testHomePageTools.php',
data:'sessName', // in PHP page, this will correspond with: $_POST['action'] == 'fillMenu'
dataType: 'text',
success: function (data) {
alert("Your name" +data);
var userName = data;
var icon = document.getElementById('user-name-icon');
icon.innerHTML = "You are logged in as: " + userName;
alert("You are logged in as: " + userName);
},
error: function(data){
alert("something's gone wrong on entry");
console.log(data);
// alert(data);
}
});
};
//====== AJAX log out behaviour ==========
function killSession(){
$.ajax({
type: 'post',
url: 'testFooter.php',
data:'killSess', // in PHP page, this will correspond with: $_POST['action'] == 'fillMenu'
dataType: 'text',
success: function (data) {
console.log(data);
alert("Bye bye");
window.location = "http://localhost/OPsite/SOmock/testIndex.php";
},
error: function(data){
alert("something's gone wrong on exit");
console.log(data);
// alert(data);
}
});
};
// ============= test to see if footer loads ===========
function baba(){
alert("footer loaded");
};
I figured out my problem. After my code updated as posted, I discovered that my problem was that I thought that having session_start() on my header would address and cover all the pages that included the header. This is not the case. The session_start() has to be on literally every php page that refers to $_SESSION super global. This was not very clear on my research, but through trial and error I figured it out.
Thanks

Ajax Tabs for Wordpress that loads and runs different shortcodes when user changes the tab

How does one execute a shortcode, which is placed in a tab, only when the user clicks on the Tab's Title. How do we do this for five tabs? MY objective is to reduce load time of me website. So, only that content which the user wants must load when he clicks on the tab.
I'm fairly certain the best way to do this is by utilizing Wordpress's admin-ajax.php. I've searched a great deal. And I've found most of the code (I think) to create the AJAX tabs. But, when I fire the code it doesn't show up. Rather the HTML shows us, the AJAX doesn't.
$(document).ready(function() {
$('.my_tabs a').click(function(e) {
e.preventDefault();
var tab_id = $('this').attr('id');
$.ajax({
type: "POST",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({
action: 'my_tab_menu',
id: tab_id
}),
success: function(data) {
$('#my_tab' + tab_id).html(data);
},
error: function(data) {
alert("Error!");
return false;
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my_tabs">
Tab 1
Tab 2
Tab 3
Tab 4
Tab 5
</div>
<div class="my_section" id="my_tab1">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<div class="my_section" id="my_tab2">
<?php echo do_shortcode ('[shortcode-2]'); ?>
</div>
<div class="my_section" id="my_tab3">
<?php echo do_shortcode ('[shortcode-3]'); ?>
</div>
<div class="my_section" id="my_tab4">
<?php echo do_shortcode ('[shortcode-4]'); ?>
</div>
<div class="my_section" id="my_tab5">
<?php echo do_shortcode ('[shortcode-5]'); ?>
</div>
I add all the code directly into the page using a page-builder. So, I'm not using functions.php to add_action for this particular tab that I'm trying to implement.
I found all the code from a similar post on stackover:
Ajax tabs (wordpress)
They call template_parts into the tabs. Where as I want to execute a shortcode.
I'm what you'd call a coding bimbo. All help shall be much appreciated.
Thank you. And if you've managed to read till here, you deserve to have a pleasant day. :D
Okay, so you can't achieve it the way you have laid your template. As soon as you echo the shortcode and the browser renders the page, the shortcode contents must have printed. You need to create a custom-page-template.php, create a page and on that page you need to send the shortcode handler as soon as you click on the tab through GET or POST method using ajax.
In your Custom Template you receive the [shortcode-1]. An example code would be like you see below:
<?php
/*
Template Name: Shortcode Processor
*/
$current_shortcode = $_POST['shortcode_name'];
?>
<div id="shortcode-contents">
<?php echo do_shortcode($current_shortcode); ?>
</div>
Now you have the response in your Ajax Call. You can now inject the success html inside your desired tab.
Try
<button class="tabs" id="my-tabid1" data-target=".my-section1.box">Tab 1</button>
<button class="tabs" id="my-tabid2" data-target=".my-section2.box">Tab 2</button>
<button class="tabs" id="my-tabid3" data-target=".my-section3.box">Tab 3</button>
<div class="my_section1 box active" id="my-tab1">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<div class="my-section2 box" id="my-tab2">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<div class="my-section3 box" id="my_tab3">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<style>
.box {
display: none;
}
.box.active {
display: block;
}
</style>
<script>
$('.tabs').on('click', function(){
var $target = $($(this).data('target'));
$target.siblings().removeClass('active');
$target.addClass('active');
});
</script>

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.

PHP Code into Javascript

I am using fullcalendar.js and the calendar is working as it should right now. If a user clicks on an entry at the calendar, a modal appears with some information. What I need now is, that those information inside the modal are information from the database, so I would like to insert some PHP code but I have no idea how.
Let me show you which PHP code I would like to use so that the data from my database are displayed at the modal:
<?php
$dates=getPcalInfoOfHour($gl_userid,0,0);
for ($x=0;$x<count($dates["id"]);$x++) {
Title: '".$dates["title"][$x]."';
Selected Date: '".$dates["date"][$x]."';
Selected Time: '".$dates["start"][$x]."' '".$dates["end"][$x]."';
Topic: '".$dates["topic"][$x]."';
Location: '".$dates["location"][$x]."';
Address: '".$dates["address"][$x]."';
}
?>
Here is the part of my Javascript Code where I would like to enter my php code:
eventClick: function(calEvent, jsEvent, view) {
//display a modal
var modal =
'<div class="modal fade">\
<div class="modal-dialog">\
<div class="modal-content">\
<div class="modal-body">\
<button type="button" class="close" data-dismiss="modal" style="margin-top:-10px;">×</button>\
<label> <strong>Topic:</strong> Topic</label>\
<label> <strong>Selected Dated:</strong> Date</label>\
<label> <strong>Selected Time:</strong> Time</label>\
<label> <strong>Title:</strong> Title</label>\
<label> <strong>Location:</strong> Location</label>\
<label> <strong>Address:</strong> Address</label>\
<label> <strong>Phone:</strong> Phone</label>\
</div>\
<div class="modal-footer">\
<button type="button" class="btn btn-sm" data-dismiss="modal"><i class="ace-icon fa fa-times"></i> Close Window</button>\
</div>\
</div>\
</div>\
</div>';
var modal = $(modal).appendTo('body');
modal.modal('show').on('hidden', function(){
modal.remove();
});
console.log(calEvent.id);
console.log(jsEvent);
console.log(view);
}
I know that PHP is a server side language and JavaScript is client based language but there must be a way, that my data from the database will be shown inside the modal am I right? I know a little bit about PHP programming but I never wrote something in JavaScript.
I would really appreciate if someone can tell me what my code should look like so that I get my information from the database inside the modal window.
Thanks,
Chris
I believe this would do:
var js_string = "<?php echo $php_string; ?>";
You have to make request to server to php script what will fetch data from DB and generate html.
Example javascript to use with php generated html for modal:
$.post('/script_generating_html.php', params, function(response) {
var modal = $(response).appendTo('body');
modal.modal('show').on('hidden', function(){
modal.remove();
});
});
Think of it this way. PHP generates what the browser will read before sending anything. So if you had the following code
<?php
$data = "Super Important";
?>
<script>
alert("<?php print $data; ?>");
</script>
It would generate for the client
<script>
alert("Super Important");
</script>
If you're going to be working with modifying javascript with php, also look into json_encode()
as another way to acheive the same thing is
<?php
$data = "Super Important";
?>
<script>
alert(<?php print json_encode($data;) ?>);
</script>

Creating a dependant picklist in Javascript survey monkey api

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! :)

Categories

Resources