Potentially wrong mySQL query making form buttons disappear - javascript

<script type="text/javascript">
function on_callPhp1()
{
var result = "<?php php_func();?>";
document.getElementById('phptext').innerHTML = result;
}
</script>
<form action="" method="POST">
<input type="button" value="Get Numbers" onclick="on_callPhp1()"/>
</form>
<div id="phptext"></div>
<?php
include_once ('/var/www/db/connection.php');
function php_func() {
for ($i = 0; $i <= 25000; $i++) {
$num = (rand(1,1000));
echo "Number #" .$i . "\t ------ " . $num;
echo "<br>";
$queryInsertNum = "INSERT INTO myDb.myTable(number) VALUES ('$num');";
$result = $mysqli -> query($queryInsertNum);
}
}
?>
Whenever I run the above code, I do not see the form button.
However, when I comment out the last line $result = $mysqli -> query($queryInsertNum); they appear and the page runs normally.
What could be wrong?
Update 1:
My connection.php is as follows
<?php
global $mysqli;
$mysqli = new mysqli("127.0.0.1", "user1", "somepassword", "myDB");
if ($mysqli -> connect_errno)
{
echo "Failed to connect to MySQL: (" . $mysqli -> connect_errno . ") " . $mysqli -> connect_error;
}
?>

You have a variable scope issue , every php function has it's own scope, you cannot deal with a variable from outside the function within it unless you pass this variable to your function .
the $mysqli variable which we are talking about here .
and to solve this , you need either use global variables , which is considered as a bad practice, checkout this wiki for more details OR by passing your variable as a parameters as follows :
// hey `php_func` ,please pass $mysqli value to be able to use it within you
// or whatever the variable name is
function php_func($mysqli) {
for ($i = 0; $i <= 25000; $i++) {
$num = (rand(1,1000));
echo "Number #" .$i . "\t ------ " . $num;
echo "<br>";
$queryInsertNum = "INSERT INTO myDb.myTable(number) VALUES ('$num');";
$result = $mysqli -> query($queryInsertNum);
}
}
but take care, you will need every time you call your function to pass that variable to it as following :
php_func($mysqli);
this , will take us to the other issue , that you are mixing and misunderstanding the difference between client-side and server-side programming? ,
you are calling the php function like this :
var result = "<?php php_func();?>";
which is wrong , if you hit CTRL+U from your firefox you will figure out that the function already executed even before call your HTML event onclick
it's recommended in such a case -which you are need to open a contacting channel so to speak between the client side and server side- to use ajax
so , your script may be like this : here i will assume that your file name is phpfunc.php
the ajax part :
<script type="text/javascript">
function on_callPhp1()
{
$.ajax({
url: 'phpfunc.php?get=data', // change this to whatever your file is
type: 'GET',
success: function (data) {
document.getElementById('phptext').innerHTML = data;
}
});
}
</script>
<form action="" method="POST">
<input type="button" value="Get Numbers" onclick="on_callPhp1()"/>
</form>
<div id="phptext"></div>
<?php
function php_func($mysqli) {
for ($i = 0; $i <= 25000; $i++) {
$num = (rand(1,1000));
echo "Number #" .$i . "\t ------ " . $num;
echo "<br>";
$queryInsertNum = "INSERT INTO myDb.myTable(number) VALUES ('$num');";
$result = $mysqli -> query($queryInsertNum);
}
}
if (isset($_GET['get']) && $_GET['get'] == 'data') {
include_once ('/var/www/db/connection.php');
php_func($mysqli);
}
?>

I guess it 's because $mysqli is an unknow object inside your function, try to add global $mysqli inside your function.
<?php
include_once ('/var/www/db/connection.php');
function php_func() {
global $mysqli;
for ($i = 0; $i <= 25000; $i++) {
$num = (rand(1,1000));
echo "Number #" .$i . "\t ------ " . $num;
echo "<br>";
$queryInsertNum = "INSERT INTO myDb.myTable(number) VALUES ('$num');";
$result = $mysqli -> query($queryInsertNum);
}
}
?>

Related

Using variable on php to create another variable in JS

I'm having a hard time getting the value of a specific variable in php to use in js. This is my code in php:
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<h4>" . $result['status'] . "</h4>";
}
?>
I want to get the value of this ($result['status']) and pass it on the variable pos in js. This is my js code:
setInterval(function() {
$("#position").load('refresh.php');
notif();
}, 1000);
function notif() {
var pos = $('PHP VARIABLE HERE').val();
alert(pos);
}
Thanks for your help.
The easiest way is to output it to javascript directly:
?>
<script type="text/javascript">
window.MY_PHP_VAR = <?php echo json_encode($myPhpVar); ?>;
</script>
...
window.MY_PHP_VAR now contains your php variable
if your javascript code is on same page where the result is comming then you can use this
var pos = `<?php echo $result['status'] ?>`;
var pos = `<?= $result['status'] ?>`;
===============
// refresh.php
===============
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<h4>" . $result['status'] . "</h4>";
echo "<script> alert('". $result['status'] ."'); </script>";
/* If the $result['status'] is 'success' the above line will be converted to:
echo "<script> alert('success'); </script>";
*/
}
?>
so, every time the refresh.php loads, the script is going to get executed.
However, I suggest you to assign a id or class attribute to your h4 where you are echoing your status and access the value using the selectors in the javascript.
you could try giving an id or class to the status.
then in JavaScript you could then get the value of the id or class.
PHP
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<h4> <span class="status">' . $result['status'] . '</span></h4>';
}
?>
JavaScript
var oldStatus = '';
setInterval(function() {
$("#position").load('refresh.php');
notif();
}, 1000);
function notif() {
// note that since we used a class, you will get the value of the first element only.
var pos = $('.status').text(); // use .text() instead of .val()
if (pos.toLowerCase() == 'out' && pos != oldStatus){
oldStatus = pos;
alert(pos);
}
}

How to pull variables from one PHP script to another

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.

Pass array from javascript to page in wordpress

I have a page in wordpress, that uses an jquery and ajax to get information from an external api. The form sends the array generated in javascript back to the same page with another variable that the php in the page uses to determine which page to display. Outside of wordpress, the code works fine. Inside Wordpress the first portion runs, but then instead of loading the same page again it goes to a search page and says nothing found.
The url on the output is:
http://kltools.net/?s=&post_type%5B%5D=portfolio&post_type%5B%5D=post&post_type%5B%5D=page
Which seems odd considering I'm using post not get.
The javascript that generates the array and submits the form:
function submitchans(){
for (var i=0;i<chans.length;i++)
{ var newHidInp = document.createElement('input');
newHidInp.type = 'hidden';
newHidInp.name = 'chans[]';
newHidInp.value = chans[i];
form.appendChild(newHidInp);
}
}
function livearray(input){
if (input != null) {
chans.push(input);
}
if (Y === cSize){
submitchans();
document.forms[0].submit();
}
}
Previously the array was outArray[] instead of chans[], I changed it thinking that may be triggering the result, but no luck.
This is the PHP portion of the code:
<?php
$page_to_load = $_POST[view];
switch($page_to_load) {
case '':
echo "<script src=\"../scripts/jquery-3.2.0.min.js\"></script>";
echo "<script type=\"application/javascript\" src=\"../scripts/raid.js\"></script>";
echo "<font size=\"+3\" color=\"#FFFFFF\">Who should I host?<br>Please wait while channel is selected<br></font>";
echo "<font size=\"+2\">";
echo "<br><br>";
echo "<img src=\"../_images/ajax_loader_blue_350.gif\">";
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$chanarray[] = null;
$offline = 0;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT `TwitchNames` FROM TK_Members WHERE Validated='1' AND RaidMe='1'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
array_push($chanarray, $row['TwitchNames']);
}
} else {
echo "0 results";
}
array_splice($chanarray, 0, 1);
$conn->close();
echo "<script type=\"application/javascript\">";
echo "var channels = ". json_encode($chanarray);
echo "</script>";
echo "</font>";
echo "<form id=\"form\" method=\"post\">";
echo "<input type=\"hidden\" name=\"view\" value=\"page2\">";
echo "</form>";
break;
case 'page2':
echo "<font size=\"+3\" color=\"#FFFFFF\">Who should I host?<br>";
echo "Your channel to host is:<br></font>";
echo "<font size=\"+2\">";
echo "<br><br>";
$chans[] = null;
$test = $_POST['chans'];
foreach ($test as $chan) {
$temparray = array(rand(),$chan);
array_push($chans, $temparray);
}
array_splice($chans,0,1);
sort($chans);
echo "".$chans[0][1]."";
echo "<br><br><br>";
echo "See All Live Channels";
echo "</font>";
break;
}
?>
After working with what blokeish has suggested I've modified the javascript file working out where the problem is.
The new javascript file is:
// JavaScript Document
var chans = ["test1","test2","test3"];
function submitchans(){
for (var i=0;i<chans.length;i++)
{ var newHidInp = document.createElement('input');
newHidInp.type = 'hidden';
newHidInp.name = 'chans[]';
newHidInp.value = chans[i];
document.getElementById('chansform').appendChild(newHidInp);
}
}
jQuery(function ($) {
submitchans();
document.getElementById('chansform').submit();
});
Using only the javascript clicking submit, it passes to the next page. When adding in the array pass is when it fails. This is the page log that is returning during the execution. !!--CORRECTION--!! there was a typo in the code, after correcting ID to Id the code is working as intended.
document.forms[0].submit() is likely submitting the wp search form as that could be the first form in the DOM. I see "http://kltools.net/?s=" in the URL where "s" is the search term.
Using document.getElementById('idOfForm').submit() should get you around that problem if there are multiple forms in a page and you cant be sure of its index.

Change the value of external Javascript with PHP in foreach loop

How can I change the value of a js variable in a PHP foreach loop?
The js needs to be external.
This is a piece of the index.php here I want to get the output $prozent in the javascript, I don't know how to get a PHP variable to execute a js every time in a loop, the js is a chart. I get the chart in the loop in the echo'<div class="chart-wrapper"> with a this chart js.
<?php
$sql = //SQL query
$res = mysql_query($sql);
$i = 0;
$survey = array();
while ($row = mysql_fetch_assoc($res)) {
$survey[$i]['label'] = $row['Label'];
$i++;
}
foreach ($survey as $survey) {
echo '<div class="col-md-4">';
echo '<div class="front face">';
echo "<h3> ".$survey['label']."<br>";
$sql = //SQL Query
$res = mysql_query($sql) ;
$sql = //SQL Query
$resSum = mysql_query($sql) ;
while ($row = mysql_fetch_array($resSum)) {
$survey['ausgabe'] = $row['sum(a.answer)'];
}
$anzahlreihen = mysql_num_rows($res);
if ($anzahlreihen > 0) {
$prozent = $anzahlreihen * $survey['ausgabe'];
//bunch of ifelse statements
//This is the variable i want to get in the js
echo (round( $prozent, 2));
echo '</font>';
}
}
echo '</div>';
echo '<div class="back face center">';
echo'<div class="chart-wrapper">
}
There are two ways PHP and Javascript can interact.
Use AJAX to request a PHP script which returns JSON or have PHP output the following example HTML;
<script type="text/javascript">
var variable = value;
</script>

How to properly load one ajax request after another

I am creating a messaging system for a website that I am making. Basically, it consists of clicking one button and two Ajax Requests afterwards. I am not even sure I am going about this the right way. On click of the button the first Ajax starts to call. The first ajax request loads a file that loads the style of the messages and retrieves them from a database. The problem I am having is that the first request sometimes takes to long to finish and the other request does not get complete. Another problem I am having is that if I put an "animation delay" type thing on it then it will look like the page it running slow. You can run an example at "http://www.linkmesocial.com/linkme.php?activeTab=mes" you must type or copy and past the whole length for it to work otherwise you will redirect to the login page. Any advice would be AWESOME! If there is some easier way to set up a messaging system please feel free to give me some advice or direct me to a tutorial. THANK YOU SO MUCH!
I would also like the know if this is a good practice. Please :)
My Original file. On click of class "mes_tab" a form is submitted. also the function mes_main() is called.
session_start();
$username = $_SESSION['user'];
$messages = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username'");
echo "<div id=\"mes_main-bar_top\" class=\"center\">Messages</div>";
echo "<div id=\"mes_main\">";
echo "<table id=\"mes_main-allView\" class=\"left\">";
echo "<td class=\"mes_tab-change\" >^</td>";
$from=array("","","", "", "", "", "", "");
for ($msgCount = 0; $msgCount < 8; $msgCount++){
$row = mysqli_fetch_array($messages);
$from[$msgCount] = $row['sender'];
for ($prev = 0; $prev < $msgCount; $prev++)
{
if ($from[$msgCount] == $from[$prev] )
{
$cont = true;
break;
}
}
if ($cont)
{
$cont = false;
continue;
}
if ($row['message'] == ""){
break;
}
echo "<tr><td class=\"mes_tab\" onclick=\"mes_main('" . $row['sender'] . "')\">";
echo "<h3 class=\"center\">" . $row['sender'] . "</h3>";
echo "<form id=\"" . $row['sender'] . "\" >";
echo "<input name=\"sender\" value=\"" . $row['sender'] . "\" hidden/>";
echo "<input name=\"id\" value=\"" . $row['id'] . "\" hidden/>";
echo "</form>";
echo "</td></tr>";
}
if ($msgCount == 8)
{
echo "<td id=\"mes_tab-change_bottom\" class=\"mes_tab-change\">V</td>";
}
echo "</table> <!-- end mes_main-allView -->";
echo "<div id=\"mes_main-mesView\" class=\"right\">";
echo "</div> <!-- end mes_main-mesView -->";
echo "</div> <!-- end mes_main -->";
mes_main() function from above. The two ajax functions inside are what I am referring to in the post above.
function mes_main(x)
{
var sender = x;
$( sender ).submit(function( event ) {
event.preventDefault();
});
ajax_req_mes("scripts/home/php/mes_load.php?" + sender , "mes_main-mesView");
ajax_req_mes("scripts/home/php/mes_content.php?" + sender ,"mes_content");
}
mes_load.php
the $sender var is created by passing the sender username through the URL. That is why I do php explode on the url.
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<div id=\"mes_content\"></div>";
echo "<div id=\"mes_field\" class=\"right\"></div>";
mes_content.php
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<table id=\"mesView-table\">";
$REC = array();
$SENT = array();
$ID = array();
for ($i = 0; $i < 25; $i++)
{
$rec = mysqli_fetch_array($recieved);
$sent = mysqli_fetch_array($sent);
if ($rec['id'] > 0)
{
$REC[$i] = $rec['id'];
}
if ($sent['id'] > 0)
{
$SENT[$i] = $sent['id'];
}
}
$ID = array_merge($SENT, $REC);
sort($ID);
for ($x = 0; $x < count($ID); $x++)
{
$key = $ID[$x];
$result = mysqli_query($con, "SELECT * FROM messages WHERE id = '$key'");
$res = mysqli_fetch_array($result);
if (in_array($key, $REC))
{
echo "<tr><td class='mes_recieved'>";
echo $res['message'];
echo "</tr></td>";
}
elseif (in_array($key, $SENT))
{
echo "<tr><td class='mes_sent'>";
echo $res['message'];
echo "</tr></td>";
}
}
echo "</table>";
Set async to false in your ajax requests!That's how the second one will wait for completing the first one and then start.
Also you can catch the on success and on error for the purposes you have.
Just use the "success" and "error" callbacks.
Also you could use the "done" callback
But, IMO, for that kind of problem I think a better alternative would be using Websockets
EDIT:
Here is some example of how you could do it:
jQuery.ajax({
type : "POST",
data : {msg:"your message"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
}).done(secondCall());
function secondCall(){
jQuery.ajax({
type : "POST",
data : {data:"data"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
});
}
EDIT2:
For visibility, here is a tutorial using websockets: http://www.sanwebe.com/2013/05/chat-using-websocket-php-socket

Categories