How to get the client side post size? - javascript

I want to ask that how can I get the size of data I am passing as a client to the server.As while developing an application, I am unable to get the whole data on server side.My POST limit size at the server side is 6M as in php.ini file.
I have asked a similar question earlier(How to parse large data via POST query), but didn't get a prompt answer.
Thanks

Try this:
$data_size = (int) $_SERVER['CONTENT_LENGTH'];

Please use this function on submit form
<button onclick="store()" type="button">form submit</button>
function store(){
var totalsize = 0; // total post data size
$('form').find('input[type=file]').each(function() { // for all files in form
totalsize += this.files[0].size;
});
totalsize=totalsize+($("form").not("[type='file']").serialize().length);
if (totalsize > (6 * 1048576)) { // > 6MB
// this will exceed post_max_size PHP setting, now handle...
alert('this will exceed post_max_size PHP setting')
} else if ($('form').find('input[type=file]').length >= 10) { // max_file_upload_limit = 10;
// if file upload is more than 10
alert('upload is more than 10 files')
}else{
you are free upload data successfully
}
}

Related

How to resend dropzone files after uploading the form and receiving server messages

I have a form that contains article information and images that I submit using the DropZone library.
I have no problem with this library and it works very well, but when the submitted form had an error and I receive this error message on the client side via Ajax, the user fixes the problems and sends the form again, but unfortunately the form is not sent and no file is left. Not selected
While the files are available in the preview and are sent to the server only once.
What should I do to solve this problem?
Please enter simple codes.
Thanks
successmultiple function
myDropzone.on("successmultiple", function(file,serverResponse) {
/* None of the uploaded files are available in Drop Zone here anymore,
** and I had to delete the files so the user could choose again,
** which would not be a good user experience.
** Exactly what code should I write here so that there is no need to
** re-select files from the user's system?
*/
myDropzone.removeFile(file);
if(serverResponse.status)
{
// Success:: In this case, I have no problem
alert("Article saved successfully. Redirecting to the Articles page ...");
window.location.href = serverResponse.redirectedTo;
}
else
{
// Display errors received from the server to the user
alert("Please enter your name and resubmit the form.");
}
});
I think a possible solution is if you pass the event to your successhandler and prevent it from its default bahaviour.
Like so:
function successHandler(event){
event.preventDefault();
}
This should prevent it refreshing the page and loosing the file in the input.
Otherwise I would just save the file to a variable.
I found the answers to my questions myself and i will put it below for you too.
This code is written for Laravel blade file :
<script>
$("document").ready(()=>{
var path = "{{ $path }}";
var file = new File([path], "{{ $attach->file_name }}", {type: "{{ $attach->mime_type }}", lastModified: {{ $attach->updated_at}}})
file['status'] = "queued";
file['status'] = "queued";
file['previewElement'] = "div.dz-preview.dz-image-preview";
file['previewTemplate'] = "div.dz-preview.dz-image-preview";
file['_removeLink'] = "a.dz-remove";
file['webkitRelativePath'] = "";
file['width'] = 500;
file['height'] = 500;
file['accepted'] = true;
file['dataURL'] = path;
file['upload'] = {
bytesSent: 0 ,
filename: "{{ $attach->file_name }}" ,
progress: 0 ,
total: {{ $attach->file_size }} ,
uuid: "{{ md5($attach->id) }}" ,
};
myDropzone.emit("addedfile", file , path);
myDropzone.emit("thumbnail", file , path);
// myDropzone.emit("complete", itemInfo);
// myDropzone.options.maxFiles = myDropzone.options.maxFiles - 1;
myDropzone.files.push(file);
console.log(file);
});
</script>

POSTing data via AJAX to a PHP file

I have an input which accepts multiple files:
<input id="propertyImages" type="file" name="submission_img[]" multiple accept=".jpg, .jpeg, .png, .gif"/>
I then POST this data to a PHP file via JS/Ajax:
//Compiling the data which will be POSTed using AJAX. Note that the input above with id of propertyImages is not part of the form with id accommodationForm and is therefore appended to the formData.
var form = $("#accommodationForm")[0];
var formData = new FormData(form);
var propertyImages = document.getElementById("propertyImages");
for(var i=0; i<propertyImages.files.length; i++){
formData.append('propImages[]', propertyImages.files[i]);
}
//Printing to console the formData entries to confirm the formData data:
for (var d of formData.entries()) {
console.log(d);
}
//The partial code for the ajax call:
$.ajax({
url: "includes/handlers/ajax_submit_accommodation.php",
method: "POST",
data: formData,
...
The PHP code to which the data is POSTed:
$errorstatus = 0; //Used as an error flag
$maximagesize = 10485760; // Max file size allowed = 10MB
$acceptableimage = array( //The allowed mime types
'image/jpeg',
'image/jpg',
'image/png',
);
$submission_images_array = array();
$output = ""; //Used for debugging purposes
for($x=0; $x<30; $x++){ //30 is the upper limit for the amount of images POSTed
if($_FILES['propImages']['size'][$x] != 0){
if( $_FILES['propImages']['size'][$x] >= $maximagesize || (!in_array($_FILES['propImages']['type'][$x], $acceptableimage))) {
$errorstatus = 1;
} else {
$submission_img = $_FILES['propImages']['name'][$x];
$submission_img = pathinfo($submission_img, PATHINFO_FILENAME);
$submission_img = $submission_img.'-'.$user_id.'-'.rand().'.jpeg';
array_push($submission_images_array, $submission_img);
$submission_img_tmp = $_FILES['propImages']['tmp_name'][$x];
compressImage($submission_img_tmp, '../../submitted_media/accommodation/'.$submission_img, 50);
$output .= "$x:"." ".$submission_img."\n";
}
} else {
$output .= "$x: Empty image\n";
$submission_img = "";
array_push($submission_images_array, $submission_img);
}
}
file_put_contents('../../filenames.txt', $output ); // DEBUG
I want the user to attach a maximum of 30 images. I have made sure that the front end and back end check for this. The issue I am having is that I can attach 30 images - the debugging confirms this via the printing to console of the formData...i.e. the formData contains all the image data. However, when I look at the filenames.txt which I logged in the PHP it only contains the first 20 file names, while the last 10 entries is logged as "Empty image" (as I instructed in the code if the image size is 0).
Notes:
I have made sure (using other JS code) that propertyImages.files.length in the for loop cannot be greater than 30 and that when I attach 30 images, that the length is indeed 30.
I have made sure that max_input_vars in the PHP.ini file is not the issue.
The image sizes of the last 10 files are NOT 0. This has been confirmed by the logging of formData
Have a look at the max_file_uploads directive:
max_file_uploads integer
The maximum number of files allowed to be uploaded simultaneously.
As shown in the table in the "File Uploads" section, it defaults to 20:
Name Default Changeable Changelog
...
max_file_uploads 20 PHP_INI_SYSTEM Available since PHP 5.2.12.
You'll need to update that value your php.ini.
Also check you don't exceed post_max_size or
upload_max_filesize.

AjaxChat: Image Upload code hangs, freezes browser, crashes server

This is a tangent from the question here:
Returning value to Javascript from PHP called from XMLHttpRequest
I am adding an "image upload" button to my AjaxChat. I am using an XMLHttpRequest to send the image to the server, where I run a PHP script to move it to my images folder. Below is the Javascript function in charge of opening the XMLHttpRequest connection and sending the file:
function uploadImage() {
var form = document.getElementById('fileSelectForm');
var photo = document.getElementById('photo');
var uploadButton = document.getElementById('imageUploadButton');
form.onsubmit = function(event) {
event.preventDefault();
// Update button text
uploadButton.innerHTML = 'Uploading...';
//Get selected files from input
var files = photo.files;
// Create a new FormData object
var formData = new FormData();
// Loop through selected files
for (var i = 0; files.length > i; i++) {
var file = files[i];
// Check file type; only images are allowed
if (!file.type.match('image/*')) {
continue;
}
// Add file to request
formData.append('photo', file, file.name);
}
// Set up request
var xhr = new XMLHttpRequest();
// Open connection
xhr.open('POST', 'sites/all/modules/ajaxchat/upload.php', true);
// Set up handler for when request finishes
xhr.onload = function () {
if (xhr.status === 200) {
//File(s) uploaded
uploadButton.innerHTML = 'Upload';
var result = xhr.responseText;
ajaxChat.insertText('\n\[img\]http:\/\/www.mysite.com\/images' + result + '\[\/img\]');
ajaxChat.sendMessage();
} else {
alert('An error occurred!');
}
form.reset();
};
// Send data
xhr.send(formData);
}
}
Here is upload.php:
<?php
$valid_file = true;
if($_FILES['photo']['name']) {
//if no errors...
if(!$_FILES['photo']['error']) {
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
if($_FILES['photo']['size'] > (1024000)) { //can't be larger than 1 MB
$valid_file = false;
}
//if the file has passed the test
if($valid_file) {
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], '/var/www/html/images'.$new_file_name);
$message = $new_file_name;
exit("$message");
}
}
}
?>
I currently have the multiple image upload disabled, so the "Loop through selected files" only executes once.
The upload worked for a little bit on my PC, but then I tried uploading an image from my phone. When I did so, the entire server (and my browser) crashed, presumably due to an infinite loop somewhere. Every time I close my browser and log back in, or restart the server, or restart my computer, it hangs and eventually crashes again (on my PC or on my phone). I have been unable to find the script that is causing the issue. I get the feeling it's right under my nose. Does anyone see the problem? If you need the HTML form code then I can provide that, but I don't think it's necessary.

Passing a JavaScript value to PHP on completion of quiz

I have a web page that allows users to complete quizzes. These quizzes use JavaScript to populate original questions each time it is run.
Disclaimer: JS Noob alert.
After the questions are completed, the user is given a final score via this function:
function CheckFinished(){
var FB = '';
var AllDone = true;
for (var QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] < 0){
AllDone = false;
}
}
}
if (AllDone == true){
//Report final score and submit if necessary
NewScore();
CalculateOverallScore();
CalculateGrade();
FB = YourScoreIs + ' ' + RealScore + '%. (' + Grade + ')';
if (ShowCorrectFirstTime == true){
var CFT = 0;
for (QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] >= 1){
CFT++;
}
}
}
FB += '<br />' + CorrectFirstTime + ' ' + CFT + '/' + QsToShow;
}
All the Javascript here is pre-coded so I am trying my best to hack it. I am however struggling to work out how to pass the variable RealScore to a MySql database via PHP.
There are similar questions here on stackoverflow but none seem to help me.
By the looks of it AJAX seems to hold the answer, but how do I implement this into my JS code?
RealScore is only given a value after the quiz is complete, so my question is how do I go about posting this value to php, and beyond to update a field for a particular user in my database on completion of the quiz?
Thank you in advance for any help, and if you require any more info just let me know!
Storing data using AJAX (without JQuery)
What you are trying to do can pose a series of security vulnerabilities, it is important that you research ways to control and catch these if you care about your web application's security. These security flaws are outside the scope of this tutorial.
Requirements:
You will need your MySQL database table to have the fields "username" and "score"
What we are doing is writing two scripts, one in PHP and one in JavaScript (JS). The JS script will define a function that you can use to call the PHP script dynamically, and then react according to it's response.
The PHP script simply attempts to insert data into the database via $_POST.
To send the data to the database via AJAX, you need to call the Ajax() function, and the following is the usage of the funciton:
// JavaScript variable declarations
myUsername = "ReeceComo123";
myScriptLocation = "scripts/ajax.php";
myOutputLocation = getElementById("htmlObject");
// Call the function
Ajax(myOutputLocation, myScriptLocation, myUsername, RealScore);
So, without further ado...
JavaScript file:
/**
* outputLocation - any HTML object that can hold innerHTML (span, div, p)
* PHPScript - the URL of the PHP Ajax script
* username & score - the respective variables
*/
function Ajax(outputLocation, PHPScript, username, score) {
// Define AJAX Request
var ajaxReq = new XMLHttpRequest();
// Define how AJAX handles the response
ajaxReq.onreadystatechange=function(){
if (ajaxReq.readyState==4 && xml.status==200) {
// Send the response to the object outputLocation
document.getElementById(outputLocation).innerHTML = ajaxReq.responseText;
}
};
// Send Data to PHP script
ajaxReq.open("POST",PHPScript,true);
ajaxReq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajaxReq.send("username="username);
ajaxReq.send("score="score);
}
PHP file (you will need to fill in the MYSQL login data):
<?php
// MYSQL login data
DEFINE(MYSQL_host, 'localhost');
DEFINE(MYSQL_db, 'myDatabase');
DEFINE(MYSQL_user, 'mySQLuser');
DEFINE(MYSQL_pass, 'password123');
// If data in ajax request exists
if(isset($_POST["username"]) && isset($_POST["score"])) {
// Set data
$myUsername = $_POST["username"];
$myScore = intval($_POST["score"]);
} else
// Or else kill the script
die('Invalid AJAX request.');
// Set up the MySQL connection
$con = mysqli_connect(MYSQL_host,MYSQL_user,MYSQL_pass,MYSQL_db);
// Kill the page if no connection could be made
if (!$con) die('Could not connect: ' . mysqli_error($con));
// Prepare the SQL Query
$sql_query="INSERT INTO ".TABLE_NAME." (username, score)";
$sql_query.="VALUES ($myUsername, $myScore);";
// Run the Query
if(mysqli_query($con,$sql))
echo "Score Saved!"; // Return 0 if true
else
echo "Error Saving Score!"; // Return 1 if false
mysqli_close($con);
?>
I use these function for ajax without JQuery its just a javascript function doesnt work in IE6 or below. call this function with the right parameters and it should work.
//div = the div id where feedback will be displayed via echo.
//url = the location of your php script
//score = your score.
function Ajax(div, URL, score){
var xml = new XMLHttpRequest(); //sets xmlrequest
xml.onreadystatechange=function(){
if (xml.readyState==4 && xml.status==200){
document.getElementById(div).innerHTML=xml.responseText;//sets div
}
};
xml.open("POST",URL,true); //sets php url
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.send("score="score); //sends data via post
}
//Your PHP-script needs this.
$score = $_POST["score"]; //obtains score from POST.
//save your score here
echo "score saved"; //this will be displayed in the div set for feedback.
so call the javascript function with the right inputs, a div id, the url to your php script and the score. Then it will send the data to the back end, and you can send back some feedback to the user via echo.
Call simple a Script with the parameter score.
"savescore.php?score=" + RealScore
in PHP Side you save it
$score = isset ($_GET['score']) ? (int)$_GET['score'] : 0;
$db->Query('INSERT INTO ... ' . $score . ' ...');
You could call the URL via Ajax or hidden Iframe.
Example for Ajax
var request = $.ajax({
url: "/savescore.php?score=" + RealScore,
type: "GET"
});
request.done(function(msg) {
alert("Save successfull");
});
request.fail(function(jqXHR, textStatus) {
alert("Error on Saving");
});

Is it any limit for POST data size in Ajax?

I'm trying to send an array of data from my page to the MVC Action using jQuery Ajax. Here is my jQuery code:
$('#btnSave').click(
function () {
result = [];
$('#tblMatters tbody tr.mattersRow').each(function () {
if (!($(this).hasClass('warning'))) {
var item = {};
if ($(this).find('td.qbmatter > div.dropdown').length > 0) {
item.QBDescription = $(this).find('td.qbmatter > div.dropdown > a').text();
} else {
item.QBDescription = $(this).find('td.qbmatter').text();
}
var id = $(this).find("td:first > a").text();
item.Narrative = $("#collapse" + id).find("div.scrollCell").text();
item.WorkDate = $(this).find('td.workDate').text();
item.Hours = $(this).find('td.hours').text();
item.Person = $(this).find('td.person').text();
if ($(this).find('td.rate > div.dropdown').length > 0) {
item.Rate = $(this).find('td.rate > div.dropdown > a').text();
} else {
item.Rate = $(this).find('td.rate').text();
}
item.Amount = $(this).find('td.amount').text();
result.push(item);
}
});
var originalRecords = $("#tblSummary tr.summaryTotalRow td.summaryOriginalRecords").text();
var originalHours = $("#tblSummary tr.summaryTotalRow td.summaryOriginalHours").text();
var excludedHours = $("#tblSummary tr.summaryTotalRow td.summaryExcludedHours").text();
var totalHours = $("#tblSummary tr.summaryTotalRow td.summaryTotalHours").text();
$.ajax({
url: "/Home/SaveQBMatter",
type: "POST",
data: JSON.stringify({ 'Matters': result, 'originalRecords': originalRecords, 'originalHours': originalHours, 'excludedHours': excludedHours, 'totalHours': totalHours }),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Success!");
var url = '#Url.Action("Index", "Home")';
window.location.href = url;
} else {
alert("Error On the DB Level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
Let me explain a little bit. I have an HTML table that was built dynamically and I need to store this data into a database. In jQuery I have a loop going through the table and I store data of every row in the result array. Then I pass this data using Ajax into MVC Action.
And here is where my problem starts... I've realized that sometimes it goes as it should be, but sometimes I'm getting an error from Ajax alert("An error has occured!!!"); Now I've understood that this error occurs when my result array is getting big. For example: If it contains 100-150 items > everything is good, but when there are more than ~150 > Error.
Is there any POST limit in Ajax? How can I set it up for any sizes? I really need this functionality! Any help please!
My ActionResult Code:
public ActionResult SaveQBMatter(QBMatter[] Matters, string originalRecords, string originalHours, string excludedHours, string totalHours) {
DBAccess dba = new DBAccess();
int QBMatterID = 0;
int exportedFileID = 0;
foreach (QBMatter qb in Matters) {
dba.InsertQBMatter(qb.QBDescription, qb.Narrative, qb.WorkDate, qb.Person, qb.Hours, qb.Rate, qb.Amount, ref QBMatterID);
}
ExcelTranslator translator = new ExcelTranslator();
translator.CreateExcelFile("", Matters, originalRecords, originalHours, excludedHours, totalHours);
return Json(new { status = "Success", message = "Passed" });
}
UPDATE: Found a solution
JSON has a maximum length! I need to increase this value. In web.config add the following:
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
</appSettings>
JSON has a maximum length! I need to increase this value. In web.config add the following:
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
</appSettings>
Is it any POST Limit in Ajax?
No, the HTTP specification doesn't impose a specific size limit for posts. However it depends on the Web Server which you are using or the programming technology used to process the form submission.
In ASP.NET MVC you can try this:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1000000" />
</requestFiltering>
</security>
The HTTP spec doesn't defining a limitation of POST data size.
But using ASP.NET MVC, there could be a POST data limitation, try to increase it in your Web.Config file:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1000000" />
</requestFiltering>
</security>
From MSDN:
Specifies the maximum length of content in a request, in bytes. The
default value is 30000000.
This solved my problem:
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483647" />
</webServices>
</scripting>
</system.web.extensions>
IF there is a client-side limit then it would be browser specific but the HTTP spec does not define a limitation of POST data size.
Keep in mind that a POST is merely bytes across the network so the more fields you are posting then the longer it can take to upload that data.
A 1MB POST is going to make the user feel like the form is broken and unresponsive if using a traditional form submit.
If there are a lot of fields to serialize() then AJAX could hang up the browser while it collects all of the data. I think browsers do have a memory limit for JavaScript overall so if you hit that limit then the AJAX process will fail.
// wanna have some fun?
var html = '<div></div>';
for(var i = 0; i < 1000000; i++){
html += html;
}
Your best bet is to increase the maximum allowable POST size on the server-side to avoid issues.
Most commonly issues arise when people make an upload script which simply seems to hang while the user is confused why their 3MB pictures are going slow on a 125KB/s upload link.
The limit is set through a server 'max_post_size' or similar naming. Typical default server settings are 2-8 MB in one post.
On the client side, only GET has a maximum limit, generally considered 1500 bytes (minus 30-150 from request headers) and the reason is the MTU in the more lowlevel network hardware
In my case the class I was posting to had 'internal set' on the property.
Changed:
public EnabledDataBundle EnabledDataBundle { get; internal set; }
to:
public EnabledDataBundle EnabledDataBundle { get; set; }

Categories