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

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.

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

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>

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

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.

Displaying jQuery checkbox selection

This web page is currently displaying data from an "all" category from an rss feed once the page is loaded. My question is there are several categories which I would like the user to select and display. There are a total of 10 categories, and each correspond to a separate rss feed. Can anyone explain how I handle this event? Also, if one of the categories is selected, will it automatically override the current data being displayed? I will elaborate any unclear parts if needed. Thank you!
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: 'GET',
url: '/example',
dataType: 'xml',
success: function (xml) {
$(xml).find("item").each(function () {
var title = $(this).find("title").text();
var description = $(this).find("description").text();
var linkUrl = $(this).find("link").text();
//var link = "<a href='" + linkUrl + "' target='_blank'>Read More<a>";
var displaytitle = "<a href='" + linkUrl + "' target='_blank'>" + title + "</a>"
$('#feedContainer').append('<h3>'+displaytitle+'</h3><p>'+description+'</p>');
});
}
});
});
</script>
</head>
<body>
<div data-role="page" id="page">
<!-- /field panel -->
<div data-role="panel" id="fieldpanel" data-position="left" data-display="push">
<ul data-role="listview" data-inset="true" data-filter="false">
<fieldset data-role="controlgroup">
<legend>Categories</legend>
<input type="checkbox" name="checkbox-bio" id="checkbox-bio">
<label for="checkbox-bio">Bioengineering</label>
<input type="checkbox" name="checkbox-com" id="checkbox-com">
<label for="checkbox-com">Communications</label>
<input type="checkbox" name="checkbox-eleP" id="checkbox-eleP">
<label for="checkbox-eleP">Electrical/Power</label>
<input type="checkbox" name="checkbox-eleD" id="checkbox-eleD">
<label for="checkbox-eleD">Electronics/Design</label>
<input type="checkbox" name="checkbox-nano" id="checkbox-nano">
<label for="checkbox-nano">NanoEngineering</label>
<input type="checkbox" name="checkbox-opt" id="checkbox-opt">
<label for="checkbox-opt">Optics/Display</label>
<input type="checkbox" name="checkbox-semi" id="checkbox-semi">
<label for="checkbox-semi">Semiconductors</label>
</fieldset>
</ul>
</div><!-- /field panel -->
<!-- /settings panel -->
<div data-role="panel" id="settingspanel" data-position="right" data-display="push">
<ul data-role="listview" data-inset="true" data-filter="false">
<li>Join IEEE</li>
<li> subscription services</li>
</ul>
</div><!-- /settings panel -->
<div data-role="header" data-theme="b">
Menu
Settings
<h1>MOBILE</h1>
</div>
<div data-role="content">
<div id="feedContainer"></div>
<h3></h3>
<p></p>
</div>
<div data-role="footer">
<h4>Advertisements</h4>
</div>
</div>
</body>
</html>
I will assume you want to get the basic information about this code!
Ok, the first thing to handle is the type of the data to be shown.
<input type="checkbox" id="1" />
<input type="checkbox" id="2" />
Lets start with 2 instead of 10! The jQuery code for this would be easy to understand.
$('input[type=checkbox]').click(function () { // click on checkbox
var val = $(this).attr('id'); // get its id as value
if(val == '2') {
$('someelement).html('2 was selected');
$('#1').prop('checked', false); // unselect the other one
}
}
So, this is the basic code which will execute when a click event occurs on a checkbox. Now in your code you'll be using something like ajax then add the ajax request code before the .html() thing and write the response there.
To update the content being displayed you will be needed to use only one element as the basic clipboard for your app. Why? Because everytime you will get the data, you will be needed to replace the current content with that one and this way you will get only the current data; the selected data.
Lets try one checkbox from your code:
<input type="checkbox" name="checkbox-bio" id="checkbox-bio">
<label for="checkbox-bio">Bioengineering</label>
<input type="checkbox" name="checkbox-com" id="checkbox-com">
<label for="checkbox-com">Communications</label>
Now lets handle the jQuery
$('input[type="checkbox"]').click(function () {
// and all others will be here just as they are.. to check the id
// your ajax request is perfect, just copy paste that here..:)
});
But just need to make a change there, instead of sending the same request try to add one more thing there,
$.ajax({
// url and datatype here,
data: value
// success function goes here
});
Note that the value was the variable that we took from the checkbox. Which will be sent with the request so that you can process only the necessary part of the RSS and leave all other, just like an if else block.
Here is a working fiddle for this http://jsfiddle.net/afzaal_ahmad_zeeshan/KU9JT/.
But I am sorry, I didnot include the if else block to make the code work as it was meant to be. But you'll understand how to manipulate this.

Categories

Resources