Ajax posting on localhost but not on VPS host - javascript

I've been facing this issue for many days i've searched the whole internet fixed my php.ini even the ngnix.confg file
Please tell me if anything is wrong with the code
i've edited the Cropper Plugin not to download but replace the current image.
so what i did i used the ajax post to do it.
PS: Ajax is sending huge data in post since it's a canvas and this whole process is working fine on localhost but not working on server. The whole site is on laravel but this code is on native php.
I've also figured out that if image is small then it's working fine and if image is large then it's not working on server.
AJAX code in main.js file
$('.docs-buttons').on('click', '[data-method]', function () {
var $this = $(this);
var data = $this.data();
var $target;
var result;
if ($this.prop('disabled') || $this.hasClass('disabled')) {
return;
}
if ($image.data('cropper') && data.method) {
data = $.extend({}, data); // Clone a new one
if (typeof data.target !== 'undefined') {
$target = $(data.target);
if (typeof data.option === 'undefined') {
try {
data.option = JSON.parse($target.val());
} catch (e) {
console.log(e.message);
}
}
}
if (data.method === 'rotate') {
$image.cropper('clear');
}
result = $image.cropper(data.method, data.option, data.secondOption);
if (data.method === 'rotate') {
$image.cropper('crop');
}
switch (data.method) {
case 'scaleX':
case 'scaleY':
$(this).data('option', -data.option);
break;
case 'getCroppedCanvas':
if (result) {
var temp = $(' #image').attr('src');
jQuery.ajax({
url: '../../cropper/demo/save.php',
type: 'POST',
data: {
data: result.toDataURL('image/jpeg'),
name: temp,
},
complete: function(data, status)
{
console.log(data.responseText);
if(status=='success')
{
$('#image').cropper("replace", temp);
}
else
{
alert('Error has been occurred');
}
}
});
}
break;
}
if ($.isPlainObject(result) && $target) {
try {
$target.val(JSON.stringify(result));
} catch (e) {
console.log(e.message);
}
}
}
});
save.php (To store the image on server)
<?php
$based64Image=substr($_POST['data'], strpos($_POST['data'], ',')+1);
$fileName='';
$fileName = substr($_POST['name'], 34);
$image = imagecreatefromstring(base64_decode($based64Image));
if($image != false)
{
if(!imagejpeg($image,"..\..\images\image\\".$fileName))
{
// fail;
}
}
else
{
// fail;
}
?>
Please Help Thanks

Add the following to your conf file
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
For more details and understanding please read
https://gist.github.com/magnetikonline/11312172#determine-fastcgi-response-sizes
These results may not be accurate, so reading to ensure your proper configuration is advised

Related

onComplete in AjaxUpload getting before server side code hits

I am working on some legacy code which is using Asp.net and ajax where we do one functionality to upload a pdf. To upload file our legacy code uses AjaxUpload, but I observed some weird behavior of AjaxUpload where onComplete event is getting called before actual file got uploaded by server side code because of this though the file got uploaded successfully still user gets an error message on screen saying upload failed.
And here the most weird thins is that same code was working fine till last week.
Code:
initFileUpload: function () {
debugger;
new AjaxUpload('aj-assetfile', {
action: '/Util/FileUploadHandler.ashx?type=asset&signup=False&oldfile=' + assetObj.AssetPath + '&as=' + assetObj.AssetID,
//action: ML.Assets.handlerPath + '?action=uploadfile',
name: 'AccountSignupUploadContent',
onSubmit: function (file, ext) {
ML.Assets.isUploading = true;
ML.Assets.toggleAsfMask(true);
// change button text, when user selects file
$asffile.val('Uploading');
$astfileerror.hide();
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
// Uploding -> Uploading. -> Uploading...
ML.Assets.interval = window.setInterval(function () {
var text = $asffile.val();
if (text.length < 13) {
$asffile.val(text + '.');
} else {
$asffile.val('Uploading');
}
}, 200);
//if url field block is visible
if ($asseturlbkl.is(':visible')) {
$asfurl.val(''); //reset values of url
$asfurl.removeClass('requiref error'); //remove require field class
$asfurlerror.hide(); //hide errors
}
},
onComplete: function (file, responseJSON) {
debugger;
ML.Assets.toggleAsfMask(false);
ML.Assets.isUploading = false;
window.clearInterval(ML.Assets.interval);
this.enable();
var success = false;
var responseMsg = '';
try {
var response = JSON.parse(responseJSON);
if (response.status == 'success') { //(response.getElementsByTagName('status')[0].textContent == 'success') {
success = true;
} else {
success = false;
responseMsg = ': ' + response.message;
}
} catch (e) {
success = false;
}
if (success) {
assetObj.AssetMimeType = response.mimetype;
$asffile.val(response.path);
$asffile.valid(); //clear errors
ML.Assets.madeChanges();
if (ML.Assets.saveAfterUpload) { //if user submitted form while uploading
ML.Assets.saveAsset(); //run the save callback
}
} else { //error
assetObj.AssetMimeType = "";
$asffile.val('');
$astfileerror.show().text('Upload failed' + responseMsg);
//if url field block is visible and type is not free offer.
if ($asseturlbkl.is(':visible') && this.type !== undefined && assetObj.AssetType != this.type.FREEOFFER) {
$asfurl.addClass('requiref'); //remove require field class
}
ML.Assets.hideLoader();
}
}
});
}
I was facing the same issue but I fixed it with some minor change in plugin.
When “iframeSrc” is set to “javascript:false” on https or http pages, Chrome now seems to cancel the request. Changing this to “about:blank” seems to resolve the issue.
Old Code:
var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
New Code with chagnes:
var iframe = toElement('<iframe src="about:blank;" name="' + id + '" />');
After changing the code it's working fine. I hope it will work for you as well. :)
Reference (For more details): https://www.infomazeelite.com/ajax-file-upload-is-not-working-in-the-latest-chrome-version-83-0-4103-61-official-build-64-bit/

XMLHttpRequest POST _self using localStorage with PHP

I'm using PHP 7.3 with MySQL v5.6.
Browsing a catalog page, I stored some items ids to localStorage.wishlistStorage.data, and now on the wishlist page I want to retrieve this list of ids for display. I'm using PHP because later I will be sending and retrieving items from a database. Also, it's easy to build HTML on the fly using PHP and a POST array. Unfortunately, I'm struggling with the AJAX XMLHttpRequest.
I am loading a Javascript file at the bottom of the page that retrieves the localStorage data:
var wishlistStorage = {};
window.addEventListener("load", function() {
wishlistStorage.get();
loadWishlist();
});
wishlistStorage = {
data : null, // empty storage
get : function() {
wishlistStorage.data = localStorage.getItem("wishlistStorage");
if(wishlistStorage.data === null) {
wishlistStorage.data = { items: [], item_notes: [], comments: '' };
wishlistStorage.save();
}
else {
wishlistStorage.data = JSON.parse(wishlistStorage.data);
}
}
};
// get wishlist contents
function loadWishlist() {
var items = wishlistStorage.data.items.join("%20");
var wishlistRequest;
if(window.XMLHttpRequest) {
wishlistRequest = new XMLHttpRequest();
} else {
wishlistRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
wishlistRequest.onreadystatechange = function() {
if(wishlistRequest.readyState == 4 && wishlistRequest.status == 200) {
console.log("Got them.");
} else {
console.log("I see nothing.");
}
wishlistRequest.open("POST", "_self", true);
wishlistRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
wishlistRequest.send("wishlist_items=" + encodeURIComponent(items));
}
}
In the body of wishlist.php
<?php
if (array_key_exists('wishlist', $_POST)) {
$temporary_wishlist = $_POST['wishlist'];
echo "Yes, it works! $temporary_wishlist";
} else {
echo 'Invalid parameters!';
}
?>
All I get is the "Invalid Parameters" message. None of the console.log messages appear. Where am I going wrong?
source

How to make progress bar on Ajax Upload

Hi I am using Ajax Upload JS 3.5 is there a way to make a progress upon uploading of image / File ?. All I see in my net is by using the <input type="file"> button and my project is not a bootstrap.
Here is my currently code
jQuery(document).ready(function () {
var extension = "";
var btnUploadDrvr = $("#btnFitaDocBrowse");
var hidFilenameDrvr = $("#imgFitaDoc");
var hidDoccFrame = $("#frmFitaDoc");
InitAjaxUpload(btnUploadDrvr, hidFilenameDrvr, hidDoccFrame );
function InitAjaxUpload(btnUpload, imgHolder, hidDoccFrame) {
new AjaxUpload(btnUpload, {
action: '../UploadDownload/UploadLocalPic',
data: '',
name: 'uploadfile',
onSubmit: function (file, ext) {
extension = ext[0];
if (!(ext && /^(jpg|png|jpeg|gif|pdf|PDF)$/.test(ext))) {
alert("File format is not supported.");
return false;
}
},
onComplete: function (file, response) {
//Add uploaded file to list
if (response !== "failed") {
$("#frmFitaDoc").attr('src', 'data:application/pdf;base64,' + response);
}
}
});
}
});
And I saw this can this be possible to embed in my code?.

PHP write file works, but says false

I don't have much experience with PHP, but what I'm trying to do is to write content to a file. For some reason the content is written to the file, but still returns 'failed to write to file!' with the 400 status code. But the contents are successfully written to the file. How?
php code (update.php):
<?php
//get root and page of request
$content_root = $_SERVER['DOCUMENT_ROOT'] . '/Animagie/content';
$page = $_POST['page'];
//open the correct contentfile
$content_file = fopen($content_root . '/' . $page, 'w');
if (isset($_POST[$page . '-content'])) {
if (fwrite($content_file, $_POST[$page . '-content']) === FALSE ) {
echo 'failed to write to file!';
fclose($content_file);
http_response_code(400);
} else {
fclose($content_file);
http_response_code(200);
}
} else {
echo 'something went wrong!';
fclose($content_file);
http_response_code(400);
}
?>
I call update.php with following code:
editor.addEventListener('saved', function(e) {
var name, payload, regions, xhr;
//check if something changed
regions = e.detail().regions;
if (Object.keys(regions).length === 0) {
return;
}
//set editor busy while saving
this.busy(true);
// Collect the contents of each region into a FormData instance
payload = new FormData();
payload.append('page', getCurrentPage());
for (name in regions) {
if (regions.hasOwnProperty(name)) {
payload.append(name, regions[name]);
}
}
// Send the updated content to the server to be saved
function onStateChange(e) {
//check if request is finished
if (e.target.readyState === 4) {
editor.busy(false);
if (e.target.status === '200') {
new ContentTools.FlashUI('ok');
} else {
new ContentTools.FlashUI('no');
}
}
}
xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', onStateChange);
xhr.open('POST', '../api/update.php');
xhr.send(payload);
});
As you probably can tell it's quiet important to get the correct statuscode since I check for it and return if it's succesfull or not to the user. Anyone able to help me?
Thanks in advance!
Apperently the problem lays in the javascript check:
if (e.target.status === '200') {
new ContentTools.FlashUI('ok');
} else {
new ContentTools.FlashUI('no');
}
should be
if (e.target.status == 200) {
new ContentTools.FlashUI('ok');
} else {
new ContentTools.FlashUI('no');
}
Also after I switched the if-statement (like told by #Jon Stirling), postman wasn't refreshed yet. So it was partially a wrong if-statement on the server side & wrong if-statement on the client side.

Input type=file alternative to be used in Google chrome extension

I am developing a Google chrome extension where user uploads a file manually. I have created a file type input in popup.html and tried to read the file. But that is not working as that is bug in Google chrome..
Please someone suggest me if there is any other work around. I found this but I am unable to proceed cause I could not understand their terminology.
Thanks
I could not find any workaround to solve this problem and solved it in another way..Here I am posting the code which I have used
First in Popup Page :
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {
'action': 'inject'
});
});
In Content Script :
chrome.extension.onRequest.addListener(function ListeningMethod(request, sender,callback)
{
switch(request.action)
{
case "inject":
if($('body').find('#TesterItems').size() < 1)
{
$('body').prepend("<div id='TesterItems'><center><input type='file' id='xfilex'></center></div>");
}
else
{
$('#TesterItems').html("<center><input type='file' id='xfilex'></center>");
$('#TesterItems').slideToggle('slow');
}
break;
}
});
$('#xfilex').live('change',function()
{
var file = document.getElementById('xfilex').files[0];
if(file)
{
var reader;
reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = loaded;
}
});
function loaded(evt)
{
var fileString = evt.target.result;
var str = fileString;
if(str.length > 0 )
{
chrome.extension.sendRequest({method: "passThisXML", key: str}, function(response) {
$('#TesterItems').html('<center><span style="padding:3px">Successfully loaded XML.</span></center>');
$('#TesterItems').slideToggle('slow');
var Dat = response.data;
});
}
}

Categories