I have the following PHP code that is capturing and encoding JSON data ready to be used by an Ext.js file:
<?php
$Query = "SELECT `Department`,`DepartmentHeadID` FROM `Department`";
$Result = mysql_query($Query) or die("Error 01: " . mysql_error());
while($r = mysql_fetch_array($Result))
{
// Create JSON Data:
$rows[] = $r;
echo $r[0];
echo "<br />";
}
$Data = json_encode($r);
echo "<hr />";
echo $Data;
?>
$Data returns "false" when I echo it out by accessing the file directly.
I am then trying to capture and use this data with Ext.js and until I can resolve this "false" issue I'm a bit stuck.
No PDO being used due to the server PHP version as this is not a production environment and it's running on an internal server.
Any help greatly appreciated.
you are encoding $r in JSON.
$r is false when your loop has finished.
Encode $rows instead ;-)
Related
I know this is frequently asked question however I have tried using :
script language='javascript'
placed header in else after alert
script type='text/javascript'
Still I don't get alert box, while else parts executes perfectly.
Here's my code:
<?php
/* header('Content-Type: application/json');
$response = array(); */
if (isset($_GET['sid'])){
$con = mysqli_connect("localhost", "root", "", "kaemiphk_greivance");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$checkdata=mysqli_query($con,"SELECT * FROM officer_master WHERE pf_no = '".$_GET['sid']."'");
$query_data=mysqli_num_rows($checkdata);
if ($query_data == 0) {
//echo alert "welcome";
echo '<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js">';
echo "alert('PF No. Does not exist. Please Contact Admin!!!');";
echo '</script>';
}
else{
header('Content-Type: application/json');
$response = array();
$select="SELECT m.officer_name,m.email,m.department,m.mobile_no,m.designation,n.quarter_no,n.address,n.colony,n.blueprint_quarter,n.type_of_quarter, n.area FROM officer_master m, quarter_master n WHERE n.pf_no='".$_GET['sid']."' AND m.pf_no = n.pf_no";
$result = mysqli_query($con, $select); //mysql_query($qry);
while ($row = mysqli_fetch_assoc($result)) {
array_push($response, $row);
}
}
echo json_encode($response);
}
?>
What am I missing here.
Thanks
You have your js files mixed up.
Include jquery and then your script, inside separate tags:
echo '<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js" ></script>';
echo '<script type="text/javascript">';
echo "alert('PF No. Does not exist. Please Contact Admin!!!');";
echo '</script>';
By the way, you do NOT need jquery for a simple alert, as it is plain javascript. Try to avoid including external library if not needed, you will end up with a bloated code.
And printing js with php it's a bit of a hack. Why not just print it into your html or js file?
Javascript inside a script tag that has an src attribute does not get executed, you have to create a second script tag after the jquery one.
<?php
/* header('Content-Type: application/json');
$response = array(); */
if (isset($_GET['sid'])){
$con = mysqli_connect("localhost", "root", "", "kaemiphk_greivance");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$checkdata=mysqli_query($con,"SELECT * FROM officer_master WHERE pf_no = '".$_GET['sid']."'");
$query_data = mysqli_num_rows($checkdata);
if ($query_data == 0) {
//echo alert "welcome";
echo '<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js">';
echo '</script>';
echo "<script>alert('PF No. Does not exist. Please Contact Admin!!!');</script>";
} else {
header('Content-Type: application/json');
$response = array();
$select="SELECT m.officer_name,m.email,m.department,m.mobile_no,m.designation,n.quarter_no,n.address,n.colony,n.blueprint_quarter,n.type_of_quarter, n.area FROM officer_master m, quarter_master n WHERE n.pf_no='".$_GET['sid']."' AND m.pf_no = n.pf_no";
$result = mysqli_query($con, $select); //mysql_query($qry);
while ($row = mysqli_fetch_assoc($result)) {
array_push($response, $row);
}
}
echo json_encode($response);
}
}
?>
I have created a php script that submits a query and downloads the results in a CSV. I have created a bootstrap button where users can click to download the file. Some of the reports take longer to create and I wanted to show the user some sort of status that the script is running in the background.
I tried something simple like BlockUI from inside the PHP script. Using echo '<script type="text/javascript">$.blockUI();</script>'; in the beginning of the script and echo '<script type="text/javascript">$.unblockUI();</script>'; at the end but it didn't work.
Can someone help? I don't need a progress bar or anything fancy. I just need to show some type of status while the php script is running.
HTML:
...
<td class="pull-right"><a type="button" href="report1_download_csv.php" class="btn">Download</a></td>
...
PHP:
<?php
/* Set up and execute the query. */
$sql = "SELECT
FROM TABLE ";
$stmt = sqlsrv_query( $conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
foreach($row AS $key => $value){
$pos = strpos($value, '"');
if ($pos !== false) {
$value = str_replace('"', '\"', $value);
}
$out .= '"'.$value.'",';
}
$out .= "\n";
}
sqlsrv_free_stmt($results);
sqlsrv_close($conn);
// Output to browser with the CSV mime type
header("Content-type: text/x-csv");
$date = date('m-d-Y-His');
header("Content-Disposition: attachment; filename=Report1_{$date}_UTC.csv");
echo "Column1, Column2\n";
echo $out;
?>
use ajax to send request to server to do operation then show a spinner or any thing else untill server give you response.
I've been at this for hours trying to figure out why this will not work. I am trying to read data from my mysql database using php and jquery. In my php file it loops through a table and should echo the results of that table. I am using the jquery .get method to try and retrieve it but i get a 404 error file not found. The 404 error goes away and everything works fine if i change my php file to something simple like:
<?php echo 'Hello'; ?>
I believe the problem is in my php file because when i create a new file with just echoing a string and nothing else it returns everything fine.
$(document).ready(function() {
$.get("php/listtasks.php", function(data){
alert("Data: " + data);
})
});
My php file where i think there is a problem contains:
<?php // sqltest.php
require_once 'session.php';
require_once 'login.php';
$conn = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if($conn->connect_error) die($conn->connect_error);
$query = "SELECT * FROM list";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " . $conn->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
echo $row[2];
}
$result->close();
$conn->close();
?>
i am trying to modify a session variable in each ajax call (so as to later retreive only the new content from db ) but one session variable $_SESSION['s'] is getting unset in every alt. ajax call ! however the unmodified session variable $_SESSION["iuser"] is working fine . I am testing this on localhost / wamp and coding in npp .
<?php
session_start();
//if(isset($_SESSION["s"]))
$in=$_SESSION["s"];
//echo $_SESSION['sid'];
$link=mysql_connect("localhost","root","");
mysql_select_db("secure_scrapbook") or die("Sorry :( Connection Error");
$query="Select data,user,id from public where public=1 && id>'$in' ORDER BY id DESC";
$result=mysql_query($query);
$i=mysql_fetch_array($result);
$_SESSION["s"]=$i["id"];
//echo $_SESSION['sid'];
if(!($_SESSION["s"]==$in))
{echo 0;
echo $in;
echo $_SESSION["iuser"];
echo $_SESSION["s"];
echo "check<br>";
}
?>
--jquery /ajax -----
<script>
setInterval(function() {
$.ajax({
url: "gets.php",
type : "get" ,
dataType : 'html',
success : function(data){
//$("#public").html(data);}
$("#public").html(data+$("#public").html()+'-');}
});}, 5000); //5 seconds
</script>
May I suggest you debug your calls like this:
<?php
session_start();
if (empty($_SESSION["s"])){
echo 'EMPTY SESSION ';
die;
}
$in = $_SESSION["s"];
$link=mysql_connect("localhost","root","");
mysql_select_db("secure_scrapbook") or die("Sorry :( Connection Error");
$query="Select data,user,id from public where public=1 && id>'$in' ORDER BY id DESC";
$result=mysql_query($query);
$i=mysql_fetch_array($result);
if (empty($i["id"])){
echo 'EMPTY $i';
die;
}
$_SESSION["s"]=$i["id"];
//echo $_SESSION['sid'];
if(!($_SESSION["s"]==$in))
{echo 0;
echo $in;
echo $_SESSION["iuser"];
echo $_SESSION["s"];
echo "check<br>";
}
?>
Each time you get the message EMPTY SESSION or EMPTY $i check:
the ajax headers and try to step-by-step track your problem.
the element in the database does have an ID
the $in is within the boundries of possible ID's
the $in is a number
<?php
session_start();
//if(isset($_SESSION["s"]))
$in=$_SESSION["s"];
//echo $_SESSION['sid'];
$link=mysql_connect("localhost","root","");
mysql_select_db("secure_scrapbook") or die("Sorry :( Connection Error");
$query="Select data,user,id from public where public=1 && id>'$in' ORDER BY id DESC";
$result=mysql_query($query);
if($i=mysql_fetch_array($result))
{
$_SESSION["s"]=$i["id"];
//echo $_SESSION['sid'];
if(!($_SESSION["s"]==$in))
{
echo 0;
echo $in;
echo $_SESSION["iuser"];
echo $_SESSION["s"];
echo "check<br>";
}
}
else
echo "No more Data in table";
?>
Try this and if "No more Data in table" is echoed, it means that your db doesn't have any data satisfying the conditions you set.
One more thing, seeing your code it looks like $_SESSION["s"] will never be equal to $in so i guess you don't need to use the if condition.
let say that, i want to my change password in php code then it will validate by the use of javascript. before it return to my index page or it will popup on index page. how can i do it? any trick that you can suggest? :)
<?php
include('config2.php');
error_reporting(E_ERROR | E_PARSE);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$val = $_GET['val1'];
session_start();
$ak = $_SESSION['autokey'];
$sql = "UPDATE tbl_user SET password = '". md5($val) ."' WHERE autokey = '$ak'";
mysql_query($sql);
header("location:index");
?>
thanks in advance :)
You could change your code block like this..
$sql = "UPDATE tbl_user SET password = '". md5($val) ."' WHERE autokey = '$ak'";
mysql_query($sql);
if(mysql_affected_rows())
{
echo "<script>alert('Password was successfully changed !');</script>";
echo "<script>window.location='index.php'</script>";
} else
{
echo "<script>alert('Password was not changed');</script>";
echo "<script>window.location='index.php'</script>";
}
As the comment says.. You are mixing up mysql_* and mysqli_*. Change that first.
Sidenote: Switching to PreparedStatements is even more better to ward off SQL Injection attacks !