I am trying to create a progress bar for multiple file i upload to a server!!! I am able to upload the files but when i try to fetch the upload progress information the session array is empty. Please do help!!! Please find below the information:
Firstly my main php page where i upload the files:
********************************************Main.php********************************
<?php session_start();?>//top of the page
<div id = "centerMain" align="center">
<iframe name="targetIframe" src="" style="width:50%;height:30%;position:relative;"></iframe>
<div id="addNewBlock" class="emboss blockPart" style="z-index:50000;padding:2%;position:relative;width:50%;left:25%;top:35%;border:1px solid black;">
<form method="POST" action="handleItemAddition.php" target="targetIframe" enctype = "multipart/form-data" onSubmit="return checkAndStartUpload()">
<!--VERY IMPORTANT:the hidden element should come first before any element within the form--> <input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" id="hidUpProg" value="upFilesInfo" />
<script type ="text/javascript">
var upProgName = "<?php echo ini_get("session.upload_progress.name"); ?>";
//alert(document.getElementById("hidUpProg").value);
</script>
<div class="stayLeft">Upload Photo:</div><input style="width:40%;" type="file" name = "itemImage[]" id="fileUp" class = "stayRight" multiple/><br/><br/>
<input type="button" id = "closeBut" style="width:20%;" value = "close" onclick="closeBlock()" class="utsaaBut stayLeft"/>
<input type="submit" id = "AddBut" style="width:20%;" value = "Done" class="utsaaBut stayRight"/>
</form>
</div>
</div>
********************************************Main.php********************************
find below the javscript function which gets called onSubmit = "checkAndStartUpload()" from above
******************************************Javascript function****************************
function checkAndStartUpload()
{
var tmp = document.getElementById("fileUp");
if(tmp.files.length == 0)
{
alert("No file selected. Kindly select a file");
return false
}
$progressPtr = setInterval(handleProgress,50);
return true;
}
var it = 0;
function handleProgress()
{
//alert("handleProgress");
var xmlhttp;
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
//alert("response");
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
//alert("value:"+xmlhttp.responseText["content_length"]);
var res = xmlhttp.responseText;
alert("Response:"+res);
it++;
if(it == 25)
{
it = 0;
clearInterval($progressPtr);
}
}
}
xmlhttp.open("POST","handleProgressValue.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(upProgName+"=upFilesInfo");
}
******************************************Javascript function*******************
Next is the file which returns session value through ajax
******************************************ajax progress return*******************
<?php
$key = ini_get("session.upload_progress.prefix") .$_POST[ini_get("session.upload_progress.name")];
if (!empty($_SESSION[$key])) {
$current = $_SESSION[$key]["bytes_processed"];
$total = $_SESSION[$key]["content_length"];
echo "Current".$current."$total".$total;
//echo $current < $total ? ceil($current / $total * 100) : 100;
}
else {
echo "100"; //IT ALWAYS RETURNS 100 MEANING$_SESSION[$key] IS ALWAYS EMPTY
}
/*session_start();
$key = ini_get("session.upload_progress.prefix").$_POST[ini_get("session.upload_progress.name")];
//var_dump($_SESSION[$key]);
$tmp = $_SESSION[$key];
echo $tmp["bytes_processed"];*/
?>
******************************************ajax progress return*******************
And finally handleItemAddition.php successfully uploads the images.
I also disabled ;session.upload_progress.cleanup = On just for testing purpose so that if upload gets completed fast it should not clear the values.
Still i am getting empty array .
Hey guys sorry i forgot to update. I fixed the issue sometime back.
I had put session_start(); on top of all files but in handleProgressValue.php i had commented it while changing the code once i uncommented it worked.
However when i am uploading 28 files say, why does
count($_SESSION[$key]["files"])
return increasing values??? It first returned 10 then 17,24,28 and then $_SESSION got unset
Related
I am doing my website on Wordpress.
I have 2 search forms that appear separate on my website and I was wondering how could I merge them into one.
The first search form searches for products First search form
The second one searches for the location of the products Second search form
Sorry for asking this silly question and thank you for your help :D
Javascript is what you need to start learning. It is the essential other half of webpage design. With Javascript you can get the value from anything on the page. Here's the basic code for pulling the values from the inputs of two different forms and posting them to your PHP file.
<!--first form-->
<form>
<input type="text" id="product" name="product">
</form>
<!--second form-->
<form>
<input type="text" id="city" name="city">
</form>
<button onclick="continuePost()">Submit Both</button>
<div id="result"></div>
<script>
function continuePost() {
var product = encodeURIComponent(document.getElementById("product").value);
var city = encodeURIComponent(document.getElementById("city").value);
var params = "product="+product+"&city="+city;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myResponse = JSON.parse(this.responseText); //send a JSON response back from your PHP file
if(myResponse.hasOwnProperty('error')){
document.getElementById("result").innerHTML = myResponse.error;
}else{
var result1 = myResponse.myResult1;
var result2 = myResponse.myResult2[0]; //or whatever key and value pairs that you used in the JSON response that you sent back from you PHP file
document.getElementById("result").innerHTML = result1;
}
}else{
window.setTimeout(failed(), 3000);
}
};
xhttp.open("POST", "yourPHPfile.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(params);
}
function failed(){
document.getElementById("result").innerHTML = 'Failed to connect to server.';
}
</script>
yourPHPfile.php
<?php
$obj = new stdClass();
$obj->dateread = date("D M j G:i:s T Y");
if(!isset($_POST["product"])){
$obj->error = 'No product.';
echo json_encode($obj);
exit;
}else {
$product=$_POST["product"];
}
if(!isset($_POST["city"])){
$obj->error = 'No city.';
echo json_encode($obj);
exit;
}else {
$city=$_POST["city"];
}
$obj->myResult1 = 'Info you want back from your PHP file.';
$obj->myResult2 = ['array', 'of', 'info', 'you', 'want'];
echo json_encode($obj);
?>
I want to make a form in which an user enters a name to create a new record and want check simultaneously, if the record exists or not, so the user can't insert 2 records with same name (but this is not primary key ) .
i am using following code right now but this reload page every time i need to check for value entered
<html>
<?php
require_once('../php/classes/class.add_album.php');
$file_name='';
$file_not_found="NULL";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$file_name = test_input($_POST["file_name"]);
echo $file_name; //for testing
//make new object
$objfile = new add_album();
//call object methid with post method value we got and save result in result
$file_not_found=$objfile->find_album($file_name);
echo $file_not_found; //for testing
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if($file_not_found){
echo '<form>';
echo '<label>File Name </label>';
echo '<input type="text" value='.$file_not_found.' >';
} else {
echo '<form method="POST" action="temp.php">';
echo '<label>File Name</label>';
echo "<input type=text name='file_name' placeholder='New file name plz' >";
echo"<input type=submit name=submit value=submit>";
}
?>
</form>
`
Follow javascript ajax and same php file as above that i had mentioned.
Refere this link for ajax http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
function validateUser()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200){
//alert(xmlhttp.responseText);
// do somting here..
document.getElementById("captcha_validation").value=xmlhttp.responseText;
}
}
xmlhttp.open("POST","yourfile.php",true);
xmlhttp.send("username=abc&password=xyz");
}
user ajax to send form data to class .
Below is ajax function
$.ajax({
url :"yourfile.php",
type :"POST",
data :$("#formid").serialize(),
success : function(response)
{
// do someting here.
}
Your PHP File (yourfile.php)
$obj = new db();
$yourdata = $_POST;
$res = $obj->validateUser($yourdata) ;
am trying to generate report through dynamically generated form. Through XMLHttpRequest the form loads well but the validation against the form fields wont work. I have tried eval() it works only during load time ( like eval(alert("hi")) but not on dom objects , think some scope problem. The form fields are dynamically generated and so its validation based on selection and availability role in database.
The code of two files is attached below
<script>
function showUser(str)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var s= xmlhttp.responseText;
parseScript1(s);
parseScript(s);
}
}
xmlhttp.open("GET","test2.php",true);
xmlhttp.send();
}
function parseScript1(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
var k = "<script> "+ scripts +"<\/script>";
document.getElementById("txtHint1").innerHTML=k ;
// Return the cleaned source
return source;
}
function parseScript(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
document.getElementById("txtHint").innerHTML=source;
// Return the cleaned source
return source;
}
function valid()
{
eval(validate());
}
</script>
<div id="txtHint1"><b>javascript will appear here</b></div>
<form>
<div id="nons1" >
<select id="nope1" name="users" onchange="showUser(this)">
<option value="">Select a option:</option>
<option value="1">not working here</option>
</select>
</div>
</form>
<div id="txtHint"><b>Select the value .</b></div>
test2.php
echo "<p>This form works fine singly not with xmlhttprequest";
echo'<form name="frm" method="post" action="test2.php" onsubmit="return(eval(validate()));">';
echo '<input value="" name="kfrm19" type="text">';
echo '<input name="save" value="submit" type="submit"></form>';
echo '<script>
function validate(){
if( document.frm.kfrm19.value.trim()=="")
{
alert( "If you can see this message .its working..." );
document.frm.kfrm19.focus() ;
return false;
}
}
</script>';
?>
try this:
function validate(){
if(document.frm.kfrm19.value.length == 0)
{
alert("If you can see this message .its working...");
document.frm.kfrm19.focus();
return false;
}
}
i have the following html:
<body onload="showcontent()"> <!-- onload optional -->
<div id="content"><img src="loading.gif"></div> <!-- leave img out if not onload -->
</body>
I also have the following script:
function showcontent(){
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 1) {
document.getElementById('content').innerHTML = "<img src='loading.gif' />";
}
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('content').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'elsevier.php', true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(null);
}
In elsevier.php I want when the rows of a table exceed 500 two buttons to be displayed, telling me whether to continue or cancel. If I put this code in the .php file nothing happens..... (except that two buttons appear).
if(mysqli_errno($con)==1062){
#$q55="SELECT COUNT(*) FROM testarticles";
$result55 = mysqli_query($con, $q55);
$row = $result55->fetch_row();
echo '#: ', $row[0].'<br>';
if($row[0]>=500&&$answer==false){
echo '<form action="" method="GET">';
echo "<label>Do you want to continue or cancel?</label>";
echo '<input type="button" id="but1" name="but1" value="Continue">';
echo '<input type="button" id="but2" name="but2" value="Cancel">';
echo '</form>';
//sleep(2);
if(isset($_GET["but1"])){
$answer=true;
break;
}
elseif(isset($_GET["but2"])){
#$q56="DELETE * FROM journal, volume, issue, articles, testarticles WHERE import_time=$unixtimestamp";
$result56 = mysqli_query($con, $q56);
exit;
}
}
I want in this step the execution of the php script to stop and to display me the two buttons to choose from. If i press continue i want the script to execute from where it was stopped.
Has anybody any idea?? Thank you in advance!
session_start();
if(mysqli_errno($con)==1062){
$where = isset($_SESSION['last_id']) ? " WHERE id > '" . $_SESSION['last_id'] . "'" : "";
if(isset($_SESSION['last_id']))
unset($_SESSION['last_id']);
#$q55="SELECT COUNT(*) FROM testarticles$where ORDER BY id";
$result55 = mysqli_query($con, $q55);
$row = $result55->fetch_row();
echo '#: ', $row[0].'<br>';
if($row[0] >= 500 && $answer == false){
$_SESSION['last_id'] = $row['id'];
echo "<label>Do you want to continue or cancel?</label>";
echo '<input type="button" id="but1" name="but1" value="Continue" onclick="showcontent(true)" />';
echo '<input type="button" id="but2" name="but2" value="Cancel">';
//sleep(2);
if(isset($_GET["but1"])){
$answer=true;
break;
}
elseif(isset($_GET["but2"])){
#$q56="DELETE * FROM journal, volume, issue, articles, testarticles WHERE import_time=$unixtimestamp";
$result56 = mysqli_query($con, $q56);
exit;
}
}
You have to modify also the showcontent function because when you press the continue button the content retrieved should be appended and not replaced
function showcontent(){
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 1 && !update) {
document.getElementById('content').innerHTML = "<img src='loading.gif' />";
}
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if(update)
alert("this is an update and I should append data, not to replace the div content");
else {
document.getElementById('content').innerHTML = xmlhttp.responseText;
//this is the first call of the function so the content of the div will be replaced
}
}
}
xmlhttp.open('GET', 'elsevier.php', true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(null);
}
HTML Code:
<body onload="showcontent(false)"> <!-- onload optional -->
<div id="content"><img src="loading.gif"></div> <!-- leave img out if not onload -->
</body>
Note that this is not a verified code so you should modify it
use 'echo' followed by the <html code> for creating a button. You will be done.
I have a situation in which i need to do insert queries for every check box selected through an ajax request sent to a php script which would do the insert in mysql.
i know how to do it without an ajax call via the simple form submission with a variable like groups[] as an array and running the foreach loop in php for every value in the array.
How do i send the array a via post ajax request?
a sample code:
<input type='checkbox' name='groups[]' value='1'>Group A
<input type='checkbox' name='groups[]' value='2'>Group B
<input type='checkbox' name='groups[]' value='3'>Group C
Please help, i know this might be easy but i am just not getting it. and guys, please don't give any example of jquery or the likes as i want pure html, javascript and php solution.
Thanks community...
Here's the Javascript function:
<script type='text/javascript'>
function addResp(tid){
a = encodeURIComponent(document.getElementById('course_add_resp').value);
b = encodeURIComponent(document.getElementById('term_add_resp').value);
c = encodeURIComponent(document.getElementById('paper_add_resp').value);
var elements = document.getElementsByName('groups[]');
var data = [];
for (var i = 0; i < elements.length; i++){
if (elements[i].checked){
data.push('groups[]='+elements[i].value);
}
}
params = "tid="+tid+"&course="+a+"&sem="+b+"&paper="+c+"&grp="+data;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.body.removeChild(document.getElementById('respBackground'));
document.body.removeChild(document.getElementById('respBox'));
contents = xmlhttp.responseText;
if(contents == "done"){
window.location = "teachers.php";
} else{
document.getElementById("studentBox").innerHTML = "There was a problem serving the request.";
}
}
}
xmlhttp.open("POST","assignresp.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params);
}
</script>
and the php script:
<?php
$tid = mysql_real_escape_string($_POST['tid']);
$cid = mysql_real_escape_string($_POST['course']);
$sem = mysql_real_escape_string($_POST['sem']);
$paper = mysql_real_escape_string($_POST['paper']);
$session = 12;
$type = 1;
$groups = $_POST['grp'];
foreach ($groups as $value ) {
$q1 = "insert into iars(sessionid,teacherid,courseid,semester,paperid,groupid,type) values('$session','$tid','$cid','$sem','$paper','$value','$type')";
$r1 = mysql_query($q1) or die(mysql_error());
if(mysql_affected_rows() > 0){
echo "done";
}
else{
echo "fail";
}
}
?>
var elements = document.getElementsByName('groups[]');
var data = [];
for (var i = 0; i < elements.length; i++){
if (elements[i].checked){
data.push('groups[]='+elements[i].value);
}
}
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data.join('&'));
//for get
//xmlhttp.open("GET",url+"?"+data.join('&'),true);
//xmlhttp.send();
EDIT
Change these two lines.
params = "tid="+tid+"&course="+a+"&sem="+b+"&paper="+c+"&"+data.join('&');
$groups = $_POST['groups'];
you can do this with two way,
you can use the post type ajax call
You can get the all selected checkbox values with JavaScript make comma separated string and just pass it in one variable
that's all you can do .... :)