Send blob image to php - javascript

I've created a dynamic upload and I want to send each blob to server after the images are cropped.
The problem is that it's sent only the last append and I don't know why.
var g = 0;
for(var j = 1;j <= boxno;j++) //boxno = 4 pics (I can have as much as I want)
{
input = $("#input"+j);
if(input.val().length !== 0)//check if input has any values
{
pcanvas = $("#pcanvas"+j)[0];
context = pcanvas.getContext("2d");
formData = new FormData($(this)[0]);
var blob = dataURLtoBlob(pcanvas.toDataURL('image/png'));
formData.append("pcanvas_"+g+"[]", blob);
g++;
}
}
var info = {
userid:userId,
username:userName,
picNr: g
}
formData.append("info[]", info["userid"]);
formData.append("info[]", info["username"]);
formData.append("info[]", info["picNr"]);
$.ajax({
url: "/send.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log(data);
},
error: function(data) {
console.log("error");
},
complete: function(data) {}
});
function dataURLtoBlob(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], {
type: contentType
});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
type: contentType
});
}
Now if I send using this method is sent only "pcanvas3", the last loop. But If I put $.ajax inside the loop is working, but I don't want this, because I want to add into my db and is adding 4 times the same results (also I create new folder for a specific upload, so if I add inside the loop $.ajax it creates 4 folders)
Here is my php.
$id = $_POST['info'][0];
$username = $_POST['info'][1];
$picNr = $_POST['info'][2];
$shuffledid = str_shuffle($id);
$uniqueid = $id.$shuffledid;
$path = $_SERVER['DOCUMENT_ROOT'].'/_user/_tests/en/'.$uniqueid;
if(!file_exists($path))
{
mkdir($path,0755);
}
for($g = 0; $g <= $picNr; $g++)
{
$virtualbg = imagecreatetruecolor(400,410);
$tmp_file = $_FILES['pcanvas_'.$g]['tmp_name'][0];
$pic = imagecreatefrompng($tmp_file);
list($width,$height,$type) = getimagesize($tmp_file);
imagecopyresampled($virtualbg,$pic, 0,0,0,0, 400,410,$width,$height);
imagejpeg($virtualbg,$path.'/pic_'.$g.'.jpg');
imagedestroy($pic);
imagedestroy($virtualbg);
}
As you can see I'm passing through each "pcanvas_0,1,2,3,4" but only the last one it gets the tmp_files.
What I'm doing it wrong? I think the problem is on my append. I've tried to append something else to the formData("pcanvas.. and it works but my blob is not appended.
Thank you!

Related

Big foreach freeze DOM

There is a script that processes lines from a text file and sends it to the server. The server, meanwhile, returns a response and fills in the required information.
The problem is that when you try to download a file with about a million entries, the browser freezes and takes a very long time to process.
Is it possible to make this process without browser delays?
document.getElementById('file').onchange = function() {
$('#uploader-after').show();
$('#uploader-before').hide();
$("#file").prop('disabled', true);
var o_time = performance.now();
$('o_total').text("");
$('o_errors').text("");
$('o_time').text("");
var file = this.files[0];
var count = 1;
var errorCount = 0;
$('.file-name').text(file.name);
var reader = new FileReader(file);
reader.onload = function(progressEvent) {
var lines = this.result.split('\n');
$('#find-count').text(lines.length);
for(var line = 0; line < lines.length; line++) {
//setTimeout( function() { // i try this, but dont work
jQuery.ajax({
'async': true,
'global': false,
'type': "POST",
'url': 'getFile.php',
'data': { url: lines[line] },
'dataType': "json",
'success': function(data) {
var answer = data.answer ? data.answer : "";
var id = data.id ? data.id : "";
$('#proc-count').text(count);
var proc = Math.round(count / lines.length * 100);
$('proc').text(proc);
$("#pg-bar-line").css("width", proc + "%");
count++;
if(id == "") {
errorCount++;
}
$('o_total').text(count - 1);
$('o_errors').text(errorCount);
scannert.DataTable().row.add([id, data.inputURL, answer]).draw(false);
if(count === lines.length) {
o_time = performance.now() - o_time;
$('o_time').text(msToTime(o_time));
$('.otchet').show();
$('#uploader-after').hide();
$('#uploader-before').show();
$("#file").prop('disabled', false);
}
},
'error': function() {
count++;
}
});
//}, 5);
}
};
reader.readAsText(file);
};
Ill try setTimeout, but it doesnt work -_-

Onclick for arrays in JSON

I'm retrieving data through an api, and creating a list using JS. I was wondering if it was possible to create a onclick function for every element in an array element of a JSON. The elements are being displayed, but nothing happens when I click them. Also, is it possible to pass on data in the JSON with this redirection to a new page?
My code is as follows:
var url = "https://api.nytimes.com/svc/movies/v2/reviews/all.json?api-key=b5f6bc931d6e446a998eb063a7c13d8e";
$.ajax({
url: url,
method: 'GET',
dataType: 'json',
success: function (data) {
var data = data;
details(data);
for (var i = 0; i < Object.keys(data.results[0]).length; i++) {
document.getElementById("movlist");
var item = document.createElement('li');
item.className = 'listele';
var itempicdiv = document.createElement('div');
itempicdiv.className = 'picdiv';
var itempic = document.createElement('img');
itempic.className = 'pic';
itempic.src = data.results[i].multimedia.src;
var itemnamediv = document.createElement('div');
itemnamediv.className = 'namediv';
var itemname = document.createTextNode(data.results[i].display_title);
itemname.className = 'name';
itempicdiv.appendChild(itempic);
itemnamediv.appendChild(itemname);
item.appendChild(itempicdiv);
item.appendChild(itemnamediv);
list.appendChild(item);
}
}
}).done(function (result) {
console.log(result);
}).fail(function (err) {
throw err;
});
function details(data) {
for (var j = 0; j < Object.keys(data.results[0]).length; j++) {
var t = data.results[j];
t.onclick = function () {
location.href = 'detail.html';
}
}
}

why my file upload not copied on directory? (javascript, php)

please help
This my constructor in class
$this->covername = $image['cover']['name'];
$this->coverdir = $image['cover']['tmp_name'];
$this->covertype = pathinfo($this->covername, PATHINFO_EXTENSION);
This json script
prosesSave = function(saveas) {
document.getElementById("saveas").value = saveas;
var message = $('#message');
var fields = $("#form1,#form2,#form3");
var formdata = new FormData(fields[0]);
$.ajax({
type: "POST",
url: "project/proses-new-page.php",
data: formdata,
cache: false,
contentType : false,
processData : false,
dataType: 'json',
success: function(response) {
$(message).empty();
if(response.saveas){
if (saveas == 'Draft') {
var idmsg = $("<div></div>", {
"class":"callout callout-info"}).appendTo(message);
}else{
var idmsg = $("<div></div>", {
"class":"callout callout-success"}).appendTo(message);
}
}else{
var idmsg = $("<div></div>", {
"class":"callout callout-danger"}).appendTo(message);
}
$(idmsg).empty().html(response.html);
document.getElementById("status").value = "EditPage";
document.getElementById("idpage").value = response.idpage;
}
});
return false;}
This my process copy
if ($this->covername) {
$this->filename = $id."_".$this->date.".".$this->covertype;
$this->move = $this->dirupload."cover/".$this->filename;
if(!move_uploaded_file($this->coverdir, $this->move)){
$this->response_html = '<p>Faild</p>'.$this->covername."<br>".$this->coverdir."<br>".$this->move;
}else{
$this->response_html = '<p>Succes</p>'.$this->covername;
}
chmod($this->move, 0777);
mysqli_query($this->conn, "UPDATE tb_pages SET COVER_PAGE = '".$this->filename."' WHERE ID_PAGE = '".$id."'");
}
i have problem with my code. in this code name of image, type and so on can insert into database. but on the image can't copied in directory($this->coverdir).
sory for my bad english.

How to pass the select box value as an array using AJAX from one page to another in PHP?

var message = $("#send_message").val();
var Teaminput = $("#sms_reminder_team").val();
for (var i = 0; i <Teaminput.length; i++)
{
var team=Teaminput[i];
}
var Memberinput = $("#sms_reminder_members").val();
for (var i = 0; i <Memberinput.length; i++)
{
var members=Memberinput[i];
}
Get 2 varaibles as array members and team
var parameter = "message="+message+"&team="+team+"&members="+members;
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage',
type: 'POST',
data: parameter,
success: function(data)
{
document.getElementById('check').innerHTML = data;
}
});
How to send both array variables using AJAX from current page to "dir_sendmessage".
Change the below line
var parameter = "message="+message+"&team="+team+"&members="+members;
to
var parameter = "message="+message+"&team="+JSON.stringify(team)+"&members="+JSON.stringify(members);
Edit: Modify like this too
var team = [];
var members = [];
for (var i = 0; i <Teaminput.length; i++)
{
team=Teaminput[i];
}
var Memberinput = $("#sms_reminder_members").val();
for (var i = 0; i <Memberinput.length; i++)
{
members=Memberinput[i];
}
Note: When you add var in each line in the loop, it will declare a new variable. You have to edit like the above code
After update the code with the JSON.stringify() function, you will be able to get the value as an array in you PHP code
Ajax will not directly pass Jquery array to PHP
First of all ideally you should send in JSON format or use array.tostring() ( can avoid this )
But if you have to send it as array you can try following:
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage',
type: 'POST',
data: {team:team, members: members},
success: function(data) {
document.getElementById('check').innerHTML = data; } });
var message = $("#send_message").val();
var teaminputt = $("#sms_reminder_team").val();
team = new Array();
members = new Array();
for (var i = 0; i <teaminputt.length; i++)
{
var team=teaminputt[i];
}
var memberinput = $("#sms_reminder_members").val();
for (var i = 0; i <memberinput.length; i++)
{
var members=memberinput[i];
}
var parameter = "message="+message+"&team="+team+"&members="+members;
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage',
type: 'POST',
data: parameter,
success: function(data)
{
document.getElementById('check').innerHTML = data;
}
});
$("#msg-send-btn").click(function() {
var message = $("#send_message").val();
var optionsmembers = $('#sms_reminder_members option:selected');
var members = $.map(optionsmembers ,function(option) {
return option.value;
});
//---- Using $.map get all selcted data as a an Array.
var postData = {
message,
members
}
//---- For Avoid Json-Stringfy.
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage.php',
type: 'POST',
data:{myData:postData},
//----- And It's Work Perfectly.

getting "undefined" when i print json array with js

I want to parse json array it came down from json.jsp, but when i access parse.js it displays undefined
Here is parse.js
$(document).ready(function() {
$('#login').click(function(event) {
$.get('json.jsp', {
}, function(responseText) {
var myJSONObject1 = responseText;
var myJSONObject = JSON.parse(myJSONObject1);
var len = myJSONObject.length;
var out = "";
for (var i = 0; i < len; i++) {
var student = myJSONObject[i];
out += "<li>"+student.ircEvent + "<li>" + student.method+"<li>"+student.regex;
}
document.getElementById("ajaxResponse").innerHTML = out;
});
});
});
and my json.jsp is,
<%
response.setContentType("plain/text");
User user = new User("RAM","ram#gmail.com");
User user1 = new User("Ravi","ravi#gmail.com");
User user2 = new User("Raghu","raghu#gmail.com");
List list = new ArrayList();
list.add(user);list.add(user1);list.add(user2);
String json = new Gson().toJson(list);
response.getWriter().write(json);
%>
when i access parse.js file, it displays undefined
any ideas......
Just use $.ajax and set the dataType to json. No need to parse anything. jQuery does it for you. http://api.jquery.com/jquery.ajax/
jQuery(document).ready(function($) {
$.ajax({
url: 'json.jsp',
type: 'get',
dataType: 'json',
success: function(data) {
if (data.length) {
var ajaxResponse = document.createElement('table'),
tbody = document.createElement('tbody');
for (var i in data) {
if (data.hasOwnProperty(i)) {
var tr = document.createElement('tr'),
key = document.createElement('td'),
keyText = document.createTextNode(i),
value = document.createElement('td'),
valueText = document.createTextNode(data[i]);
key.appendChild(keyText);
tr.appendChild(key);
value.appendChild(valueText);
tr.appendChild(value);
tbody.appendChild(tr);
}
}
ajaxResponse.appendChild(tbody);
$("#ajaxResponse").append(ajaxResponse);
}
else alert("No data returned!");
}
});
});

Categories

Resources