Database won't connect, no results returned - javascript

So I've got three PHP files, and I'm trying to connect my database through these files. It won't seem to connect, I'm trying to connect it so then my ajax in my javascript file will hopefully work.
BaseClass.php:
<?php
require("Conn.php");
require("MySQLDao.php");
$handle = fopen("php://input", "rb");
$raw_post_data = '';
while (!feof($handle)) {
$raw_post_data .= fread($handle, 8192);
}
fclose($handle);
if (empty($raw_post_data))
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "No Data Recieved";
echo json_encode($returnValue);
return;
}
else
{
$dao = new MySQLDao();
if ($dao->openConnection() == false)
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "Connection Could Not Be Established Between Server And Database";
echo json_encode($returnValue);
}
else
{
//Decodes data, dont change
$body = json_decode($raw_post_data, true);
$recieved = $body["data"];
//Gets the result of a query
//$result = $dao->MySQLDaoMethodName(parameters);
//Return the result of the query
echo json_encode($result);
}
$dao->closeConnection();
return;
}
?>
When I run this in chrome all it shows is:
{"status":false,"title":"Error","message":"No Data Recieved"}
MySQLDao.php:
<?php
//Class for holding queries
class MySQLDao
{
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $mysqli = null;
var $dbname = null;
var $result = null;
//constructor
function __construct()
{
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
//Attempt a connection to the database
public function openConnection()
{
//Try and connect to the database
$this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
//If the connection threw an error, report it
if (mysqli_connect_errno())
{
return false;
}
else
{
return true;
}
}
//Get method for retrieving the database conection
public function getConnection()
{
return $this->mysqli;
}
//Close the connection to the database
public function closeConnection()
{
//If there is a connection to the database then close it
if ($this->mysqli != null)
$this->mysqli->close();
}
//-----------------------------------QUERY METHODS-------------------------------------
public function getResults($data)
{
$sql = "SELECT room.room_description FROM room WHERE room.room_id = 1";
$result = $this->mysqli->query($sql);
//if (mysql_num_rows($result) == 1) {
// $obj = mysql_fetch_object($result, 'obResults');
//}
echo json_encode($result);
echo($result);
}
}
?>
Nothing shows when I run this in chrome. Even when I put echo statements in some of the functions.
Conn.php:
<?php
class Conn
{
public static $dbhost = "***";
public static $dbname = "***";
public static $dbuser = "***";
public static $dbpass = "";
}
?>
part of my test.html:
function callPHP() {
$.ajax ({
type: "GET",
datatype: "application/json",
url: "MySQLDao.php",
data: { action : 'getResults()' },
//error: function(err){console.log(err)},
success: function(output) {
console.log(output);
}
//error, function(err){console.log(err)}
});
}
I basically just want to be able to write query methods and transport the results from these querys to my js, this is because I have a few graphs in my javascript and I want to get data from the database. All this code doesn't produce any errors I believe but it's just not returning anything back.
All help appreciated! Thanks!

Related

How to read a json file which contains an array from javascript

Please guys help me because i can't find out what i can do in order to read my javascript a json file which contains an array with one element.
My php file is working fine and the output is a .json file which contains this line: {"posts":[["30"]]}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];
$sql= "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$response = array();
$posts = array();
$result=mysqli_query($link, $sql);
while($row=mysqli_fetch_assoc($result)) {
$site_id=$row['site_id'];
$posts[] = array($site_id);
}
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
// Close connection
mysqli_close($link);
?>
Can anybody help me what i have to do (without using ajax) in order my javascript function reads that value? I want to rerad this value cause i want to manipulate this number.
function load3() {
var flag1 = true;
do{
var selection = window.prompt("Give the User Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection)) {
flag1=false;
}
}
while(flag1!=false);
$("#user_id").val(selection)
var flag2 = true;
do{
var selection2 = window.prompt("Give the Book Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection2)) {
flag2=false;
}
}
while(flag2!=false);
$("#book_id").val(selection2)
var flag3= true;
do{
var selection3 = window.prompt("Give the Game Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection3)) {
flag3=false;
}
}
while(flag3!=false);
$("#game_id").val(selection3)
//i do not want to do with ajax!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$.ajax({
type: 'POST',
url: 'http://127.0.0.1/PHP/loo.php',
data: $('#LoadGame').serialize(),
success: function (html) {
//do something on success?
$('#outPut').html(html);
var bingoValue=4;
if( $('#outPut').text().indexOf(''+bingoValue) > 0){
//alert('bingo!');
window.location.href='https://support.wwf.org.uk/';
//document.location.replace('https://developer.mozilla.org/en-US/docs/Web/API/Location.reload');
}
else {
alert('No!');
}
}
});
}
Thank you for your help!
Assuming this PHP code runs during your doc request,
You can read that json if you put it in a script tag
<script type="text/javascript">
window.myJson = <?php echo(json_encode($response)); ?>
</script
and it will be accessible as window.myJson in frontend

Display message after successful delete

I want to display a message after a record has been successfully deleted. I tried everything but without success.
I have an external js file from which I call a PHP file that deletes the record.
JS file:-
// Delete records
function DeleteGoal(ids) {
$.post("ajax/deletegoal.php", {
userid: ids.user_id,
goalid: ids.goal_id
},
function (data, status) {
// reload goals
ShowGoals();
}
);
var jsuccess = $("#myPhpValue").val();
console.log(jsuccess);
}
PHP file:-
<?php
if(isset($_POST['userid']) && isset($_POST['goalid']))
{
// include Database connection file
require('../../login_system/db.php');
$userid = $_POST['userid'];
$goal_id = $_POST['goalid'];
// $query = "DELETE from goals where user_id = '$userid' AND goal_id='$goal_id'";
// if (!$result = $mysqli->query($query)) {
// exit(mysqli_error($mysqli));
// }
$success = "true";
echo '<form><input type="hidden" id="myPhpValue" value="'.$success.'"/></form>';
mysqli_close($mysqli);
}
?>
I tried to send the $success variable back to js file with several ways but none worked. It seems that any output command (echo, alert, console.log) doesn't display anything and I don't know why.
I would appreciate any help!
You could simply return using echo and display the response directly :
a.php:
<?php
if(isset($_POST['userid']) && isset($_POST['goalid']))
{
...
echo true;
}
?>
A.js:
function DeleteGoal(ids) {
$.post("ajax/deletegoal.php", {
userid: ids.user_id,
goalid: ids.goal_id
},
function (response) {
if( response ){
// reload goals
ShowGoals();
console.log("Success message");
}
}
);
}
You could return a json format what gives you the ability to return multiple info like :
A.js:
function DeleteGoal(ids) {
$.post("ajax/deletegoal.php", {
userid: ids.user_id,
goalid: ids.goal_id
},
function (data) {
var response = $.parseJSON(data);
if( response.success ){
// reload goals
ShowGoals();
console.log(response.message);
}
}
);
}
a.php:
<?php
if(isset($_POST['userid']) && isset($_POST['goalid']))
{
echo jdon_encode(['success'=>true,"message"=>"Deleted Successfully"]);
}
?>
finally I did it!
PHP file
<?php
if(isset($_POST['userid']) && isset($_POST['goalid']))
{
// include Database connection file
require('../../login_system/db.php');
$userid = $_POST['userid'];
$goalid = $_POST['goalid'];
$query = 'DELETE from goals where userid ='.$userid.' AND goal_id='.$goalid;
if (!$result = $mysqli->query($query)) {
exit(mysqli_error($mysqli));
}
$data = true;
echo($data);
mysqli_close($mysqli);
}
?>
JS file
// Delete records
function DeleteGoal(ids) {
$.post("ajax/deletegoal.php", {
userid: ids.user_id,
goalid: ids.goal_id
},
function (data, status) {
// reload goals
if (data==true && status =="success")
ShowGoals();
else
alert("Problem");
}
);
}
So, I return what happen using data variable.

Using AJAX for query to MySQL database

I'm using the JavaScript function setInterval every 30 seconds to check the MySQL table with AJAX. Using AJAX it updates the page with new results without reloading the page.
I would like to use the effect highlight to colour certain records, in the example below this highlights ID 1 and 10:
$("#image_li_1").effect("highlight", {}, 25000);
$("#image_li_10").effect("highlight", {}, 25000);
I would like to highlight all new records that have been added since the last load.
index.php
// Run polling function every 60 seconds
var myVar = setInterval(myfunction, 30000);
// Load data from check_status page
function myfunction() {
$.ajax({
url: "check_status.php", success: function(result2) {
$("#div2").html(result2);
$("#title").html("Food Items AUTO Poll");
$("#image_li_1").effect("highlight", {}, 25000);
$("#image_li_10").effect("highlight", {}, 25000);
}
});
}
check_status.php
// Include and create instance of db class
require_once 'DB.class.php';
$db = new DB();
<?php
// Fetch all items from database
$data = $db->getRows();
if (!empty($data)) {
foreach ($data as $row) {
?>
<li id="image_li_<?php echo $row['id']; ?>" class="ui-sortable-handle">
<a href="javascript:void(0);" style="float:none;" class="image_link">
<?php echo $row['name']; ?>
</a>
</li>
<?php
}
}
?>
DB.class.php
<?php
class DB {
// Database configuration
private $dbHost = "###";
private $dbUsername = "###";
private $dbPassword = "###";
private $dbName = "###";
private $itemTbl = "###";
function __construct() {
if (!isset($this->db)) {
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
if ($conn->connect_error) {
die("Failed to connect with MySQL: " . $conn->connect_error);
} else {
$this->db = $conn;
}
}
}
// Get rows from data table
function getRows() {
$query = $this->db->query("SELECT * FROM ".$this->itemTbl." ORDER BY img_order ASC");
if ($query->num_rows > 0) {
while ($row = $query->fetch_assoc()) {
$result[] = $row;
}
} else {
$result = FALSE;
}
return $result;
}
send ajax request to server each some second
respond json-formatted data, not html from your server controller
if this is first request, save it into "current" and "previous" variables
if this is not first request, save it into "current" variable
Display your data in your html page. During this operation compare "current" and "previous" variables, if something new in "current" highlight it
before next request to server, make assignment: previous = current
profit
Try to search and read something like "create REST service php". You should get main idea of such approach. Generally, your code should look like this:
php.php
<?php
$yourDatabaseClass = new YourDatabaseClass("localhost", "username", "password", "database");
$data = $yourDatabaseClass->getTable("select * from table");
echo json_encode($data);
Your js:
var oldData = [];
var currentData = [];
var yourElement = document.getElementById('application');
client.doRequest("php.php").then(function(response){
currentData = response;
renderData();
})
function renderData() {
yourElement.innerHTML = '';
currentData.forEach(function(item){
if(isNew(item)) {
yourElement.apendChild(createHighlightedData(item));
} else {
yourElement.apendChild(createOrdinarData(item));
}
})
}
function createHighlightedData(item) {
return ...
}
function createOrdinarData(item) {
return ...
}

EOF / Failed to load error when calling PHP file with AJAX

Apparently my POST requests are being cancelled?
http://puu.sh/d73LC/c6062c8c07.png
and also, mysqli_result object has all null values when i query the database with a select query:
object(mysqli_result)[2]
public 'current_field' => null
public 'field_count' => null
public 'lengths' => null
public 'num_rows' => null
public 'type' => null
here is my php file:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "uoitlol";
$name = "test1"; //this should be $_POST['name']; test1 is just to test if it works.
$err = false;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_errno > 0) {
echo 'connerr';
die();
}
$sql = "INSERT INTO summoners (name) VALUES (?)";
$getname = "SELECT name FROM summoners";
$result = $conn->query($getname);
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
if ($err === false) {
if (!$stmt->execute()) {
echo 'sqlerr';
} else {
echo 'success';
}
}
$stmt->close();
mysqli_close($conn);
here is my javascript file, which calls the php file with ajax whenever i click submit on my form (in a different html file)
$(document).ready(function () {
$("#modalClose").click(function () {
document.getElementById("signupInfo").className = "";
document.getElementById("signupInfo").innerHTML = "";
});
$("#formSubmit").click(function () {
var name = $("#name").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = {'name' :name};
if (name === '')
{
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>Please enter a summoner name!</b>";
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "submitName.php",
data: dataString,
cache: false,
success: function (msg) {
if (msg === 'error'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>That summoner name is already in the database!</b>";
} else if (msg === 'sqlerror'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>SQL error, contact the administrator.</b>";
} else if (msg === 'success'){
document.getElementById("signupInfo").className = "alert alert-success";
document.getElementById("signupInfo").innerHTML = "<b>Summoner successfully added!</b>";
}
}
});
}
return false;
});
});
I'm getting these errors everytime I click my button that submits my form:
Failed to load resource: Unexpected end of file from server (19:41:35:538 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:35:723 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:36:062 | error, network)
at public_html/submitName.php
I'm using Netbeans IDE, if that matters.
puu.sh/d6YXP/05b5f3dc06.png - screenshot of the IDE, with the output log errors.
Remove this from your submitName.php, unless there really is HTML in it.
<!DOCTYPE html>
If there is HTML in it, do this instead.
<?php
//your PHP code//
?>
<!DOCTYPE html>
//your HTML here//
</html>
Also, if submitName.php contains no HTML, make sure there is no blank line after ?> at the bottom.
EDIT: In regards to your query failing, try this code.
if (!empty($name) { //verify the form value was received before running query//
$getname = "SELECT name FROM summoners WHERE name = $name";
$result = $conn->query($getname);
$count = $getname->num_rows; //verify a record was selected//
if ($count != 0) {
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
} else {
echo "no record found for name";
exit;
}
}
Drop the ?> at the end of the php file and instead of using var dataString = 'name=' + name; use this instead:
var data = { "name" : name};
jQuery will automagically do the dirty stuff for you so that you don't have to special text-escape it and stuff.
That's as far as I can help without any log files and just a quick skim of your code.

How to generate an excel file using js

I have a UI that shows a CRUD(create, read, update and delete) account of an employee. Now, I want to add a generate button that when its click, a window will pop-up that will show and ask if the following data in the grid lines under the UI are to be open or saved using the excel report.Also, I have already EXcelPhp library.
Here's my code for my 'actions.class.php':
public function executeLoadEmployeeList(sfWebRequest $request)
{
// $start = $request->getParameter('start') ? $request->getParameter('start'): 2;
// $limit = $request->getParameter('limit') ? $request->getParameter('limit'): 2;
$query = pg_escape_string($request->getParameter('query'));
$start = $request->getParameter('start');
$limit = $request->getParameter('limit');
if(isset($limit))
{
$page = $start / $limit;
$page ++;
}
else
$page = 1;
$criteria = Doctrine_Query::create();//what is the query?? is it select,inset,update,delete?
$criteria->select("(fname || ' ' || lname) AS fullname, department");
$criteria->from('Employees'); // Select * from profile
$criteria->orderBy('id'); // order by id
//print $criteria->getSqlQuery();
//die();
if($query!=null)
{
$criteria->where("(fname ilike '%$query%' or lname ilike '%$query%' or department ilike '%$query%')"); //where (uname ilike '%$query%' or status ilike '%$query%')
}
$allData = $criteria->fetchArray();
// print "<pre>";
// print_r($allData);
// die();
$this->pager = new sfDoctrinePager('Employees', 20); //what is sfdoctrine about? dont mind this.. this is a symphony built in class for pager
$this->pager->setQuery($criteria);
$this->pager->setPage($page);
$this->pager->init();//What is the purpose of this line? //initialize sfDoctrinePager
$result['data'] = $this->pager->getResults();
$result['totalCount'] = count($allData);
$result['limit'] = $limit;
$result['page'] = $page;
$result['query'] = $query;
die(json_encode($result));
}
public function executeAddEmployee(sfWebRequest $request)
{
try{
$fname = $request->getParameter('fname');
$lname = $request->getParameter('lname');
$department = $request->getParameter('department');
$Employee = new Employees();
$Employee->fname = $fname;
$Employee->lname = $lname;
$Employee->department = $department;
//save the data to the database
$Employee->save();
$data = array("success"=> true, "data"=>"Employee Added.");
}
catch(Exception $e)
{
$data = array("success"=> false, "data"=>$e->getMessage());
}
//$data is a return value of trycatch
die(json_encode($data));
}
public function executeDeleteEmployee(sfWebRequest $request)
{
try{
//what is Doctrine::getTable's purpose // to get the table profile
$this->forward404Unless($Employee = Doctrine::getTable('Employees')->find(array($request->getParameter('id'))), sprintf('Employee ID in Form does not exist (%s).', $request->getParameter('id')));
$Employee->delete();
$data = array("success"=> true, "data"=>"Employee record is Deleted.");
} catch(Exception $e) {
$data = array("success"=> false, "data"=>$e->getMessage());
}
//$data is a return value of trycatch
die(json_encode($data));
}
public function executeEditEmployee(sfWebRequest $request)
{
try{
$this->forward404Unless($Employee = Doctrine::getTable('Employees')->find(array($request->getParameter('id'))), sprintf('Employee ID in Form does not exist (%s).', array($request->getParameter('id'))));
$criteria = Doctrine_Query::create();
$criteria->select('fname,lname,department');
$criteria->from('Employees');
$criteria->where('id = ?', $request->getParameter('id'));//('id = ?', $request->getParameter('id') means... id = $request->getParameter('id')
$result = $criteria->fetchArray();
$record['fname'] = $Employee['fname'];
$record['lname'] = $Employee['lname'];
$record['department'] = $Employee['department'];
$data = array("success"=> true, "data"=>$record);
} catch(Exception $e) {
$data = array("success"=> false, "data"=>$e->getMessage());
}
//$data is a return value of trycatch
die(json_encode($data));
}
public function executeUpdateEmployee(sfWebRequest $request)
{
try{
$Employee = Doctrine::getTable('Employees')->find(array($request->getParameter('id')));
$Employee->fname = $request->getParameter('fname');
$Employee->lname = $request->getParameter('lname');
$Employee->department = $request->getParameter('department');
//save the update to the database
$Employee->save();
$data = array("success"=> true, "data"=>"Employee Successfully Updated.");
}
catch(Exception $e)
{
$data = array("success"=> false, "data"=>$e->getMessage());
}
//$data is a return value of trycatch
die(json_encode($data));
}
public function executeGenerateEmployee(sfWebRequest $request)
{
// ...
}**
What I've tried so far is setting only the generate button and there's no action yet. This is under my try.js:
var generateItem = new Ext.Action ({
text: 'Generate Excel Report',
width: 60,
enabled: true,
});
Could someone help me regarding this issue?
You can not generate an excel file without using a server side language / script. You can just prepare how it Will look and add some functions to make it functional like write, delete etc.
You can generate an Excel spreadsheet without any server side processing however you'll have a hellish time with browser support.
In theory you could generate an excel formatted file in js then simply do a window.open with the data URI.
for example here's a javascript generated image:
window.open('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC');
however.. it'll probably not be supported in most of the browsers for Excel data URIs:
here's another similar question:
Data URI used to export to CSV/Excel (no server-side request) : browser support/limitations?

Categories