Having trouble pulling variables from one PHP to another script.
I have three different files, adminPage.html, reportScript.php, and report.php.
adminPage.html takes variables from the user and uses AJAX post function to post the variables to reportScript.php.
report.php is supposed to pull those posted variables from reportScript.php and use the variables in a SQL function, however, I am receiving an error stating that I have an "undefined index: startDate" and "undefined index: endDate" where I am instantiating the variables in PHP.
adminPage.html:
<center><h2> Choose the dates below that you need an order list from: </h2>
</br>
<form>
<h2>Start:</h2>
<input type="date" id ="reportStartDate" name = "startDate">
</br>
<h2>End:</h2>
<input type="date" id ="reportEndDate" name = "endDate">
</form>
</center>
</br></br>
<button id="runReportButton" onclick = "runReport()"> Run Report </button>
<script>
function runReport()
{
var jStartDate;
var jEndDate;
jStartDate = document.getElementById("reportStartDate").value;
jEndDate = document.getElementById("reportEndDate").value;
/*console.log(jStartDate);
console.log(jEndDate); */
$.ajax
({
type: "POST",
url: "phpScripts/reportScript.php",
data: {startDate: jStartDate, endDate: jEndDate},
success: function(response)
{
console.log("posted");
window.open("report.php", "_self");
}
});
}
</script>
reportScript.php:
<?php
require 'connect.php';
//posts data to db
$startDate = $_POST["startDate"];
$endDate = $_POST["endDate"];
$sql = "SELECT * FROM orderlist WHERE NOT (dateOrdered < startDate OR
dateOrdered > endDate)";
$result = $conn->query($sql);
if($result){
echo "true";
}
else{
echo "false";
}
?>
report.php:
<?php
require 'phpScripts/connect.php';
require 'phpScripts/reportScript.php';
//posts data to db
/*$startDate = $_POST['startDate'];
$endDate = $_POST['endDate'];*/
/*$startDate = '2018-01-01';
$endDate = '2018-08-08'; */
$sql = "SELECT * FROM orderlist WHERE NOT (dateOrdered < '$startDate' OR dateOrdered > '$endDate');";
$result = $conn->query($sql);
//above is reportScript.php, below is pulling list method from order.php
//below works, just needs variables from the reportScript
echo "<ul>";
if($result->num_rows >0)
{
$i = 0;
while($row = $result->fetch_assoc()) // this loads database into list, also
creates array of pricing which someone can pull from later to get total
{
echo "<li style='font-size:15px'>".$row["drinkName"]. ", Date Ordered: "
.$row["dateOrdered"] . ",Cost: " .$row["drinkCost"] . "</li>";
echo "</br>";
$i = $i+1;
}
}else {
echo "<p> you're a dummy and you did this wrong </p>";
}
echo "</ol>";
?>
You forgot the dollar sign ($) in your variables in reportScript.php.
$sql = "SELECT * FROM orderlist WHERE NOT (dateOrdered < $startDate OR
dateOrdered > $endDate)";
This statement is also vulnerable to sql injection.
With some of the advice taken from #Ralf, I combined both reportScript.php and report.php, and used a $_GET statement to put the date variables into the URL upon opening. This way, the query isn't placed twice and the variables are still saved.
Related
My aim is to get the lec_id which is the Button value when the button is clicked and pass it to chapters.php where I use the button value for a SQL query.
Below is part of my code for index.php
<?php
$con = mysqli_connect("localhost", "root", "", "lectureHub");
if(!$con) {
die("Could not connect to MySql Server:" . mysqli_error());
}
$query = "select * from lectures";
$result = mysqli_query($con, $query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$lec_id = $row['lec_id'];
$lec_name = $row['lec_name'];
$lec_number = $row['lec_number'];
$lec_views = $row['lec_views'];
echo "<button id=linkButton name={$row['lec_name']} value={$row['lec_id']} type='button' class='btn btn-outline-primary lecture' onclick='buttonClicked(this)'>
{$row['lec_name']}
</button> ";
}
} else {
echo "0 results";
}
?>
my button onclick function
function buttonClicked(btn) {
btn.click_counter = (btn.click_counter || 0) + 1;
document.getElementById("num_clicks_feedback").textContent = `btn ${btn.getAttribute('name')} has been clicked ${btn.click_counter} times`;
localStorage.setItem("lecId", btn.getAttribute('value'));
location.href = 'index.php?action=lec_hub/chapters';
}
I want to use the Button value here in chapters.php for a SQL query.
<html>
<head></head>
<body>
<?php
echo "<p id='lecId'></p>";
$con = mysqli_connect("localhost", "root", "", "lectureHub");
if(!$con) {
die("Could not connect to MySql Server:" . mysqli_error());
}
$query = "select * from chapters where <<this is where i want to use lecId>> ";
?>
<script>
function getValue(){
var lecId = localStorage.getItem("lecId");
document.getElementById("lecId").innerHTML = lecId;
var resetValue= 0;
localStorage.setItem("lecId", resetValue)
}
getValue()
</script>
</body>
</html>
Welcome to Stack Overflow! As Barmar stated in their comment, you can pass data to a PHP file using URL parameters, or more commonly known as GET parameters. Here's how you do it.
From your file with your button in it, you can create a form like this one:
<form action="chapters.php" method="get">
<input type="text" name="data" /> <!-- This is the value that will be passed -->
<input type="submit" value="Button" /> <!-- This is your button -->
</form>
And then from your PHP file, you can get that passed data like this:
echo $_GET["data"]
$_GET is a global PHP array that contains all of the URL parameters sent to the file. you can pass multiple values as GET parameters to a file. You can read all about the $_GET variable here. I hope this helps!
I have this modal jQuery AJAX:
$('#switch_modal').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).attr('data-id');
$.ajax({
type : 'post', // commented for this demo
url : 'pars.php', // commented for this demo
data : 'id='+ rowid,
success : function(data) {
$('.fetched-data').show().html(rowid); // show rowid for this demo
}
});
});
My mysql query:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
while ($row = $result->fetch_assoc()) {
My modal data-id:
<a href="#viewgame" data-toggle="modal" data-id="<?php echo $row['id'];?>"">
How can i do to use the var rowid like a PHP post? Something like that:
$id = $_POST['rowid'];
echo $id;
If i understand well this test your doing...
Your JavaScript rowid is the value.
The $_POST identifier is id.
Try this in your PHP:
$id = $_POST['id'];
echo $id;
You'll get the javascript rowid sent as a POST value (named as $_POST['id']) via ajax... And returning in data on ajax success.
$('.fetched-data').show().html(data);
So you'll have to use data in your jQuery html()... Wich is the echoed text.
-----
EDIT AFTER ACCEPTATION of this answer
(Based on your last comment)
So i have this query:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$gameid = $row['id'];
}
}
So i want to use $gameid variable into this query:
$sql = "SELECT * FROM games WHERE id='".$gameid."'";
I understand, that you want to get THE LAST matching full line where winner value is empty from games table.
No need for an ajax call...
No need for a second query.
Just do it:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
$result = $conn->query($query);
$row = $result->fetch_assoc();
for ($i=0;$i<sizeOf($row);$i++){ // This is the «size» (number of values) of one row, the last fetched.
echo $row[$i] . "<br>";
}
You'll get all your line values echoed...
This will be the LAST matching line fetched.
If you have many matching lines and want all results, do it like this:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
$result = $conn->query($query));
while ($row = $result->fetch_assoc()) { // While fetching, echo all values of one matching line.
echo "row id: " . $row['id'] . "<br>";
echo "values: <br>";
for ($i=0;$i<sizeOf($row);$i++){
echo $row[$i] . "<br>";
}
}
Notice that this script, that I suggest, will enlight you about the while fetch loop possible results. You'll have to work a little to have it displayed correctly on your page.
;)
I am having trouble executing SQL via AJAX when a dropdown box is changed and would like some help if possible.
Background Info
I have been tasked with creating a daily calendar that shows all the classes ran at a gym, which at its maximum is 5 x classes of 6 (30) people per hour for 14 hours.I'm no pro and I may have created a convoluted way around this issue, please let me know if i have.
I have managed to create the view which consists of 14 columns of 30 drop down boxes (5 x classes of 6 per hour for 14 hours). Each drop down box polls the db and if an entry resides it will populate the box with the name of the bookinguser. If no booking is found it will create a drop downbox that polls the members table and presents all the members of the gym, which when changed, will hopefully book that person in. - herein lies my current issue!
Each drop down box's name corresponds to the time, group and headcount which I intend on passing to javascript function and eventually to the SQL statement. Each option's value corresponds with the memberid which will also be passed giving all the information needed to construct the SQL.
The code I have so far
HTML - snipped generated from php loops
<div id="results">
<div id="07" class="column">07:00<br/>
<div id="group1">
<select name="07:00-1-0" onchange="getda(this.value,this)">
<option value="none">---------------</option>
<option value="2">John Doe</option>
<option value="1">Joe Bloggs</option>
</select>
<select name="07:00-1-1" onchange="getda(this.value,this)">
<option value="none">---------------</option>
<option value="2">John Doe</option>
<option value="1">Joe Bloggs</option>
</select>
PHP
<?php
$mysqli = new mysqli("localhost", "root", "", "gym");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
function hyphenate($str) {
return implode("-", str_split($str, 2));
}
function getmembers($time,$group,$iteration)
{
$date=$_GET["date"];
$date=hyphenate($date);
$date = explode('-', $date);
$new_date = $date[2].'-'.$date[1].'-'.$date[0];
$mysqli = new mysqli("localhost", "root", "", "gym");
if ($iteration == 0){
$result = $mysqli->query("select members.memberid, members.firstname, members.lastname from bookings inner join members on bookings.memberid = members.memberid where bookings.date = '$new_date' and time = '$time' and bookings.groupnumber = '$group' order by bookings.bookingid ASC limit 1");
}
else {$result = $mysqli->query("select members.memberid, members.firstname, members.lastname from bookings inner join members on bookings.memberid = members.memberid where bookings.date = '$new_date' and time = '$time' and bookings.groupnumber = '$group' order by bookings.bookingid ASC limit 1,$iteration");
}
$rowcount=mysqli_num_rows($result);
if ($rowcount==$iteration && $iteration == 0)
{
$result = $mysqli->query("select firstname, lastname,memberid from members order by firstname ASC");
echo '<select name="'.$time.'-'.$group.'-'.$iteration.'" onchange="getda(this.value,this)"><option value="---------------">---------------</option>';
while ($row = $result->fetch_assoc()) {
unset($firstname, $lastname);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$memberid = $row['memberid'];
echo '<option value="'.$memberid.'">'.$firstname . ' ' . $lastname .'</option>';
}
echo "</select>";
}
else if ($rowcount>=$iteration){
echo '<select name="'.$time.'-'.$group.'-'.$iteration.'" onchange="getda(this.value,this)">';
while ($row = $result->fetch_assoc()) {
unset($firstname, $lastname);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$memberid = $row['memberid'];
echo '<option value="'.$memberid.'">'.$firstname . ' ' . $lastname .'</option><option value="cancel">Cancel</option>';
}
echo "</select>";
}
else{
$result = $mysqli->query("select firstname, lastname, memberid from members order by firstname ASC");
echo '<select name="'.$time.'-'.$group.'-'.$iteration.'" onchange="getda(this.value,this)"><option value="---------------">---------------</option>';
while ($row = $result->fetch_assoc()) {
unset($firstname, $lastname);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$memberid = $row['memberid'];
echo '<option value="'.$memberid.'">'.$firstname . ' ' . $lastname .'</option>';
}
echo "</select>";
}
}
?>
JS
function getda(id,booking){
$.ajax({
type: 'post',
url: 'samefile.php',
data: {
get_option:id
},
success: function (response) {
document.getElementById("result").innerHTML=response;
}
});
}
samefile.php
<?php
if(isset($_POST['get_option']))
{
inlude 'config/config.php';
$name=$_POST["get_option"];
echo "<SCRIPT>
alert('$name');
</SCRIPT>";
$sql = "insert into bookings (memberid,date,time,groupnumber) values (1,'2016-04-14','09:00',3)";
$query = mysqli_query($sql);
$mysqli->close();
?>
The console in chrome looks fine (below) but no records are inserted and the php alert doesn't show. I havent passed any of the variable to the SQL as I was first testing that a query executed properly
jquery.min.js:4 XHR finished loading: POST "http://localhost/gym/samefile.php".send # jquery.min.js:4n.extend.ajax # jquery.min.js:4getda # cal.php?date=140416:42onchange # cal.php?date=140416:36ListPicker._handleMouseUp # about:blank:535
Might want to look into jQuery's .change(). I think that it would work with something like below for your code. You could also have it call your function that has ajax in it as well
$( ".class" ).change(function() { //can use #id here too
$.ajax({
type: 'post',
url: 'samefile.php',
data: {
get_option:this.value
},
success: function (response) {
document.getElementById("result").innerHTML=response;
}
});
});
I see three problems in samefile.php - include spelled incorrectly, an extra semicolon, and a missing closing bracket:
<?php
if(isset($_POST['get_option']))
{
include 'config/config.php';
$name = $_POST["get_option"];
//this should be converted to parameterized queries
$sql = "insert into bookings (memberid,date,time,groupnumber) values (1,'2016-04-14','09:00',3)";
$query = mysqli_query($sql);
if(is_object($query)){
echo 'successfully inserted';
} else {
echo 'insert failed';
}
$mysqli->close();
} else {
echo 'no data to process!';
}
?>
I have one login.php, one main.php, one functions_js.js and one functions_php.php (I use jquery too).
My problem is I need to take two variables from login.php and send it to functions_php.php (ajax, ok that works) but then in functions_php.php I make a query select (with this variables) and it returns me an array which I need on functions_js.js , in this file I have a function to insert images on main.php.
I don't know how to pass the array from functions_php to functions_js.js.
I've read that I can use json but I don't know how to use between 2 different files.
I've tried to use json and pass it to main.php but no works:
functions_php.php:
if (isset($_POST['user'])) {
function startPerson($nick,$pass){
$query = $conexion->query('SELECT archive_id FROM family WHERE family_id=(select distinct family_id from person where user_id = (select user_id from user where user_name="'.$nick.'" and password="'.$pass.'"))');
$query->execute();
while ($res = $query->fetch()) {
$id = $res['archive_id']; //archive_id
}
//coger las personas de las familias de ese archive_id
$query = $conexion->query('SELECT person_id, birth_date FROM person WHERE family_id in (select family_id from family where archive_id='.$id.')');
$query->execute();
while ($res = $query->fetch()) {
$person[] = $res[0]; //archive_id
$date[]=$res[1];
}
return array($person, $date);
}
header('Content-Type: application/json');
$encoded=json_encode(startPerson($_POST['user'],$_POST['pass']));
echo $encoded;
}
main.php:
<?php
$json_data=json_encode($encoded);
?>
<script>
var an_obj= <?php echo $json_data;?> ;
alert(an_obj);//returns null
</script>
function_js.js:
function startPerson (date) {
for(i=0;i=>date.length;i++){
var elem = date[i].split('-');
var mon= elem[1]; //month
var year=elem[0]; //year
var mont= num2mon(mon);
position(year,mont);
elem=" ";
mon=" ";
year=" ";
}
}
function position(year, mon)
{
$('#' + year + ' .' + mon).prepend('<img class="black_point" src="./images/circle.png"/>');
}
Have you tried changing:
var an_obj= <?php echo $json_data;?> ;
to:
var an_obj = "<?php echo $json_data;?>";
Remember, the variable is a string.
Can you also try doing an echo on $encoded?
I am using ajax to post comments to a certain page, I have everything working, except for when the user posts a comment I would like it to show immediately without refreshing. The php code I have to display the comments is:
<?php
require('connect.php');
$query = "select * \n"
. " from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '$s_post_id' ORDER BY comments.id DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$c_comment_by = $row['comment_by'];
$c_comment_content = $row['comment_content'];
?>
<div class="comment_box">
<p><?php echo $c_comment_by;?></p>
<p><?php echo $c_comment_content;?></p>
</div>
<?php } ?>
</div>
</div>
<?php
}
}
and the code I have to post comments is:
<?php
$post_comment = $_POST['p_post_comment'];
$post_id = $_POST['p_post_id'];
$post_comment_by = "Undefined";
if ($post_comment){
if(require('connect.php')){
mysql_query("INSERT INTO comments VALUES (
'',
'$post_id',
'$post_comment_by',
'$post_comment'
)");
echo " <script>$('#post_form')[0].reset();</script>";
echo "success!";
mysql_close();
}else echo "Could no connect to the database!";
}
else echo "You cannot post empty comments!"
?>
JS:
function post(){
var post_comment = $('#comment').val();
$.post('comment_parser.php', {p_post_comment:post_comment,p_post_id:<?php echo $post_id;?>},
function(data)
{
$('#result').html(data);
});
}
This is what I have for the refresh so far:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('.comment_box').load('blogpost.php');
}, 3000);.
});
Now what I want to do is to use ajax to refresh the comments every time a new one is added. Without refreshing the whole page, ofcourse. What am I doing wrong?
You'll need to restructure to an endpoint structure. You'll have a file called "get_comments.php" that returns the newest comments in JSON, then call some JS like this:
function load_comments(){
$.ajax({
url: "API/get_comments.php",
data: {post_id: post_id, page: 0, limit: 0}, // If you want to do pagination eventually.
dataType: 'json',
success: function(response){
$('#all_comments').html(''); // Clears all HTML
// Insert each comment
response.forEach(function(comment){
var new_comment = "<div class="comment_box"><p>"+comment.comment_by+"</p><p>"+comment.comment_content+"</p></div>";
$('#all_comments').append(new_comment);
}
})
};
}
Make sure post_id is declared globally somewhere i.e.
<head>
<script>
var post_id = "<?= $s_post_id ; ?>";
</script>
</head>
Your new PHP file would look like this:
require('connect.php');
$query = "select * from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '".$_REQUEST['post_id']."' ORDER BY comments.id DESC";
$result = mysql_query($query);
$all_comments = array() ;
while ($row = mysql_fetch_array($result))
$all_comments[] = array("comment_by" => $result[comment_by], "comment_content" => $result[comment_content]);
echo json_encode($all_comments);
Of course you'd want to follow good practices everywhere, probably using a template for both server & client side HTML creation, never write MySQL queries like you've written (or that I wrote for you). Use MySQLi, or PDO! Think about what would happen if $s_post_id was somehow equal to 5' OR '1'='1 This would just return every comment.. but what if this was done in a DELETE_COMMENT function, and someone wiped your comment table out completely?