Drop down list solution? - php

I am a newby so appologise for asking a basic question.
I have a php page - a 'create new project' page
There are some simple data such as name, deadline etc...
but depending on the type of the project I have 4 different ends (different pages?) in this FORM and I can't find the solution for it.
Here is my code:
<h1>New Project</h1>
<form name="newpr">
New project name:<input type="text" placeholder="new project name..."><br />
New project end date:<input type="text" placeholder="date..."><br />
New project type:
<select name="menu" onChange="location=document.newpr.menu.options[document.newpr.menu.selectedIndex].value;" >
<?php
$listdata = mysql_query("SELECT * FROM lists WHERE tag='prtype' ORDER BY listing ASC");
while($listresult = mysql_fetch_array($listdata))
{
if ($listresult["listing"]!="...") $link=$listresult["value"].".php";
else $link="";
echo "<option value='".$link."'>".$listresult["listing"]."</option> ";
}
?>
</select>
</form>
As you see the select list comes from Mysql and I would like a div under a form to be able to open page1.php or page2.php etc as user selects...
Thanks in advance
Andras
it might be ajax question...

I'd solve this the following way
<!-- using jQuery -->
<h1>New Project</h1>
<form method="" action="post">
New project name:<input type="text" placeholder="new project name..."><br/>
New project end date:<input type="text" placeholder="date..."><br/>
New project type:
<select name="menu">
<?php
$listdata = mysql_query("SELECT * FROM lists WHERE tag='prtype' ORDER BY listing ASC");
while($listresult = mysql_fetch_array($listdata))
{
$link = '';
if($listresult['listing'] != '...') {
$links = $listresult['value'] . ".php";
echo "<option value='$link'>${listresult['listing']}</option>";
}
}
?>
</select>
<div id="page">
<!-- container for loaded page -->
</div>
<script type="text/javascript">
$("select[name=menu]").change(function() {
var url = $("option:selected", this).val();
// Load a page to the container
$("#page").load(url);
});
</script>
</form>
Using jQuery I added on change handler on select box and if it's changed it loads via ajax a page to the div container.
And let me give you and advice - try to avoid mixing code and html. It leads to difficulties in further development and maintenance.

You want to make a HTTP request to your php page Checkout http://mootools.net/docs/core/Request/Request.HTML
http://mootools.net/docs/more/Request/Request.JSONP
Listen for the callback on your request then inject the returned data as an element into the DOM. Mootools is my weapon of choice but Jquery etc. all have this same functionality. call php page under Javascript function This question is very similar to yours.

Related

Taking values from form, pulling results from MySQL, and using AJAX for results

I am having a bit of trouble figuring out how exactly to make a certain connection. It's a project I thought might be simple enough for me to do on my own without help, but I've hit a wall unfortunately. It's an 'exercise generator' that basically asks a few basic questions, and based on your answers, it outputs a recommended workout routine. I've constructed the MySQL database with plenty of exercises, have successfully connected the database, and have made the form.
What I am having trouble though, however, is storing those form results into variables, and based on those variables (if workout days is 3, for example, there would only be 3 groups of workouts printed instead of 5) output a routine into the same div as the form, effectively replacing it with the answer instead of placing it underneath the submitted form.
Index.php
<!DOCTYPE html>
<html>
<?php $page_title = "Workout Generator"; ?>
<link rel="stylesheet" type="text/css" href="style.css">
<head>
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" ></script>
</head>
<body>
<?php include("header.php"); ?>
<?php include("connect.php"); ?>
<div id="appWindow">
<h3>Please answer the following questions and click 'Submit' to generate your workout routine.</h3>
<form id="homeForm" method="post" >
<label for="name">Name: </label>
<input type="text" name="name"><br>
<label for="age">Age: </label>
<input type="number" name="age"><br>
<label for="workoutdays">How many days a week can you workout?</label>
<select name="workoutdays">>
<option value="1">3</option>
<option value="2">5</option>
</select><br>
<label for="workoutstyle">Do you prefer a gym, or bodyweight exercises?</label>
<select name="workoutstyle">>
<option value="1">Gym</option>
<option value="2">Bodyweight</option>
</select><br>
<button type="submit" name="submit">Submit</button>
<button type="reset" name="reset">Reset</button>
<div class="form_result"></div>
</form>
<?php
$age = $_POST['age'];
$workoutdays = $_POST['workoutdays'];
$workoutstyle = $_POST['workoutstyle'];
?>
</div>
<br><br><br>
<?php include("footer.php"); ?>
</body>
</html>
I don't necessarily want an answer giving me the exact code to enter, but would appreciate being pointed in the right direction to get that form pulling data from MySQL, and using AJAX to print in the same window without refreshing.
THANK YOU
First of all, you need to post your request. With $.ajax this
//Do this thing on page load
$(function() {
//handle submit
$("#homeForm").submit(function(e) {
//customize your submit
e.preventDefault();
$.ajax({
type: "POST",
url: youURL, //maybe an url pointing to index.php
data: yourData, //attach everything you want to pass
success: function(response) {
$("#appWindow").html(response);
}
});
});
});
code should help. You need to make sure you pass the necessary elements and you provide the correct url. On server side, generate the desired html and send back as response.
In the script file
$(document).ready(function(){
$(document).on('click','#submit_btn',function(){
var url = '/xyz.php'; //full path of the function where you have written the db queries.
var data = '';//any data that you would like to send to the function.
$.post(url,{data: data}, function(result){
var arr = JSON.parse(result);
});
});
});
in your php file once your database query has been executed and you get the result. for example
$result = //result of your mysql query.
echo json_encode($result);
exit;

How to get ajax commenting system to work from different directory?

I have a page and I am trying to add an ajax commenting system to it. When I put all the code in the /comment directory into root, my new pages can implement the script. However, if I make another directory, say /books, then link to the pages inside the /comment directory, It will not post the comments. I can display them and access the javascript page, but I can't not make new comments. What is causing it to fail. I think it is somewhere in the javascript file... I didn't want to include so much code if you need to see anything else, let me know and I will post it. I will include the php file and the javascript file up one directory, and into another... Any tips would be great. Here is my page:
<?php
// Error reporting:
error_reporting(E_ALL^E_NOTICE);
include('../comments/connect.php');
include($_SERVER['DOCUMENT_ROOT'] . '/comments/comment.class.php');
/*
/ Select all the comments and populate the $comments array with objects
*/
$comments = array();
$result = mysql_query("SELECT * FROM comments ORDER BY id ASC");
while($row = mysql_fetch_assoc($result))
{
$comments[] = new Comment($row);
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../style.css" />
</head>
<body>
<ul id="nav">
<li class="current">Home</li>
<li>
<ul>
<li></li>
</ul>
<div id="container">
<div id="content">
<?php
/*
/ Output the comments one by one:
*/
foreach($comments as $c){
echo $c->markup();
}
?>
<div id="addCommentContainer">
<p>Add a Comment</p>
<form id="addCommentForm" method="post" action="">
<div>
<label for="name">Your Name</label>
<input type="text" name="name" id="name" />
<label for="email">Your Email</label>
<input type="text" name="email" id="email" />
<label for="url">Website (not required)</label>
<input type="text" name="url" id="url" />
<label for="body">Comment Body</label>
<textarea name="body" id="body" cols="20" rows="5"></textarea>
<input type="submit" id="submit" value="Submit" />
</div>
</form>
</div>
</p>
</div>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="../comments/script.js"></script>
</body>
</html>
and the javascript...
$(document).ready(function(){
/* The following code is executed once the DOM is loaded */
/* This flag will prevent multiple comment submits: */
var working = false;
/* Listening for the submit event of the form: */
$('#addCommentForm').submit(function(e){
e.preventDefault();
if(working) return false;
working = true;
$('#submit').val('Working..');
$('span.error').remove();
/* Sending the form fileds to submit.php: */
$.post('submit.php',$(this).serialize(),function(msg){
working = false;
$('#submit').val('Submit');
if(msg.status){
/*
/ If the insert was successful, add the comment
/ below the last one on the page with a slideDown effect
/*/
$(msg.html).hide().insertBefore('#addCommentContainer').slideDown();
$('#body').val('');
}
else {
/*
/ If there were errors, loop through the
/ msg.errors object and display them on the page
/*/
$.each(msg.errors,function(k,v){
$('label[for='+k+']').append('<span class="error">'+v+'</span>');
});
}
},'json');
});
});
It seems you are connecting to your database with an include, using a relative path:
include('../comments/connect.php');
That would be the first thing to change, it could be something like:
include($_SERVER['DOCUMENT_ROOT'] . '/comments/connect.php');
In general, look for relative paths and see if you can change them to absolute paths, either relative to the root of your server for php files or relative to the web-root for javascript files.
You would normally have your comment script at a URL that doesn't change, i.e. www.domain.com/comments. Then, you can either fetch comments for a page with a GET request (specifying the page, URL or other unique identifier via a query string parameter), and then the ability to post a comment with, well, a POST request.
This way, your comments module is completely separate from your application and you don't need to go through every script it's included in if you need to say, change your database details or a file path.
At it's simplest, you could have a PHP file that looks like this for your comments script:
<?php
header('Content-Type: application/json');
switch (strtolower($_SERVER['REQUEST_METHOD'])) {
case 'get':
// return comments for page in JSON format
break;
case 'post':
// post new comment; return result in JSON format
break;
}
And then in your HTML view files:
<!DOCTYPE html>
<html>
<body>
<div id="comments"></div>
<form action="http://domain.com/comments.php" method="post" id="new-comment">
<!--rest of your form here-->
</form>
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
$.getJSON('http://domain.com/comments.php?page_id=YOUR_PAGE_ID', function(comments) {
$.each(comments, function(index, comment) {
// add comment to #comments div
});
});
$('#new-comment').submit(function() {
$.post('http://domain.com/comments.php', $(this).serialize(), function(response) {
// act on your form depending is response was success or not
});
return false;
});
});
</script>
</body>
</html>
You could also wrap the above in a plugin, and then just add your comments widget to your page with a one-liner, i.e. $('#comments').nameOfYourCommentsPlugin();.
Hopefully that's helpful enough for you to build a working solution.
I think problem is on the javascript side, your post goes to a relative url you should replace it with an absolute url:
/* Sending the form fileds to submit.php: */
$.post('submit.php',$(this).serialize(),function(msg){//<- replace submit.php with absolute url
...

How do I refer to a php variable in jQuery?

I'm a complete beginner with jQuery and I have this bit of script here and I want to mix jQuery with PHP. I have Courses and in those Courses are Lessons. A Teacher is assigned to teach a Course. What I want is a link where if I press it a popup appears and in it shows the Lesson details or Course details. My problem is that I will be having multiple links and thus dialogs/modal windows in a page such that $l['id'] and $c['id'] will be different. How can I therefore use $l['id'] and $c['id'] in or with jQuery given that the jQuery script is inside the view file and I'm creating the actual content itself in the controller and passing it onto view. Sorry if I don't make sense cause I'm still quite confused about all this myself.
view.php
<script type="text/javascript">
$(function(){
// setup ul.tabs to work as tabs for each div directly under div.panes
$("#tabs").tabs();
$('#dialog').dialog({
modal: true
});
})
</script>
<h1>Student Hub: Courses for <?php echo $studentName;?></h1>
<div id="tabs">
<?php echo $content;?>
</div>
controller.php
This is in a foreach loop
<div class="lessonDetails">
<p>Lesson Details:<p>
<div id="lessonDialog'.$l['id'].'" title="Lesson Details">
'.$l['name'].'
</div>
</div>
<div class="courseDetails">
<p>Course Timetable & Resources<p>
<div id="courseDialog'.$c['id'].'" title="Course Details">
<p>'.$c['fullname'].'</p>
<p>'.$c['summary'].'</p>
<p>Upcoming Lessons: </p>
</div>
Technical answer is you don't as one is a server-side language and one is a client-side language; you can't access PHP variables via JavaScript (jQuery). You can, however, drop your PHP variables into your HTML page on generation, and then pick them up with JavaScript or jQuery.
Reading your scenario, I think your over-complicating things. Think of your application; don't think of the technical aspects, but more the way it should be laid out. I'm guessing you have a students controller, a lessons controller, and a courses controller. Those controllers will have actions, called view or similar, and then these actions will take an ID to display a particular student/course/lesson.
In your HTML page/view/template, you should have just vanilla URLs. JavaScript should then be used to enhance the website. So in your case, I would have mark-up it up similar to as follows:
<ul class="courses">
<?php foreach ($courses as $course): ?>
<li><?php echo $course->title; ?></li>
<?php endforeach; ?>
</ul>
I'd then, in an external JavaScript file, have a function that listens for a click on the <a> tag and instead of navigating to that URL, instead displays the page content in a pop-up/modal window.
<script>
$('.courses a').click(function(e) {
e.preventDefault();
// load external page and display it in a modal
});
</script>
This way, if for some reason JavaScript's not available then the user will be taken to the course details page. If they do have JavaScript, then they'll get a fancy modal pop-up.
Hope this helps. If you need anything clearing up then let me know, as I have wrote this in the early hours after a few JD and Cokes!
you can create in every link some extra attributes and using jQuery retrieve the information with the attr function $('a').attr('courses').
somethig like
<a href="#" class=".information" teacher="idTeacher" course="idCourse" >list </a>
then using jquery
$('.information').click(function(){
teacher= $(this).attr('teacher');
course=$(this).attr('course');
});
remember to use $('.information').live() if you are using some AJAX to get the data from the server and the parse it to create the links
You can place tags within your JavaScript code. Since that code is server side, it will "render" to your JavaScript client side code. So your JavaScript can access values stored by your PHP script.
Here's a solution using jQueryUI dialog. No ID's are required however should they be needed add them as a data attribute to that links
<p><a href="#courseInfo'.$c['id'].'" data-id="'.$c['id'].'" >Course Timetable & Resources</a><p>
This allows easily getting ID with jQuery data() method.
Dialog is created and destroyed each use. As noted in comments, no idea what content goes in dialog. I can easily adjust if it is ajax from href
$('.lessonDetails a, .courseDetails a').click(function(){
var $this=$(this);
/* if need the id associated to link*/
var id=$this.data('id');
var content= ''/* ??????? */
var title=$this.parent().next().attr('title')
loadDialog(title, content);
return false; /* stop browser following href*/
})
function loadDialog(title, content) {
var dialogOpts = {
modal: true,
title: title,
width: 800,
close: function() {
/* remove this dialog from DOM on close*/
$(this).remove()
}
};
$('<div>').append(content).dialog(dialogOpts);
}
Maybe you can create forms that have hidden values in it.
<?php foreach($lesson as $l): ?>
<form method="POST" action="">
<input type="hidden" name="lesson_id" value="<?php echo $l['id']; ?>" />
Click
</form>
<?php endforeach; ?>
javascript:
$(document).ready(function() {
$('.modal_window').click(function() {
var form = $(this).closest('form');
var lesson_id = $(form).find('input[name=lesson_id]').val();
// Do something with lesson_id
});
});
The idea is the same for courses.
****** Edit ********
Maybe you can try using input arrays. Assumming you have something like this
<input type="hidden" name="courses[]" value="1" />
<input type="hidden" name="courses[]" value="2" />
javascript:
var courses = $(form).find('input[name^=courses]');
$(courses).each(function() {
var course = $(this).val();
});

Linking page in a div with html forms and php

So I have this html code
<div id="wrap">
<div id="header">
</div>
<div id="content">
<form method="POST" action="code.php">
Name:
<input type="text" name="name" size="50">
<input type=submit value="Get Code">
</form>
</div>
<div id="footer">
</div>
Is it possible to load the code.php after the user clicks submit into the #content div?
Essentially, what I want is when the user clicks the submit button, the code.php after processing is loaded onto the same #content div.
So let say in my code.php, after processing the inputted data, I come up with this lilne of code,
<?php
some processing code here;
$name = 'john';
echo $name;
?>
So then after hitting submit, user would see
<div id="content">
john
</div>
Hope I didn't complicate my question by repeating myself, please let me know if this is possible with javascript, php or whatever.
Thanks for the read!
#JohnP yes, $.load is a good solution. However, you'll need to send the form data in the request:
UPDATED [3] for sending a POST with multiple fields and checkboxes:
$('form').submit(function(){
// create an object to send as a post
var form = this,
fields = form.elements,
el,
post = {};
for (var i = fields.length; i--; ) {
el = fields[i];
if (el.name) {
switch (el.type) {
case 'checkbox':
case 'radio':
post[el.name] = (el.checked) ? el.value : '';
break;
default:
post[el.name] = el.value;
}
}
}
// send the form data in the load request...
$('#content').load(this.action, post);
return false;
});
This will send the data as a POST.
Since you've tagged jQuery, I'll use a jQuery example
$(document).ready(function(){
$('form').submit(function(){
$('#content').load('code.php');
return false;
})
})
This makes a couple of assumptions here
This assumes that code.php is in the same path that you are in now.
There is only one form in the page.
As #johnhunter points out, this example obviously won't work with post. You can send the post data along with the method. See here for usage : http://api.jquery.com/load
EDIT
Here's a fiddle example : http://jsfiddle.net/jomanlk/J4Txg/
It replaces the form area with the content from jsfiddle/net/echo/html (which is an empty string).
NOTE 2 Make sure to include the code in $(document).ready() or include it at the bottom of the page. It goes without saying you need jQuery in your page to run this.
You might want to check out jquery form plugin http://jquery.malsup.com/form/#
in simple way use
<div id="content">
if(isset($_POST['submit'] && !empty($_POST) )
{
// do your all post process
$name ='John';
echo $name;
}
else {
<form method="POST" action="$_SERVER['PHP_SELF']">
<label for="uname" >Name:</label><input type="text" name="uname" id="uname" size="50">
<input type=submit value="Get Code" name="submit">
</form>
}
</div>

PHP Pass variable to popup form within same page

Following on from a previous question, (previous question here), the problem I'm having seems to involve trying to pass/post a value through a form when the form action is '#'. I've tried session data but it always returns the last item from the database. Everthing else returns nothing.
Any help/ideas/advice greatly received, S. (Code below)
This is the code that displays the list of items, each containing an 'email' link/button to one instance of a popup window/form that is located at the bottom of the page.
<?php
$query = mysql_query("select * from istable where categoryID = '1'");
while ($result = mysql_fetch_array($query)) {
echo '<h4>'.$result['title'].'</h4>
<p>'.substr($result['descrip'],0,408).'... <strong>Read more</strong></p>
<form action="#" method="post" rel="#sheet" class="see">
<input type="hidden" name="propTitle" value="'.$propResult['title'].'">
<input type="submit" name="submit" value="Email">
</form>
';
}
?>
This is the code for the popup window/form at the bottom of the same page that is called through jquery.
<div id="sheet" class="rounded">
<!--{{{ pane1 -->
<div class="pane" id="pane1">
<h4>Email Details to a Friend</h4>
<p>You have selected to forward the details of <?php echo $_POST['propTitle']; ?> to a friend.</p>
<p>Please fill out the following form</p>
<form class="rounded" id="email-form" method="post" action="<?php echo $pageLink; ?>">
<!-- form goes in here -->
</form>
</div>
<!--}}}-->
</div>
<script type="text/javascript">
$(".see").overlay({mask: '#999', fixed: false}).bind("onBeforeClose", function(e) {
$(".error").hide();
});
</script>
Why are you using PHP for this? If the popup is called through the same page, use JavaScript to get the DOM element value and if you need to process data use AJAX.

Categories