Combination of Jquery and SQL - php

I am looking to build a website which has a page, upon which there are some jChartFX charts, which are driven by a MySQL query. The query is driven by a date selected on a drop down on the main page.
I am struggling to structure the code properly (all completely self taught so fraught with poor practice!) so that the graph will update when a different option is selected.
The code is listed below, however my question is; where should the code sit for the drawing the chart to make this work. Should the function loadChart exist on the main page and echo the data in from the query from another page, or should I have the whole function on a separate page, which is loaded by the jquery, or option 3 - am I completely wide of the mark?
The code for the chart is; <> The echo $data is the section which echos the MySQL output, and works fine when the code and the SQL query is fixed.
<script>
var chart1;
function loadChart()
{
chart1 = new cfx.Chart();
chart1.getData().setSeries(1);
chart1.getAxisY().setMin(100);
chart1.getAxisY().setMax(1000);
var series1 = chart1.getSeries().getItem(0); series1.setGallery(cfx.Gallery.Lines);
var data = <?php echo json_encode($temp, JSON_NUMERIC_CHECK); ?>;
chart1.setDataSource(data);
var divHolder = document.getElementById('ChartDiv');
chart1.create(divHolder);
}
</script>
The SQL Query is
SELECT COUNT(`column_Date`) AS 'Count' FROM Dates WHERE `column_Date` > date('2013-06-01')
Note: Where the date is above 2013-06-01, I want this to change based on the drop down from the main page.
<head>
<script src="js/jquery-1.7.1.min.js"></script>
<script>
$(document).ready(function(){
$("#optionschosenid").click(function(){
if($("#optionsid").val() == "OptionA" ){
$("#chart").load("weeks.php");
}
else {
$("#chart").load("text_test.php");
}
});
});
</script>
</head>
<body onload="loadChart()">
<div id="row">
<form method="post" id="weekcommencing" name="dateselector">
<select id="optionsid" name="optionsname">
<option value="2013-06-01">June</option>
<option value="2013-01-01">January</option>
</select>
<button name="optionschosenname" id="optionschosenid"> Select Additional Option </button>
</form>
</div>
<div id="chart" name="chart">
<?php echo $data;
echo 'hello'; ?>
<br /> -->
Test 0.11
</div>
<button id="testId">click me</button>
<br />
<br />
<div id="ChartDiv">
</div>
</body>

The answer to your question is most likely "option 3" - you are completely wide of the mark :)
I don't know what is in your PHP $data variable - you don't show where it was declared and set. I see a Javascsript variable named data. I wonder if you might have the impression that javascript variables and PHP variables are visible to each other? They most certainly are not.
Bottom line is that you should separate everything as much as possible - as it seems you are starting to do. Include your javascript from a JS file. Include your HTML from a template.
Even though you are new, you are biting off enough that you should just dive right into an MVC framework. It will force you to learn at least some good practices.

Related

How to change a text value by requesting a PHP file thanks to AJAX? (Without refreshing the page)

I'm learning AJAX and want to create a really simple web app to use my knowledge in the "real world".
I'm trying to calculte different percentages of a user input value, and make it appears on the webpage, without refreshing, thanks to AJAX.
Here is my HTML form:
<form id="warmupForm" class="form">
<label for="userWorkLoad">Work load (in kgs)</label><br>
<input type="text" name="userWorkLoad" id="userWorkLoad">
<button type="submit">Calculate</button>
</form>
<div id="#output">This is where I want the result to be shown with AJAX</div>
Here is some of my PHP code, for you to get the idea:
# Get the user input (work load in kgs)
if (isset($_POST['userWorkLoad'])) {
$workload = $_POST['userWorkLoad'];
# Avoid JS hacking
$workload = htmlspecialchars($workload);
}
# CALCULATION #
# Calculate 55% of the work load (1st warm up set)
$FirstWarmupSet = ($workload * 0.55);
# Calculate 70% of the work load (2nd warm up set)
$SecondWarmupSet = ($workload * 0.7);
# First Warmup set #
echo "<li>Do 8 reps with " . $FirstWarmupSet . " kgs, then take 1 minute rest.</li>";
echo "<br>";
# Second Warmup set #
echo "<li>Do 5 reps with " . $SecondWarmupSet . " kgs, then take 1 minute rest.</li>";
echo "<br>";
// etc etc...
I'd like the different variables values from PHP to be shown in my "#output" div when the user click on the submit button.
I've tried a lot of different things (AJAX without jQuery, AJAX with jQuery), but didn't manage to get what I want.
I'm sure I'm doing something wrong, but I don't know what. I'm sure my PHP script is working, since I used it without AJAX without any problem.
I would be very grateful if someone could help me on that.
As mentioned above, the easiest way to make an AJAX request for you is probably to try jQuery:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<!-- Add jQuery on your HTML page -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<!-- Add some custom JavaScript file -->
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form id="warmupForm" class="form">
<label for="userWorkLoad">Work load (in kgs)</label><br>
<input type="text" name="userWorkLoad" id="userWorkLoad">
<button id="btn" type="submit">Calculate</button>
</form>
<div id="output">This is where I want the result to be shown with AJAX</div>
</body>
</html>
The script.js content:
$(function() {
// Process a button click
$("#btn").click(function() {
event.preventDefault();
// Get input field
var userWorkLoadInput = $("#userWorkLoad");
// Build some request parameters
var params = {
userWorkLoad: userWorkLoadInput.val()
};
// Let's name your PHP script file as "server.php"
// And send POST request with those parameters
$.post("server.php", params, function(response) {
// Response text we're going to put into the `output`
$("#output").html(response);
});
});
});
You can simply do it using Jquery instead of using Ajax (using PHP you should add method="POST" to the form).
Here's an example:
$(document).ready(function(){
$("#send").click(function(){
// your calculates
$("#output").html(...);
});
});
...
<button type="submit" id="send">Calculate</button>

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 [professionally/correct way] insert php code into javascript and/or html?

For instance,
in javascript:
1
<script>
var name = "<?php echo 'Adam'; ?>";
alert("The name is: " + name);
</script>
or
2
<script>
alert("The name is: <?php echo 'Adam'; ?>");
</script>
And in html?
1
<head>
<?php echo '<title>Page #1</title>'; ?>
</head>
or
2
<?php $page_number = "1"; ?> // on top of the script with the rest of the other X code. //
<!doctype html....
<html>
<head>
<title>Page #<?php echo $page_number; ?></title>
</head>
I'm not looking for the short, long, easy or hard method, I'm looking for the correct method to do this.
1 - In a professional way, how this should be done?
2 - What is your way/method to do this?
Thanks
Update:
Also:
<input type="button" onclick="javascript:add_friend(0,<?php echo $profile_user_id; ?>);" />
There is no correct method. Rather, there are conventions that you will find yourself using, or your team will find itself using. Further, it is at times a case by case situation where your HTML may need to be processed a bit by PHP prior to being spit out, and other times it may not.
I happen to prefer seeing as clean as separation as possible, where the limits of the PHP tags are shared by the same limits of any code we would hard-wire into place.
<title><?php echo $title; ?></title>
<script>
var strValue = <?php echo json_encode( $strValue ); ?>;
</script>
But again, that's just me.
With regards to JavaScript within HTML attributes, I would encourage you to stay as far away from that as you can. Rather than using onclick attributes, bind all of this up in your JavaScript. This, again, keeps a clean line of separation between your structure and your logic.
Which would you prefer seeing in your markup:
<input type="button" onclick="javascript:add_friend(0,288);" />
Or
<input type="button" data-action="add_friend" data-friendId="288" />
Keep your programmers out of your design, and more importantly your designers out of your code.

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();
});

Submit Search query & get Search result without refresh

I want to submit search query form & get search result without redirecting/reloading/refreshing on the same page.
My content is dynamic so can not use those "submit contact form without refreshing page which replies back on success".
In order to submit a form, collect the results from the database and present them to the user without a page refresh, redirect or reloading, you need to:
Use Ajax to Post the data from your form to a php file;
That file in background will query the database and obtain the results for the data that he as received;
With the query result, you will need to inject it inside an html element in your page that is ready to present the results to the user;
At last, you need to set some controlling stuff to let styles and document workflow run smoothly.
So, having said that, here's an working example:
We have a table "persons" with a field "age" and a field "name" and we are going to search for persons with an age of 32. Next we will present their names and age inside a div with a table with pink background and a very large text.
To properly test this, we will have an header, body and footer with gray colors!
index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="pt" dir="ltr">
<head>
<title>Search And Show Without Refresh</title>
<meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<!-- JQUERY FROM GOOGLE API -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#lets_search").bind('submit',function() {
var value = $('#str').val();
$.post('db_query.php',{value:value}, function(data){
$("#search_results").html(data);
});
return false;
});
});
</script>
</head>
<body style="margin:0;padding:0px;width:100%;height:100%;background-color:#FFFFFF;">
<div style="width:1024px;margin:0 auto;height:100px;background-color:#f0f0f0;text-align:center;">
HEADER
</div>
<div style="width:1024px;margin:0 auto;height:568px;background-color:#f0f0f0;text-align:center;">
<form id="lets_search" action="" style="width:400px;margin:0 auto;text-align:left;">
Search:<input type="text" name="str" id="str">
<input type="submit" value="send" name="send" id="send">
</form>
<div id="search_results"></div>
</div>
<div style="width:1024px;margin:0 auto;height:100px;background-color:#f0f0f0;text-align:center;">
FOOTER
</div>
</body>
</html>
db_query.php
<?php
define("HOST", "localhost");
// Database user
define("DBUSER", "username");
// Database password
define("PASS", "password");
// Database name
define("DB", "database_name");
// Database Error - User Message
define("DB_MSG_ERROR", 'Could not connect!<br />Please contact the site\'s administrator.');
############## Make the mysql connection ###########
$conn = mysql_connect(HOST, DBUSER, PASS) or die(DB_MSG_ERROR);
$db = mysql_select_db(DB) or die(DB_MSG_ERROR);
$query = mysql_query("
SELECT *
FROM persons
WHERE age='".$_POST['value']."'
");
echo '<table>';
while ($data = mysql_fetch_array($query)) {
echo '
<tr style="background-color:pink;">
<td style="font-size:18px;">'.$data["name"].'</td>
<td style="font-size:18px;">'.$data["age"].'</td>
</tr>';
}
echo '</table>';
?>
The controlling stuff depends from what you want, but use that code, place those two files in the same directory, and you should be fine!
Any problems or a more explicative code, please let us know ;)
You'll probably want to start with any of the thousands of "AJAX for beginners" tutorials you can find on the net. A Google search with that term should get you going.
Try this for starters:
http://www.destraynor.com/serendipity/index.php?/archives/29-AJAX-for-the-beginner.html
After you've read through that, keep in mind that you really don't need to be writing any XHR handling code. As pointed out by Jamie, jQuery or any of the other multitudes of Javascript libraries out there, can greatly simplify your client-side AJAX code.
This is what AJAX is for.
In jQuery (apologies if you're looking for a different library)
$("form#search").bind('submit',function() {
$.post("search.php",this.serialize(),function(data) {
// Put the code to deal with the response data here
});
return false;
});
It's good if you can get some basics of Ajax before straight away going to the code.
Ajax , is the exact solution for your problem. It asynchronously makes a request to the server, get the result and the data in the page can be modified with the result . It's all done in JavaScript.
Suppose you have an html like this:
<html>
<body>
<div id="myDiv"> your content area</div>
<button type="button" onclick="loadByAjax()">Change Content</button>
</body>
</html>
Now, your javascipr code will be like this:
<script type="text/javascript">
function loadByAjax()
{
$.ajax({
type: "POST",
url: "yourserverpage.php",
data: "searchkey=data_from_user_input",
success: function(response_data){
$('myDiv').html(response_data)
}
});
}
</script>
so, basically upon click of the button, the JavaScript will be executed. It wil call the php serverside script, pass the parameters it got from user input and retrieve the response data and place it inside the div.
So your page is updated without full refresh.
Also, please understand that, i used jquery library here for the Ajax function.

Categories