PHP script status bar - javascript

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.

Related

How to show alert box after successful or not data deletion in mssql

I want to show JavaScript alert after successful or not data deletion in MSSQL. How to do this? I have written this code but it shows only the message=success part alert everytime, even when the deletion dont work becasue of errors like "conflict with reference(foreign_key)" So when i click on this link.
echo "<a class='activater' href='ma_QualiOverviewloeschen.php?TestaufstellungID=".$row['TestaufstellungID'] ."&QualiID=".$row['QualiID'] ."' title='Qualitest löschen' data-toggle='tooltip' onclick='confirm_delete()'> <span class='glyphicon glyphicon-trash'></span></a>";
It calls the following php Page, which handle the SQL Part:
$QualiDelete =("DELETE FROM MyDB.dbo.Testaufstellung WHERE MyDB.dbo.Testaufstellung.TestaufstellungID = :TestaufstellungID");
$QualiDelete .=("DELETE FROM MyDB.dbo.AllgemeineAngaben WHERE MyDB.dbo.AllgemeineAngaben.QualiID = :QualiID");
$sth = $connection->prepare($QualiDelete);
$sth->execute(array(':TestaufstellungID' => $TestaufstellungID, ':QualiID:' => $QualiID));
if($sth)
{
header("location: ma_QualiOverview.php?message=success");
}
else
{
echo sqlsrv_errors();
header("location: ma_QualiOverview.php?message=failed");
}
$connection = null;
Back to the main page where the link is clicked the following ifelseconsider on messageshould Show me the right alert.
<?php
if($_GET['message']=='success'){
echo '<script language="javascript">';
echo 'alert("Erfolgreich gelöscht.");';
echo '</script>';
} elseif($_GET['message']=='failed'){
echo '<script language="javascript">';
echo 'alert("Nicht gelöscht, da Quali "ongoing" ist.");';
echo '</script>';
}
?>
What do i miss?
$sth will never be falsy, you have to check the return value of $sth->execute
Also, you should echo the errors after sending out the header.
Since $sth is always defined, you always get the success result
See the modified code here
$QualiDelete =("DELETE FROM MyDB.dbo.Testaufstellung WHERE MyDB.dbo.Testaufstellung.TestaufstellungID = :TestaufstellungID");
$QualiDelete .=("DELETE FROM MyDB.dbo.AllgemeineAngaben WHERE MyDB.dbo.AllgemeineAngaben.QualiID = :QualiID");
$sth = $connection->prepare($QualiDelete);//Check the value returned instead of $sth
$result = $sth->execute(array(':TestaufstellungID' => $TestaufstellungID, ':QualiID:' => $QualiID));
if($result )
{
header("location: ma_QualiOverview.php?message=success");
}
else
{
header("location: ma_QualiOverview.php?message=failed");
echo sqlsrv_errors();//Echo must be after header
}
$connection = null;

PHP echo selected value from html dropdown list

In my dropdown list, i put all the "pack_name(s)" the user has posted and I display it all in the list for the user to select and update. So when the user selects one and hits submit, i want to get that "value" submitted and use it for later purposes but ive been researching and only found "pre-set" values with html and the value was given using Jquery. So i wondering if its possible to basically take the "pack_name" selected and when the user hits submit, echo out the selected value.
PHP
<?php
session_start();
if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post'){ //catch file overload error...
$postMax = ini_get('post_max_size'); //grab the size limits...
echo "<p style=\"color: #F00;\">\nPlease note files larger than {$postMax} will result in this error!</p>"; // echo out error and solutions...
return $postMax;
}
if(isset($_COOKIE['id'])){
if($_SESSION['came_from_upload'] != true){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerLogin.php");
exit;
}
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicserver', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
$userid = $_SESSION['id'];
$stmt = $handler->prepare("SELECT * FROM pack_profile WHERE pack_developer_id = :userid");
$stmt->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmt->execute();
echo "<select>";
while($result = $stmt->fetch()){
echo "<option>" . $result['pack_name'] ."</option>";
}
echo "</select>";
if($_SERVER['REQUEST_METHOD'] =="POST"){
$token = $_SESSION['token'];
}
}
?>
You need to give the select element a name attribute, and give each option element a value attribute.
For example:
echo "<select name=\"pack\">";
while($result = $stmt->fetch()){
echo "<option value=\"" . $result['pack_name'] . "\">" . $result['pack_name'] ."</option>";
}
echo "</select>";
Of course you should be escaping anything which could contain &, < or " with something like htmlspecialchars().

Sending JSON Data to Ext.js

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 ;-)

SESSION value not passing after redirection to the thank you page

I am trying to pass $email field to thank you page which appears after redirection once user submits the enquiry form.
Its a 2 step enquiry form with thank you page being last.
It seems like the SESSION is live on thank you page however the values are lost. I'd like to get $email field posted on the thank you page to an iframe. Please let me know where exactly the session id is going wrong?
Here are the codes:
Step 1: Small Enquiry form
<?php
error_reporting(0);
session_start();
require_once('validation.class.php');
if(isset($_REQUEST['btnSubmit']) == 'Next'){
$obj = new validation();
$obj->add_fields(trim($_POST['txt_fname']), 'req', 'Enter your first name.');
$obj->add_fields(trim($_POST['txt_contact']), 'req', 'Enter phone number.');
$obj->add_fields(trim($_POST['txt_finamount']), 'req', 'Enter the amount.');
$obj->add_fields(trim($_POST['sel_loantype']), 'req', 'Please select vehicle type.');
$error = $obj->validate();
if($error){
$error_msg = "".$error."";
$_SESSION['error_msgs'] = $error_msg;
header("location:".$_SERVER['HTTP_REFERER']."");
exit();
}else{
$_SESSION['form1data'] = $_REQUEST;
header("location: quick-quote.php");
exit();
/*$fname = trim($_REQUEST["txt_fname"]);
$surname = trim($_REQUEST["txt_surname"]);
$phone = trim($_REQUEST["txt_contact"]);
$finamount = trim($_REQUEST['txt_finamount']);
$sel_loantype = trim($_REQUEST['sel_loantype']);
$message = '<html><body>';
$message .= '<table rules="all" width="100%" style="border:1px solid #666;" cellpadding="10">';
$message .= "<tr><td><strong>First Name:</strong> </td><td>" . strip_tags($fname) . "</td></tr>";
if($surname != ''){
$message .= "<tr><td><strong>Surname:</strong> </td><td>" . strip_tags($surname) . "</td></tr>";
}
$message .= "<tr><td><strong>Phone:</strong> </td><td>" . strip_tags($phone) . "</td></tr>";
$message .= "<tr><td><strong>Amount to Finance:</strong> </td><td>" . strip_tags($finamount) . "</td></tr>";
$message .= "<tr><td><strong>Loan Type:</strong> </td><td>" . strip_tags($sel_loantype) . "</td></tr>";
$message .= "</table>";
$message .= "</body></html>";
$ToEmail = 'testemail#gmail.com';
$EmailSubject = "GET A QUICK QUOTE from ".strip_tags($fname);
$mailheader = "From: ".strip_tags($fname)."\r\n";
//$mailheader .= "Reply-To: ".$_REQUEST["txt_email"]."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
$MESSAGE_BODY = $message;
if(#mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader)){
$_SESSION['sucess'] = "Your message has been sent successfully.";
$_SESSION['form1data'] = $_REQUEST;
header("location: quick-quote.php");
exit;
}else{
$_SESSION['sucess'] = "Sorry! Your message has not been sent.";
$_SESSION['form1data'] = $_REQUEST;
header("location: quick-quote.php");
exit;
}*/
}
}
?>
Step 2 Code:
<?php
error_reporting(0);
session_start();
require_once('validation.class.php');
?>
<script type="text/javascript">
function submitToCRM()
{
$.ajax({
type: 'POST',
url: 'http://test.com.au/quick-quote/car-finance/quickquote-one.php',
data: $("#applynowform").serialize(),
beforeSend: function () {
$("#loadingimg").show();
},
success: function (){
//alert(data);
window.location.href = "http://www.test.com.au/thank-you";
}
});
Step 3: The above page sends data to quickquote-one.php form processing script which has below code.
<?php
if(!isset($_SESSION))
{
session_start();
}
$_SESSION['user_email'] = $_POST['email'];
Step 4: thank you page (this page has below code)
<?php
if(!isset($_SESSION))
{
session_start();
$_SESSION['user_email'] = $_POST['email'];
echo $_SESSION['user_email'];
}
?>
Add
session_set_cookie_params(0);
before your
session_start();
You can also pass the SID (session ID) between the pages using the URL to make sure it isn't lost in transition.
url: 'http://test.com.au/quick-quote/car-finance/quickquote-one.php?<?php echo htmlspecialchars(SID); ?>',
and
window.location.href = "http://www.test.com.au/thank-you?<?php echo htmlspecialchars(SID); ?>";
You're losing the session because you're sending the browser to the next URL without a relative path but instead a fully-qualified domain. This is a security measure to prevent session IDs from being inadvertently sent to the wrong server.
Another small solution would be to use relative paths like /page.php instead of http://www.domain.com/page.php
Read more here (PHP Manual)
In step 4 your setting
$_SESSION['user_email']
again. If the form has refreshed then your post is empty and you are overwriting the session with an empty value. Try removing it from step 4 and just leave.
<?php
if(isset($_SESSION['user_email']) && !empty($_SESSION['user_email']))
{
echo $_SESSION['user_email'];
}
?>
Also you are trying to echo your session email value IF the session is NOT set. I don't think that will work if the session is actually set..
i think it is better to start a session in one page and access all the session variables throghout if all the pages are connected to eachother. it will be some thing like we create login page. When user logs in capture alll the required values in a session and can be accessed through out the application even after refresh.
$query = "SELECT Useid,UserName,AccountStatus, FullName FROM Users WHERE UserName = :UserName";
from this query we can get the session variables easily.
if($login_ok)
{
//for last visit
$Month = 2592000 + time();
//this adds 30 days to the current time
setcookie(AboutVisit, date("F jS - g:i a"), $Month);
//last visit ends here.
$_SESSION['user'] = $row['UserName'];
$_SESSION['userid'] = $row['Useid'];
$_SESSION['fullname'] = $row['FullName'];
}
where ever you need th variable you can use like this
$username=$_SESION['user'];
I think this will work instead of startign session every time in each page.
Hope it helps

Javascript and PHP scan for nudity

I am trying to not allow the uploading of files that have nudity to my server. I found javascript online that will scan a photo for nudity. It comes with demo pics and an html file and js files. I am using PHP to upload the file and I am having trouble not allowing if the scan find that the pic has nudity.
Here is my code sample:
$q= "insert into $table values('', '$email', '$aim', '$icq', '$yahoo', '$homepage', '0', '0', '0', '0', '0', '0', '', now(),'$myip','$email2','$password','$title','$download','$approved','$allowdelete','$author','$facebook','$piclink','$domain','$option3','$secret')";
$result = mysql_query($q) or die("Failed: $sql - ".mysql_error());
$q = "select max(id) from $table";
$result = mysql_query($q);
$resrow = mysql_fetch_row($result);
$id = $resrow[0];
$file = $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], "pics/".$id.".".$picext);
$picfile=$id.".".$picext;
echo '<script type="text/javascript" <src="nude.js">';
echo 'nude.load("pics/".<? echo $picfile; ?>);nude.scan(function(result){if(!result){ <? $nude = false; ?>;}else{ $nude = true;}})';
echo '</script>';
if ($nude === false) {
$q = "update $table set picfile = '".$id.".".$picext."' where id='$id'";
$result = mysql_query($q);
Header("Location: index.php?id=$id");
} else{
echo '<script type="text/javascript">';
echo 'alert("Nudity found. Please try again.")';
echo '</script>';
$q = "delete from $table where id='$id'";
$result = mysql_query($q);
unlink("pics/".$picfile);
Header("Location: new2.php");
}
The code uploads the file and then it's supposed to check the file for nudity and delete it and tell the user to try again if nudity is found. If nudity is not found the user is brought to the main page of the site.(This is the add new photo page). All of the PHP is working fine, but since the javascript doesn't seem to be running the file i uploaded and then since $nude isn't set it goes into the else of the if statement and again the js doesnt run(no alert box), and then the file is deleted. How can I make the javascript run to scan my uploaded pic for nudity? What am I doing wrong here?
Any help is greatly appreciated!
P.S.
For those that would like to see the js file that is doing the scanning: http://pastebin.com/MpG7HntQ
The problem is that this line:
echo 'nude.load("pics/".<? echo $picfile; ?>);nude.scan(function(result){if(!result){ <? $nude = false; ?>;}else{ $nude = true;}})';
Doesn't do what you think it does.
When you output JavaScript via echo(), that code runs on the browser or client side and doesn't run until after the PHP script has finished.
You'll either need to port the code to PHP or use an AJAX call to report the validity of the images.

Categories

Resources