Refresh PHP SESSION var after AJAX request - php

I've index.php and callSession04.php. When index.php does an AJAX request PHP SESSION variables are set on callSession04.php to store the current page and rows per page but on index.php PHP SESSION variables stay as initial state until I refresh index.php
You can see the example here, Need to refresh page before each AJAX request:
http://www.sanchezvalero.com/DWS/pracSESIONES/ej4/sesion04.php
And here is the code:
index.php
<? session_start(); ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Listado de empleados</title>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="content" align="center"></div>
<p>
<div align="center">
<label for="fldRows">Resultados por página:</label>
<input name="fldRows" type="text" id="fldRows" size="2" />
</div>
</p>
<p>
<div id="manage" align="center">
<input name="btnFirst" type="button" id="btn1" value="|<" />
<input name="btnBefore" type="button" id="btn2" value="<" />
<input name="btnAfter" type="button" id="btn3" value=">" />
<input name="btnLast" type="button" id="btn4" value=">|" />
<p>Reset</p>
</div>
</p>
<script type="text/javascript">
$(document).ready(function() {
<? if(!isset($_SESSION['rows'])){ ?>
$("#fldRows").val("10");
<? } else { ?>
$("#fldRows").val("<? echo $_SESSION['rows']; ?>");
<? } if(!isset($_SESSION['actp'])){ ?>
$actp=0;
<? } else { ?>
$actp=<? echo $_SESSION['actp']; ?>;
<? } ?>
$.ajax({type: "GET",
url: "callSesion04.php",
data: "rows="+$("#fldRows").val()+"&actp="+$actp,
success: function(data) {
$("#content").html(data);
}
});
});
$("#fldRows").keyup(function() {
if($(this).val()>=0){
$.ajax({type: "GET",
url: "callSesion04.php",
data: "rows="+$(this).val()+"&actp=0",
success: function(data) {
$("#content").html(data);
}
});
}
});
$("body").on("click","#manage input",function(){
$id=$(this).attr('id').substr($(this).attr('id').search(/\d/));
$.ajax({type:"GET",
url:"callSesion04.php",
data:"pag="+$id+"&actp=<? echo $_SESSION['actp']; ?>&rows=<? echo $_SESSION['rows']; ?>",
success: function(data) {
$("#content").html(data);
}
});
});
</script>
</body>
</html>
callSession04.php
<? session_start();
$dom = new DOMDocument();
$dom->load('empleados.xml');
$empleados=$dom->getElementsByTagName('RECORD');
foreach($empleados as $empleado){
$ids=$empleado->getElementsByTagName('ID_EMPLEADO');
$id=$ids->item(0)->nodeValue;
$array_ids[]=$id;
$nombres=$empleado->getElementsByTagName('NOMBRE');
$nombre=$nombres->item(0)->nodeValue;
$array_nombres[]=$nombre;
$apellidos=$empleado->getElementsByTagName('APELLIDOS');
$apellido=$apellidos->item(0)->nodeValue;
$array_apellidos[]=$apellido;
$fechas=$empleado->getElementsByTagName('FECHA_NACIMIENTO');
$fecha=$fechas->item(0)->nodeValue;
$array_fechas[]=$fecha;
$tipos=$empleado->getElementsByTagName('TIPO_EMPLEADO');
$tipo=$tipos->item(0)->nodeValue;
$array_tipos[]=$tipo;
$hijos=$empleado->getElementsByTagName('NUM_HIJOS');
$hijo=$hijos->item(0)->nodeValue;
$array_hijos[]=$hijo;
}
$rows=$_GET['rows'];
$actp=$_GET['actp'];
$pag=$_GET['pag'];
$_SESSION['rows']=$rows;
if($rows>0){
$tpag=intval(count($array_ids)/$rows);
}
if($pag=='1'){
$actp=0;
}else if($pag=='2' && $actp>0){
$actp--;
}else if($pag=='3' && $actp<$tpag){
$actp++;
}else if($pag=='4'){
$actp=$tpag;
}
$_SESSION['actp']=$actp;
$minrow=$rows*$actp;
$maxrow=$rows*$actp+$rows;
if($maxrow>count($array_ids)){
$maxrow=count($array_ids);
}
echo "<p align='center'><strong>EMPLEADOS</strong></p>";
echo "<table border='1' cellspacing='0' cellpadding='5'>";
echo "<tr><td>ID</td><td>Nombre</td><td>Apellidos</td><td>Nacimiento</td><td>Tipo</td><td>Hijos</td></tr>";
for($i=$minrow;$i<$maxrow;$i++){
echo "<tr><td>".$array_ids[$i]."</td><td>".$array_nombres[$i]."</td><td>".$array_apellidos[$i]."</td>
<td>".$array_fechas[$i]."</td><td>".$array_tipos[$i]."</td><td>".$array_hijos[$i]."</td></tr>";
}
echo "</table>";
?>
I need to know how refresh PHP SESSION VARS on index.php withouth press F5.

Finally I solved this, the solution, JSON. Is not necessary to refresh PHP SESSION vars on index.php, only on callSession04.php, simply I've to use AJAX callback to reflect the current server state parsing JSON array on index.php from callSession04.php then you can set new current page and rows per page vars.
index.php
<? session_start(); ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Listado de empleados</title>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="content" align="center"></div>
<p>
<div align="center">
<label for="fldRows">Resultados por página:</label>
<input name="fldRows" type="text" id="fldRows" size="2" />
</div>
</p>
<p>
<div id="manage" align="center">
<input name="btnFirst" type="button" id="btn1" value="|<" />
<input name="btnBefore" type="button" id="btn2" value="<" />
<input name="btnAfter" type="button" id="btn3" value=">" />
<input name="btnLast" type="button" id="btn4" value=">|" />
<p>Reset</p>
</div>
</p>
<script type="text/javascript">
$(document).ready(function() {
<? if(!isset($_SESSION['rows'])){ ?>
$("#fldRows").val("10");
$rows=10;
<? } else { ?>
$("#fldRows").val("<? echo $_SESSION['rows']; ?>");
$rows=<? echo $_SESSION['rows']; ?>;
<? } if(!isset($_SESSION['actp'])){ ?>
$actp=0;
<? } else { ?>
$actp=<? echo $_SESSION['actp']; ?>;
<? } ?>
$.ajax({type: "GET",
url: "callSesion04.php",
data: "rows="+$("#fldRows").val()+"&actp="+$actp,
success: function(data) {
var json = $.parseJSON(data);
$("#content").html(json.html);
}
});
});
$("#fldRows").keyup(function() {
if($(this).val()>=0){
$.ajax({type: "GET",
url: "callSesion04.php",
data: "rows="+$(this).val()+"&actp=0",
success: function(data) {
var json = $.parseJSON(data);
$rows=json.rows;
$("#content").html(json.html);
}
});
}
});
$("body").on("click","#manage input",function(){
$id=$(this).attr('id').substr($(this).attr('id').search(/\d/));
$.ajax({type:"GET",
url:"callSesion04.php",
data:"pag="+$id+"&actp="+$actp+"&rows="+$rows,
success: function(data) {
var json = $.parseJSON(data);
$actp=json.actp;
$("#content").html(json.html);
}
});
});
</script>
</body>
</html>
callSession04.php
<? session_start();
$dom = new DOMDocument();
$dom->load('empleados.xml');
$empleados=$dom->getElementsByTagName('RECORD');
foreach($empleados as $empleado){
$ids=$empleado->getElementsByTagName('ID_EMPLEADO');
$id=$ids->item(0)->nodeValue;
$array_ids[]=$id;
$nombres=$empleado->getElementsByTagName('NOMBRE');
$nombre=$nombres->item(0)->nodeValue;
$array_nombres[]=$nombre;
$apellidos=$empleado->getElementsByTagName('APELLIDOS');
$apellido=$apellidos->item(0)->nodeValue;
$array_apellidos[]=$apellido;
$fechas=$empleado->getElementsByTagName('FECHA_NACIMIENTO');
$fecha=$fechas->item(0)->nodeValue;
$array_fechas[]=$fecha;
$tipos=$empleado->getElementsByTagName('TIPO_EMPLEADO');
$tipo=$tipos->item(0)->nodeValue;
$array_tipos[]=$tipo;
$hijos=$empleado->getElementsByTagName('NUM_HIJOS');
$hijo=$hijos->item(0)->nodeValue;
$array_hijos[]=$hijo;
}
$rows=$_GET['rows'];
$actp=$_GET['actp'];
$pag=$_GET['pag'];
if($rows>0){
$tpag=intval(count($array_ids)/$rows);
}
if($pag=='1'){
$actp=0;
}else if($pag=='2' && $actp>0){
$actp--;
}else if($pag=='3' && $actp<$tpag){
$actp++;
}else if($pag=='4'){
$actp=$tpag;
}
$_SESSION['rows']=$rows;
$_SESSION['actp']=$actp;
$minrow=$rows*$actp;
$maxrow=$rows*$actp+$rows;
if($maxrow>count($array_ids)){
$maxrow=count($array_ids);
}
$html = "<p align='center'><strong>EMPLEADOS</strong></p>";
$html .= "<table border='1' cellspacing='0' cellpadding='5'>";
$html .= "<tr><td>ID</td><td>Nombre</td><td>Apellidos</td><td>Nacimiento</td><td>Tipo</td><td>Hijos</td></tr>";
for($i=$minrow;$i<$maxrow;$i++){
$html .= "<tr><td>".$array_ids[$i]."</td><td>".$array_nombres[$i]."</td><td>".$array_apellidos[$i]."</td>";
$html .= "<td>".$array_fechas[$i]."</td><td>".$array_tipos[$i]."</td><td>".$array_hijos[$i]."</td></tr>";
}
$html .= "</table>";
$aPag = array("rows"=>$rows,"actp"=>$actp,"html"=>$html);
echo json_encode($aPag);
?>

The session state is on the server, your code updates it on the server correctly (I assume). What you experience is the representation of the server state (index.php) is not updated on the client (browser) after the Ajax call.
You have multiple options to fix that:
Use the ajax callback to reload the current page (index.php)
Use the ajax callback to update the current page (DOM manipulation) to reflect the server state
This can not be fixed in the php (server side) alone.

Related

chatting system between users

I have been trying to create a chatting system using php+ ajax + mysql.
<?php
session_start();
?>
<html>
<head>
<title>Live Table Data Edit</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">You Are : <?php echo $_SESSION['name'];
?></h3><br />
<div id="live_data"></div>
</div>
<div id="messages"></div>
<div class="area" style="display:none">
<textarea id="text" name="text"></textarea>
<input type="submit" id="sub" name="sub" value="Send" />
</div>
</div>
</body>
</html>
<script>
$(document).ready(function() {
function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
$('#live_data').html(data);
}
});
}
fetch_data();
$(document).on('click', '.first_name', function() {
var id = $(this).data("id1");
function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
id: id
},
dataType: "text",
success: function(data) {
$('#messages').html(data);
$("div.area").show();
}
});
}
fetch_chat();
$("#sub").click(function() {
var text = $("#text").val();
$.post('insert_chat.php', {
id: id,
msg: text
}, function(data) {
$("#messages").append(data);
$("#text").val('');
});
alert(text);
});
});
});
but the trouble is that when I try to insert a new message in mysql the messages is send to all the users in which i have clicked.
the fetch_chat.php
<html>
<head>
</head>
<body>
<?php
session_start();
$con=mysqli_connect('localhost','root','','test');
$id= $_POST['id'];
$sql="select * from users where id='$id'";
$res=mysqli_query($con,$sql);
$row=mysqli_fetch_array($res);
$user_to= $row['name'];
$sql1="select * from chats where user_from='$_SESSION[name]' AND
user_to='$user_to' OR user_to='$_SESSION[name]' AND user_from='$user_to'
order by id";
$res1=mysqli_query($con,$sql1);
if(mysqli_num_rows($res1)>0){
while($row=mysqli_fetch_array($res1)){
?>
<b> <?php echo $row['user_from']; ?>:</b>
<?php echo $row['msg']; ?><br /><br />
<?php
}
}
else
echo "No msgs <br />";
?>
</body>
</html>
and insert_chat.php is:
<html>
<head>
</head>
<body>
<?php
session_start();
$con=mysqli_connect('localhost','root','','test');
$id= $_POST['id'];
$msg=$_POST['msg'];
$sql="select * from users where id='$id'";
$res=mysqli_query($con,$sql);
$row=mysqli_fetch_array($res);
$user_to= $row['name'];
$sql1="insert into chats(user_from,user_to,msg)
values('$_SESSION[name]','$user_to','$msg')";
$res1=mysqli_query($con,$sql1);
if($res1){
?>
<b> <?php echo $_SESSION['name']; ?>:</b>
<?php echo $msg; ?><br /><br />
<?php
}
?>
</body>
</html>
I don't know where I am going wrong. Please help me with this.
For example, the list of users is:
(1) user a
(2) user b
(3) user c
So at first I clicked a then I changed my mind to select b and send the text. But there arises the problem: the data gets inserted for both a and b like I am texting both of them at the same time.
You keep on adding more and more "click" event handlers to "sub", every time you click on "first_name". So then each time you click sub again, it runs all the previous event handlers again and again. So you get the current message, but sent to all users you previously clicked on since you loaded the page.
$("#sub").click(function() {
needs to be
$("#sub").off("click").on("click", function() {
so that it removes previous handlers before you define the new version with new data.

how to submit the form without refreshing the page

this is my html code when i click on submit button it displays alert and then when i open the retrieveform.php it does not show me the value please solve this mystery
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'retrieveform.php',
data: $('form').serialize(),
success: function () {
alert('helllo');
}
});
});
});
</script>
</head>
<body>
<form>
<input type="text"name="t1">
<input type="submit"name="s1"value="submit">
</form>
</body>
</html>
and my retrieveform.php is
<?php
if($_POST['t1'])
{
echo $_POST['t1'];
}
else
{
echo "hekllojjio";
}
?>
Is it possible that the element "t1" is present since it's part of your form, but empty or just empty characters .. perhaps check if this is the case?
<?php
if($_POST['t1'] && !empty($_POST['t1'])) {
echo "You submitted t1 of: ".$_POST['t1'];
} else {
echo "t1 is empty";
}
?>
Also of note is you may want to use something like firebug to view the ajax page loaded and its results. The echo statement on the ajax loaded page will not display on the parent page unless you set the contents of the response into the page:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$('.form').on('submit', function (e) {
tValue = $(this).find(input[type=text]:first).val();
e.preventDefault();
$.ajax({
type: 'post',
url: 'retrieveform.php',
data: $('form').serialize(),
success: function (response) {
alert('helllo');
$('#placeholder').html(response);
$('#placeholder2').html(tValue);
}
});
});
});
</script>
</head>
<body>
<?PHP for ($i = 1; $i <= 10; $i++) { ?>
<form class="form" name="form_<?PHP echo $i; ?>" id="form_<?PHP echo $i;?>">
<input type="text" id="t<?PHP echo $i; ?>" name="t<?PHP echo $i; ?>">
<input type="submit" name="s<?PHP echo $i; ?>" value="submit">
</form>
<?PHP } ?>
<div id="placeholder"></div>
<div id="placeholder2"></div>
</body>
</html>
with this your ajax loaded page's echo will be put on the page in the "placeholder" div.

chat app with user typing partly working

This code works very well for chatting. I have added ajaxcall.php for real time notification. The problem is; instead of displaying a typing notification when other users are typing, it will be displaying myself whenever am typing.please how do i make it to show other users typing.
index.php
<?php
ob_start();
?>
<?php
session_start();
?>
<!doctype>
<html>
<head>
<title>Chat</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<script type="text/javascript" src="jscolor.js"></script>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function() {
$.ajaxSetup(
{
cache: false,
beforeSend: function() {
$('#messages').hide();
$('#messages').show();
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
},
complete: function() {
$('#messages').hide();
$('#messages').show();
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
},
success: function() {
$('#messages').hide();
$('#messages').show();
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
}
});
var $container = $("#messages");
$container.load('ajaxload.php?id=<?php echo htmlentities( $_GET['id'], ENT_QUOTES, "UTF-8"); ?>');
var refreshId = setInterval(function()
{
$container.load('ajaxload.php?id=<?php echo htmlentities( $_GET['id'], ENT_QUOTES, "UTF-8"); ?>');
}, 3000);
$("#userArea").submit(function() {
$.post('ajaxPost.php', $('#userArea').serialize(), function(data) {
$("#messages").append(data);
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
document.getElementById("output").value = "";
});
return false;
});
});
</script>
<!--Ajax Server Call-->
<script>
function getAjaxFromServer(str){
if (str.length==0){
document.getElementById("ajaxResponse").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("ajaxResponse").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",'ajaxcall.php?id=<?php echo htmlentities( $_GET['id'], ENT_QUOTES, "UTF-8"); ?>',true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="chatwrapper">
<!--display-->
<!--http://www.youtube.com/watch?v=FyXeOX-uYMc-->
<div id="messages"></div>
<!--post-->
<form id="userArea">
<div id="usercolor">
<input name="reciever" type="hidden" value="<?php echo htmlentities($_GET['id'], ENT_QUOTES, "UTF-8");?>"><br>
<input name="text" class="color" id="text" maxlength="6" value="000000" />
</div>
<div id="messagesntry">
<textarea id="output" name="messages" placeholder="Message" onkeyup="getAjaxFromServer(this.value)"/></textarea>
</div>
<div id="messagesubmit">
<input type="submit" value="Post message" id="submitmessage" />
</div>
</form>
</div>
</body>
</html>
ajaxload.php
<?php
ob_start();
?>
<?php
session_start();
?>
<?php
include('connect.php');
$id=$_GET['id'];
$result = $db->prepare("SELECT * FROM messages ORDER BY id ASC");
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
echo '<div style="color:'.$row['textcolor'].'">' .$row['user'] . ' : '. $row['message'] .'</div>';
}
?>
ajaxcall.php
<?php
ob_start();
?>
<?php
session_start();
?>
<?php
$txt=strip_tags($_GET['id']);
$txt1=strip_tags($_SESSION['SESS_MEMBER_ID']);
echo $txt;
echo " is typing ";
?>
The idea is to store a flag on a database and have an a .setTimeOut on your script on which will run whenever your field flag turns from 0 to 1
here is the code snippet to try
$('#txt_message').keyup(function(){
// Start a flag loop with an id of 'loop' and a counter.
var i = 1;
var dataString = 'flag='+ i ;
$.ajax({
type: "POST",
url: "notif.php",
data: dataString,
cache: false,
success: function(url){
}
});
this snippet will update your database whenever you type on your text field
var timer;
function AjaxRetrieve()
{
$.get("type_on.php?flag=0",function(data)
{
window.clearTimeout(timer);
$("#typing_on").html(data);
timer=window.setTimeout(function(){AjaxRetrieve()},3100);
});
}
timer=window.setTimeout(function(){AjaxRetrieve()},1300);
this snippet will be the one to update your flag after a few seconds

issue sending a retrieving value using ajax

This is a cleaner code of my preview problem, the idea is to send and retrieve a value using ajax, but the value is not being sent nor ajax seems to work. I updated this code because this way it could be easily tested on any machine. First time using ajax. Here is the code:
Javascript
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
$.ajax({
url: 'request.php',
type:'POST',
data: $("#form").serialize(),
dataType: 'json',
success: function(output_string){
alert(output_string);
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
HTML:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP file, request.php
<?php
$centro = $_POST['centro'];
$output_string = ''.$centro;
echo json_encode($output_string);
?>
Try Changing Your Code A bit like Below .
Jquery part
success: function(d){
var output=d[0].data; // Will output only first record
$('#cuentas').html(output);
} // End of success function of ajax form
PHP PART
$centro = $_POST['centro'];
$output_string = array('data'=>$centro);
echo json_encode($output_string);
if still not works Check The Developer tool in chrome or firebug in firefox to monitor the Requests
Looking at your code:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
I miss an ending-tag for the div id="centro". Therefore the click-event for jQuery("#centro") will not trigger.
I suppose it should be like this: (Always set <form> and </form> inside OR outside of a div, do not mix and put <form> outside and </form> inside of a div. Some things wont work as expected when you do a mix like that.
<?php
$result = 'works';
?>
<div id="centro">
<form id="form">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
</div> ><!-- end of div centro -->
<div id="cuentas">
</div>
I solved it, now this works, plus I added a gif loader:
Javascript:
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
var result = $("input#centro").val();
$.ajax({
url: 'request.php',
type:'POST',
data: { 'dataString': result },
beforeSend: function(){
$("#loader").show();
},
success: function(output_string){
$("#loader").hide();
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
HTML
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
<div id="loader" style="display:none"><img src="ajax-loader.gif" width="20px" height="20px"></div>
Click here
<br>
<input type="hidden" name="centro" id="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP
<?php
$data = $_POST['dataString'];
$output_string = '';
$output_string = '<h3>'.$data.' '.'testing'.'</h3>';
echo $output_string;
?>
Output: "works testing"

How to detect the number of uploaded files and their names before uploading from client side by javascript or jquery?

I want to upload multiple files and have a file called test.php with this code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="js/jquery-1.8.0.min.js"></script>
<script>
$(function(){
var myVar;
$('form').submit(function(){
myVar = setInterval(ajax, 1000);
});
var ajax = function() {
$.ajax({
url: 'test2.php',
type: 'post',
success: function(ajax_result){
$('.result').html(ajax_result);
if (!ajax_result) {
clearInterval(myVar);
}
},
error: function(){
alert('error');
}
});
};
});
</script>
</head>
<body style="width:100%; height:100%;">
<form action="test2.php" target="iframe" method="post" enctype="multipart/form-data" >
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="fil" />
<input name="file[]" type="file" multiple />
<input type="submit">
</form>
<iframe id="iframe" name="iframe"></iframe>
<div class="result" style="width:100%; height:100%;"></div>
</body>
</html>
and a file called test2.php with this code:
<?php
session_start();
if (isset($_FILES['file'])){
for ($i = 0; $i < count($_FILES['file']['tmp_name']); $i++) {
move_uploaded_file($_FILES['file']['tmp_name'][$i],'a/'.$_FILES['file']['name'][$i]);
}
}
if (isset($_SESSION[$key = ini_get("session.upload_progress.prefix") . 'fil'])) {
var_dump($_SESSION[$key]);
} else echo false;
?>
Now I want before sending files to server to detect the number of files selected via their names in the client side.
How can I do this?
$('form').submit(function() {
var numberOfFilesAboutToBeSubmitted = $("[name='file[]']", this ).prop("files").length;
});
Note that you are not submitting any files with your ajax request, it has no association with your form at all.
Also note that this doesn't work in IE < 10

Categories