Ajax call works in stand alone, but fails in wordpress - php

This code is working in stand alone, but when it gets put into wordpress it gives a series of errors related to the ajax call. The first problem it had was that it couldn't read the jquery from the remote source so I downloaded the file and have it read internal to the server, but these errors are still left and I'm not sure how to correct this. Note that in wordpress, I use a plugin that allows me to use [php] and [/php] to use php within wordpress.
<?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 = "";
$password = "";
$dbname = "";
$chanarray[] = null;
// 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['outArray'];
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;
}
?>
Here are the errors:

Change $(document).ready(function() { to jQuery(function($){ because WordPress runs jQuery in no-conflict mode.
Source: https://wordpress.org/support/topic/simple-jquery-not-working/

Related

Specific information on how to insert into html table

I am trying to use the results of a database and display them in an HTML table. I've searched around but can't find a specific answer for my situation as I am new to PHP and I had to copy this code from another source because I was unable to get it to work on my own. Please help.
<?php $server = "127.0.0.1";
$user = "admin";
$pass = "password";
$dbname = "hysteryalelogs";
// Create connection in mysqli
$connection = new mysqli($server, $user, $pass, $dbname);
//Check connection in mysqli
if($connection->connect_error){
die("Error on connection:" .$connection->connect_error);
}
//Display the informaion
$sql = "SELECT * FROM logs";
$res = $connection->query($sql);
if($res->num_rows > 0){
while($row = $res->fetch_assoc()){
echo "Sales Number: ". $row["Sales_Number"]. "<br/>";
echo "Quantity: ". $row["Quantity"]. "<br/>";
echo "Due Date: ". $row["Due_Date"]. "<br/>";
echo "Burnished Housing: ". $row["Burnished"]. "<br/>";
echo "Greased Bearings: ". $row["Grease"]. "<br/>";
echo "Air Cleaned: ". $row["Air"]. "<br/>";
echo "SS Screw: ". $row["Screw"]. "<br/>";
echo "Test Date: ". $row["Test_Date"]. "<br/>";
echo "Pass: ". $row["Pass"]. "<br/>";
echo "Fail: ". $row["Fail"]. "<br/>";
echo "Tester: ". $row["Tester"]. "<br/>";
echo "Final Check: ". $row["Final_Check"]. "<br/>";
echo "Green Dot: ". $row["Green_Dot"]. "<br/>";
echo "Green Dot Check: ". $row["Green_Dot_Check"]. "<br/>";
echo "Ship Date: ". $row["Ship_Date"]. "<br/>";
echo "Serial Number: ". $row["Serial_Number"]. "<br><br><hr><br/>";
}
} else {
echo "No Record Found!";
}
$connection->close();
?>
(clarification) The code works. I Just don't know how to format the table for it to display inside.
Hi :) Hope this helps :)
<?php
$server = "127.0.0.1";
$user = "admin";
$pass = "password";
$dbname = "hysteryalelogs";
// Create connection in mysqli
$connection = new mysqli($server, $user, $pass, $dbname);
//Check connection in mysqli
if($connection->connect_error){
die("Error on connection:" .$connection->connect_error);
}
//Display the informaion
$sql = "SELECT * FROM logs";
$res = $connection->query($sql);
if($res->num_rows > 0){
echo "<table border='3px' cellpadding='5px' cellspacing='5px' align='center' bgcolor='skyblue' ";
echo "<tr>";
echo "<td><center><strong>Sales Number</strong></center></td>";
echo "<td><center><strong>Quantity</strong></center></td>";
echo "<td><center><strong>Due Date</strong></center></td>";
echo "<td><center><strong>Burnished Housing</strong></center></td>";
echo "<td><center><strong>Greased Bearings</strong></center></td>";
echo "<td><center><strong>Air Cleaned</strong></center></td>";
echo "<td><center><strong>SS Screw</strong></center></td>";
echo "<td><center><strong>Test Date</strong></center></td>";
echo "<td><center><strong>Pass</strong></center></td>";
echo "<td><center><strong>Fail</strong></center></td>";
echo "<td><center><strong>Tester</strong></center></td>";
echo "<td><center><strong>Final Check</strong></center></td>";
echo "<td><center><strong>Green Dot</strong></center></td>";
echo "<td><center><strong>Green Dot Check</strong></center></td>";
echo "<td><center><strong>Ship Date</strong></center></td>";
echo "<td><center><strong>Serial Number</strong></center></td>";
echo "</tr>";
while($row = $res->fetch_assoc()){
echo "<tr>";
echo "<td>"."<center>"."<i>".$row["Sales_Number"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Quantity"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Due_Date"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Burnished"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Grease"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Air"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Screw"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Test_Date"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Pass"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Fail"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Tester"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Final_Check"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Green_Dot"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Green_Dot_Check"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Ship_Date"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Serial_Number"]."</i>"."</center>"."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "No Record Found!";
}
$connection->close();
?>

How to generate a Log file in my machine when batch file is run as cronjob

Im running a Batch file as cronJob in my windows 7 machine,all I wanted is I want to create a log file ,when the cron Job is run along with the data,which it was displaying in the console.
The data ,is the echo statements which are present in the index.php which i have imported in the batch file.
Help me out to solve this issue.
index.php
<?php
echo "Welcome" ;
$fileD = "Login_".date('Y-m-d').".csv";
$fp1 = fopen($fileD, 'a+');
//Getting the files from below mentioned folder
$iterator1 = new FilesystemIterator("C:/wamp/www/logs1");
$iterator2 = new FilesystemIterator("C:/wamp/www/logs2");
$filelist = array();
foreach($iterator1 as $GLOBALS['entry1'])
{
if (strpos($entry1->getFilename(), "p1") === 0)
{
$filelist[] = $entry1->getFilename();
echo $entry1;
}
}
foreach($iterator2 as $GLOBALS['entry2']) {
if (strpos($entry2->getFilename(), "p2") === 0) {
$filelist[] = $entry2->getFilename();
echo "<br>";
echo $entry2;
}
}
$file1 = file_get_contents($entry1);
fwrite($fp1, $file1);
$file1 = file_get_contents($entry2);
fwrite($fp1, $file1);
fclose($fp1);
echo "<br/>";
echo "Done";
echo "<br/>";
//Deletes log file present in the logs folder
$n1= "$entry1";
if(!unlink($n1))
{
echo ("Error deleting file1 $n1");
}
else
{
echo ("Deleted $n1");
}
echo "<br/>";
$n2= "$entry2";
if(!unlink($n2))
{
echo ("Error deleting file2 $n2");
}
else
{
echo ("Deleted $n2");
}
echo "<br/>";
foreach (glob("*.csv") as $filename)
{
echo "$filename size " . filesize($filename) . "\n";
echo "<br>";
}
echo "<br>";
//$insertionDate = substr($filename,6,10);
$servername = "localhost";
$username = "user";
$password = "";
$dbname = "stat";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$file = file_get_contents($fileD);
$count = preg_match_all("/,Login,/", $file, $matches);
echo "Csv first word ";
$insertionDate = substr($file,1,10);
echo "<br/>";
echo "Total Hits:" . $totalLines = count(file($fileD));
echo "<br/>";
echo "Login:" . $count;
// Insert the Total hits and the corresponding success and failure count
$sql = "INSERT INTO hit_s (HitDate, count, category,success,failure,tcount,ocount)
VALUES ('$insertionDate', $totalLines, 'Hits',$success,$fail,$treeCnt,$oCnt)";
if ($conn->query($sql) === TRUE) {
echo "Total hits record inserted successfully \n";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$iterator = new FilesystemIterator("C:/wamp/www/Fed");
$filelist1 = array();
foreach($iterator as $GLOBALS['entry3'])
{
if (strpos($GLOBALS['entry3']->getFilename(), "*.csv") === 0)
{
$filelist1[] = $GLOBALS['entry3']->getFilename();
}
}
echo $GLOBALS['entry3'];
echo "<br/>";
$entry3="$fileD";
$n3= "$entry3";
if(!unlink($n3))
{
echo ("Error deleting $n3");
}
else
{
echo ("Deleted $n3");
}
echo "<br/>";
$conn->close();
?>
In batch file im calling the index.php file like below
C:\wamp\bin\php\php5.4.16\php.exe C:\wamp\www\Fed\csv\index.php
It looks like syslog will work for you:
$access = date("Y/m/d H:i:s");
syslog(LOG_WARNING, "Unauthorized client: $access {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']);

Limiting Data in php mysql

I have made a slambook, it is still under contruction.
I have written the following code :
<?php
$n=$_REQUEST['n'];
$n=strtolower($n);
echo "<html><body alink=black vlink=black link=black><center><h1>";
$target_dir = "fu/uploads/";
$target_file = $target_dir . $n . ".jpg";
if (file_exists($target_file)) {
echo "<img src=\"http://slambook.esy.es/fu/uploads/".$n.".jpg\" width=85 height=85 alt=\"Profile Pic\">";
}
echo "Welcome to your wall, ".$n."</h1><br><br>";
echo "<button>Change Password</button><br><br>";
echo "<form action=\"visit.php\" method=\"get\">";
echo "<input type=\"hidden\" name=\"u\" value=\"".$n."\">";
echo "<input type=\"text\" name=\"n\" placeholder=\"Search A Nickname\">";
echo "<input type=submit value=\"Search By Nickname\"></form>";
echo "<form action=\"sbi.php\" method=\"post\">";
echo "<input type=\"hidden\" name=\"u\" value=\"".$n."\">";
echo "<input type=\"text\" name=\"id\" placeholder=\"Search A id\">";
echo "<input type=submit value=\"Search By Id\"></form>";
$post="http://slambook.esy.es/post.php?n=".$n;
echo "Fill Someone's Slambook<br><br><br>";
$servername = "myhost";
$username = "myusername";
$password = "mypass";
$dbname="mydatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT i,f,e,p,m,d FROM ".$n." ORDER BY i DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<center><table border=2><tr><th>Date</th><th>From</th><th>Email</th><th>Phone</th><th>Message</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
$from=$row["f"];
echo "<tr><td>".$row["d"]."</td><td>".$from."</td><td>".$row["e"]."</td><td> ".$row["p"]."</td><td>".$row["m"]."</td></tr>";
}
echo "</table></center>";
} else {
echo "Your slambook has been filled by 0 people!";
}
$conn->close();
?>
But on running this wall.php, all records are printed on one page.
I wanted to limit the data per page and use the paging system.
What i wanted is at the end to the table,
a "previous post" link must be there which would show the next posts.
But i tries many times and what i came out with is this :
<?php
$n=$_REQUEST['n'];
$p=$_REQUEST['p'];
$n=strtolower($n);
if($p=="")
$p=2;
$ipp=2;
$os=($p-1)*$ipp;
echo "<html><body alink=black vlink=black link=black><center><h1>";
$target_dir = "fu/uploads/";
$target_file = $target_dir . $n . ".jpg";
if (file_exists($target_file)) {
echo "<img src=\"http://slambook.esy.es/fu/uploads/".$n.".jpg\" width=85 height=85 alt=\"Profile Pic\">";
}
echo "Welcome to your wall, ".$n."</h1><br><br>";
echo "<button>Change Password</button><br><br>";
echo "<form action=\"visit.php\" method=\"get\">";
echo "<input type=\"hidden\" name=\"u\" value=\"".$n."\">";
echo "<input type=\"text\" name=\"n\" placeholder=\"Search A Nickname\">";
echo "<input type=submit value=\"Search By Nickname\"></form>";
echo "<form action=\"sbi.php\" method=\"post\">";
echo "<input type=\"hidden\" name=\"u\" value=\"".$n."\">";
echo "<input type=\"text\" name=\"id\" placeholder=\"Search A id\">";
echo "<input type=submit value=\"Search By Id\"></form>";
$post="http://slambook.esy.es/post.php?n=".$n;
echo "Fill Someone's Slambook<br><br><br>";
$servername = "myhost";
$username = "myuser";
$password = "mypass";
$dbname="mydatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM ".$n." ORDER BY id DESC LIMIT ".$os.",".$ipp."";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$page_count = (int)ceil($result / $ipp);
// double check that request page is in range
if($p > $page_count) {
// error to user, maybe set page to 1
$p = 1;
}
echo "<center><table border=2><tr><th>Date</th><th>From</th><th>Email</th><th>Phone</th><th>Message</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
$from=$row["f"];
echo "<tr><td>".$row["d"]."</td><td>".$from."</td><td>".$row["e"]."</td><td> ".$row["p"]."</td><td>".$row["m"]."</td></tr>";
}
echo "</table></center>";
echo "Previous Posts";
} else {
echo "No more Posts";
}
$conn->close();
?>
But in this, there were 5 records and records per page was set to 2 so only two pages are visible and the 5th record (should be on page 3) never turns up.
What should I do to fix this error ?
U can use Datatables for more easy pagination, check this, and tell me if work for u

PHP/MYSQL Multiple Search Form not showing records with large database content

My search form works when I'm querying in a database with around 10 records only, but when I go more than that, it doesn't show any records and goes to my else "0 records" Please help, below is my php code.
<?php
$sfname = $_POST["fname"];
$sgen = $_POST["gen"];
$sdoc = $_POST["doc"];
$smisc = $_POST["misc"];
$ssick = $_POST["sick"];
$sothers = $_POST["others"];
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(!empty($sfname) || !empty($sgen) || !empty($sdoc) || !empty($smisc) || !empty($ssick) || !empty($sothers) ){
$genQueryPart = !empty($sgen) ? "Gender LIKE '%$sgen%'" : "";
$fnameQueryPart = !empty($sfname) ? "FullName LIKE '%$sfname%'" : "";
$docQueryPart = !empty($sdoc) ? "Doctor LIKE '%$sdoc%'" : "";
$miscQueryPart = !empty($smisc) ? "Misc LIKE '%$smisc%'" : "";
$sickQueryPart = !empty($ssick) ? "Sickness LIKE '%$ssick%'" : "";
$othersQueryPart = !empty($sothers) ? "Others LIKE '%$sothers%'" : "";
$arr = array($genQueryPart, $fnameQueryPart,$docQueryPart,$miscQueryPart,$sickQueryPart,$othersQueryPart);
$sql = "select * from index where";
$needsAnd = false;
for ($i = 0; $i < count($arr); $i++) {
if ($arr[$i] != "") {
if ($needsAnd) {
$sql .= " AND ";
}
$needsAnd = true;
$sql .= " " . $arr[$i];
}
}
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>File ID</th>";
echo "<th>Full Name</th>";
echo "<th>Gender</th>";
echo "<th>Doctor</th>";
echo "<th>Misc</th>";
echo "<th>Sickness</th>";
echo "<th>Others</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['FileID']."</td>";
echo "<td>".$row['FullName']."</td>";
echo "<td>".$row['Gender']."</td>";
echo "<td>".$row['Doctor']."</td>";
echo "<td>".$row['Misc']."</td>";
echo "<td>".$row['Sickness']."</td>";
echo "<td>".$row['Others']."</td>";
echo "</tr>";
}
echo "</table>";
}
else {
echo "0 results";
}
} else {
echo "You must enter at least one value";
}
mysqli_close($conn);
?>
Have you tried buffering the results?
$result = mysqli_query($conn, $sql);
mysqli_store_result($conn);
if(mysqli_num_rows($result) > 0) {
...
}
from PHP Manual:
The behaviour of mysqli_num_rows() depends on whether buffered or unbuffered result sets are being used. For unbuffered result sets, mysqli_num_rows() will not return the correct number of rows until all the rows in the result have been retrieved.
May be issue with your empty() function (depends on your data), use isset() instead.
empty() : will return true if the variable is an empty string, false, array(), NULL, “0?, 0, and an unset variable.
isset() : will return true only when the variable is not null.
EDIT
User got answer from my comments below
Try debug like this: print $sql before the mysqli_query, copy sql in phpmyadmin and check the query result and query itself.

Function prepare() on a non-object error

I have looked up the error for this and I think I am calling the statement before for it to be initialized. I have made a simple connection class that I can include into all of my files that will be talking to the mysql server. Knowing how I am with things, I am most likely over thinking things. I cant seem to find what I am doing wrong.....
Top part of the code is cut off as it only contains the HTML head and php starting code that is non-important for this.
//include database connection
include('connection.php');
$action = isset($_GET['action']) ? $_GET['action']: "";
if($action=='delete'){ //if the user clicked ok, run our delete query
try {
$query = "DELETE FROM sc_steamgames WHERE appid = ?";
$stmt = $con->prepare($query);
$stmt->bindParam(1, $_GET['appid']);
$result = $stmt->execute();
echo "<div>Record was deleted.</div>";
}catch(PDOException $exception){ //to handle error
echo "Error: " . $exception->getMessage();
}
}
//select all data
$query = "SELECT * FROM sc_steamgames";
$stmt = $con->prepare( $query );
$stmt->execute();
//this is how to get number of rows returned
$num = $stmt->rowCount();
echo "<a href='add.php'>Create New Record</a>";
if($num>0){ //check if more than 0 record found
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th>AppID</th>";
echo "<th>Title</th>";
echo "<th>Release Date</th>";
echo "<th>Last Updated</th>";
echo "</tr>";
//retrieve our table contents
//fetch() is faster than fetchAll()
//http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$appid}</td>";
echo "<td>{$title}</td>";
echo "<td>{$releasedate}</td>";
echo "<td>{$lastupdate}</td>";
echo "<td>";
//we will use this links on next part of this post
echo "<a href='edit.php?id={$appid}'>Edit</a>";
echo " / ";
//we will use this links on next part of this post
echo "<a href='#' onclick='delete_user( {$appid} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{ //if no records found
echo "No records found.";
}
?>
<script type='text/javascript'>
function delete_user( appid ){
//this script helps us to
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id to the record to be deleted
window.location = 'index.php?action=delete&id=' + appid;
}
}
</script>
</body>
</html>
connection.php
/* Database Info */
// Host/IP
$host = "localhost";
// Database Name
$db_name = "**";
// Username
$username = "**";
//Password
$password = "**";
/* End Database Info */
try {
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
echo "Connection error: " . $exception->getMessage();
}

Categories