Bypass Input FIle; Uploading Image directly using javascript - javascript

I'd like to automate the uploading of images to a website. The problem is I'm stuck at the input file type. The site seems to use a JQuery uploading method. I'd like to feed the script the image data directly satisfying validation.
Here's the HTML of the input file type used to upload images along with it's structure.
<div id="item_img_msg1" abp="568"></div>
<div class="mg_b5 mg_l10" id="item_img_empty1" abp="569">
<input name="updfile1" class=" " id="item_img_file1" type="file" abp="570">
</div>
<div class="mg_b5 mg_l10" id="item_img_selected1" style="display: none;" abp="571">
<img id="item_img1" src="/common/images/noimage.gif" abp="572">
<input id="item_img_del1" style="vertical-align: bottom;" type="button" value="Delete" abp="573">
</div>
<input name="hdnImgDelFlg1" id="imgdelflg1" type="hidden" value="" abp="574">
<span class="font_85 pg_l10" abp="575">(Size:Under 1MB;Format:JPEG,GIF,PNG</span>
<br abp="576">
<span class="pg_l10" abp="577">Wide or Tall images will be chopped</span>
<div class="HelpTxt mg_t5" abp="578">
Guide:Image Upload Guide
</div>
And here's the related javascript.
var ImageUploader = function (idx) {
var postData = {
name: "updfile",
index: idx,
imgApiType: $("#img_api_type").val(),
unq: $("#unique_id").val(),
postCnt: 0
};
var deleteData = {
index: idx,
imgApiType: $("#img_api_type").val(),
unq: $("#unique_id").val(),
postCnt: 0
};
var onIamgeUploaded = function (response) {
var status = $(response).find("otoma_status").text();
if (status != "0") {
$("#item_img_msg" + idx).html("<div class='error_with_icon'>Upload Failed</div>");
return;
}
var url = $(response).find("img_url").text();
$("#item_img" + idx).attr("src", url + "?" + new Date().getTime());
$("#item_img_empty" + idx).hide();
$("#item_img_selected" + idx).show();
$("[name='hdnImgDelFlg" + idx + "']").val("0");
postData.postCnt++;
};
this.manualUpload = function (data) {
var postDataForManual = $.extend({}, postData, data);
jQuery.ajax({
data: postDataForManual,
url: "/api/itemimage/upload",
cache: false,
type: "post",
beforeSend: function (XMLHttpRequest) {
var loading_image_tag = $("<img>").attr({
"class": "js-loading_image" + idx,
src: Module.imgpath + "/lib/fileuploader/loading.gif"
});
$("#item_img_empty" + idx).after(loading_image_tag);
$("#item_img_empty" + idx).hide();
},
success: function (response) {
onIamgeUploaded(response);
},
error: function () {
$("#item_img_msg" + idx).html("<div class='error_with_icon'>Upload Failed!</div>");
$("#item_img_empty" + idx).show();
},
complete: function () {
$("img.js-loading_image" + idx).remove();
}
});
};
var init = function (idx) {
postData.index = idx;
try {
new AjaxUpload("#item_img_file" + idx, {
action: "/api/itemimage/upload",
name: "updfile",
data: postData,
onSubmit: function (file, extension) {
AjaxUtils.loading(true);
$("#item_img_msg" + idx).html("");
},
onComplete: function (file, response) {
AjaxUtils.loading(false);
onIamgeUploaded(response);
}
});
} catch (e) {}
$("#item_img_del" + idx).click(function () {
jQuery.ajax({
dateType: "xml",
data: deleteData,
url: "/api/itemimage/delete",
cache: false,
type: "post",
beforeSend: function (XMLHttpRequest) {
deleteData.postCnt = postData.postCnt;
$("#item_img_msg" + idx).html("");
$("#item_img_empty" + idx).show();
$("#item_img_selected" + idx).hide();
$("[name='hdnImgDelFlg" + idx + "']").val("1");
},
error: function () {
$("#item_img_msg" + idx).html("<div class='error_with_icon'>Upload Failed!</div>");
}
});
});
};
init(idx);
};
var ImageUploaders = [];
var maxImageNumber = $("#max_image_number").val();
for (var i = 1; i <= maxImageNumber; i++) {
ImageUploaders.push(new ImageUploader(i));
}
var params = Module.Utility.getParameters();
var buying_support_item_id = params.buying_support_item_id;
if (buying_support_item_id) {
ImageUploaders[0].manualUpload({
buying_support_item_id: buying_support_item_id
});
}
I can make javascript script calls to the webpage. I just basically need to know which calls to make. Does anyone know how to do this? If so, could you provide sample code.
Thanks!

Related

How can I fix the html error in the jquery post?

I am responding by sending a post in jquery. But div also writes when the div is closed and when the div is opened.
I need to leave only after closing
the code I wrote
<script>
jQuery(document).ready(function() {
jQuery(".button").bind("click", function() {
var name = jQuery('.nameField').val();
var surname = jQuery('.surnameField').val();
var age = jQuery('.ageField').val();
jQuery('.surnameField').val('');
jQuery.ajax({
url: "../ajax/db.php",
type: "POST",
data: {
name: name,
surname: surname,
age: age
}, // Передаем данные для записи
dataType: "json",
success: function(result) {
if (result) {
jQuery('.comments-list div').remove();
jQuery('.comments-list').append(function() {
var res = '';
for (var i = 0; i < result.users.name.length; i++) {
res += '<div class="media last-child"><a class="media-left" href="#">' + result.users.id[i] + '</a><div class="media-body"><h4 class="media-heading user_name">' + result.users.name[i] + '<small>' + result.users.age[i] + '</small></h4><p>' + result.users.surname[i] + '<p></div></div><hr class="invis">';
}
return res;
});
console.log(result);
} else {
alert(result.message);
}
return false;
}
});
return false;
});
});
</script>

I want to return function result after calculating in a for loop

i want to check whether is a valid item or not before saving the values. then i create java-script function to check validation and return result. but the problem is this function returns before validate items, the always true the condition above if condition. my code is below. could anyone help me please?
this is series of ajax call and i'm not aware of how to use callback for this..
if(IsValidItems() != ''){
//Do something
}
function IsValidItems() {
var IsvalidStatus = '';
var lineqty = 0;
var LineNumber = -1;
var allRowData = jQuery("#tblJQGrid").jqGrid("getRowData");
for (var i = 0; i < allRowData.length - 1; i++) {
if (allRowData[i].BulkItem != "False") {
if (allRowData[i].quantity != '') {
lineqty = parseInt(allRowData[i].quantity);
LineNumber = i + 1;
var postURL = "/BookingDetail/GetItemAvailablity?ItemCode=" + allRowData[i].itemCode + "&StartDate=" + allRowData[i].StartDate + "&EndDate=" + allRowData[i].EndDate + "&srno=" + allRowData[i].srno + "&locationID=" + allRowData[i].Location;
$.ajax({
url: postURL,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "",
type: "POST",
async: true,
dataFilter: function (data) {
return data;
},
success: function (result) {
if (lineqty > parseInt(result)) {
IsvalidStatus = IsvalidStatus + "," + LineNumber;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) { }
});
}
}
}
return IsvalidStatus;
}

Upload multiple image using AJAX, PHP and jQuery

I have a lot of problem to upload multiple images using AJAX. I write this code:
HTML
<form id="upload" method="post" enctype="multipart/form-data">
<div id="drop" class="drop-area">
<div class="drop-area-label">
Drop image here
</div>
<input type="file" name="file" id="file" multiple/>
</div>
<ul class="gallery-image-list" id="uploads">
<!-- The file uploads will be shown here -->
</ul>
</form>
<div id="listTable"></div>
jQuery/AJAX
$(document).on("change", "input[name^='file']", function(e){
e.preventDefault();
var This = this,
display = $("#uploads");
// list all file data
$.each(This.files, function(i, obj){
// for each image run script asynchronous
(function(i) {
// get data from input file
var file = This.files[i],
name = file.name,
size = file.size,
type = file.type,
lastModified = file.lastModified,
lastModifiedDate = file.lastModifiedDate,
webkitRelativePath = file.webkitRelativePath,
slice = file.slice,
i = i;
// DEBUG
/*
var acc = []
$.each(file, function(index, value) {
acc.push(index + ": " + value);
});
alert(JSON.stringify(acc));
*/
$.ajax({
url:'/ajax/upload.php',
contentType: "multipart/form-data",
data:{
"image":
{
"name":name,
"size":size,
"type":type,
"lastModified":lastModified,
"lastModifiedDate":lastModifiedDate,
"webkitRelativePath":webkitRelativePath,
//"slice":slice,
}
},
type: "POST",
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
// Check if upload property exists
if(myXhr.upload)
{
// For handling the progress of the upload
myXhr.upload.addEventListener("progress",progressHandlingFunction, false);
}
return myXhr;
},
cache: false,
success : function(data){
// load ajax data
$("#listTable").append(data);
}
});
// display progress
function progressHandlingFunction(e){
if(e.lengthComputable){
var perc = Math.round((e.loaded / e.total)*100);
perc = ( (perc >= 100) ? 100 : ( (perc <= 0) ? 0 : 0 ) );
$("#progress"+i+" > div")
.attr({"aria-valuenow":perc})
.css("width", perc+"%");
}
}
// display list of files
display.append('<li>'+name+'</li><div class="progress" id="progress'+i+'">'
+'<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">'
+'</div></div>');
})(i);
});
});
I've tried a various versions and I never succeed to send multiple data through ajax. I have tried in this way what you see above, and now I get only POST informations. I understand why i get POST but I need to send FILES information and I do not know where I'm wrong.
I not work the first time with ajax and often use it for most projects but I have never used to send multiple files and that bothering me now.
Thanks!
Try utilizing json to upload , process file object
html
<div id="drop" class="drop-area ui-widget-header">
<div class="drop-area-label">Drop image here</div>
</div>
<br />
<form id="upload">
<input type="file" name="file" id="file" multiple="true" accepts="image/*" />
<ul class="gallery-image-list" id="uploads">
<!-- The file uploads will be shown here -->
</ul>
</form>
<div id="listTable"></div>
css
#uploads {
display:block;
position:relative;
}
#uploads li {
list-style:none;
}
#drop {
width: 90%;
height: 100px;
padding: 0.5em;
float: left;
margin: 10px;
border: 8px dotted grey;
}
#drop.hover {
border: 8px dotted green;
}
#drop.err {
border: 8px dotted orangered;
}
js
var display = $("#uploads"); // cache `#uploads`, `this` at `$.ajax()`
var droppable = $("#drop")[0]; // cache `#drop` selector
$.ajaxSetup({
context: display,
contentType: "application/json",
dataType: "json",
beforeSend: function (jqxhr, settings) {
// pre-process `file`
var file = JSON.parse(
decodeURIComponent(settings.data.split(/=/)[1])
);
// add `progress` element for each `file`
var progress = $("<progress />", {
"class": "file-" + (!!$("progress").length
? $("progress").length
: "0"),
"min": 0,
"max": 0,
"value": 0,
"data-name": file.name
});
this.append(progress, file.name + "<br />");
jqxhr.name = progress.attr("class");
}
});
var processFiles = function processFiles(event) {
event.preventDefault();
// process `input[type=file]`, `droppable` `file`
var files = event.target.files || event.dataTransfer.files;
var images = $.map(files, function (file, i) {
var reader = new FileReader();
var dfd = new $.Deferred();
reader.onload = function (e) {
dfd.resolveWith(file, [e.target.result])
};
reader.readAsDataURL(new Blob([file], {
"type": file.type
}));
return dfd.then(function (data) {
return $.ajax({
type: "POST",
url: "/echo/json/",
data: {
"file": JSON.stringify({
"file": data,
"name": this.name,
"size": this.size,
"type": this.type
})
},
xhr: function () {
// do `progress` event stuff
var uploads = this.context;
var progress = this.context.find("progress:last");
var xhrUpload = $.ajaxSettings.xhr();
if (xhrUpload.upload) {
xhrUpload.upload.onprogress = function (evt) {
progress.attr({
"max": evt.total,
"value": evt.loaded
})
};
xhrUpload.upload.onloadend = function (evt) {
var progressData = progress.eq(-1);
console.log(progressData.data("name")
+ " upload complete...");
var img = new Image;
$(img).addClass(progressData.eq(-1)
.attr("class"));
img.onload = function () {
if (this.complete) {
console.log(
progressData.data("name")
+ " preview loading..."
);
};
};
uploads.append("<br /><li>", img, "</li><br />");
};
}
return xhrUpload;
}
})
.then(function (data, textStatus, jqxhr) {
console.log(data)
this.find("img[class=" + jqxhr.name + "]")
.attr("src", data.file)
.before("<span>" + data.name + "</span><br />");
return data
}, function (jqxhr, textStatus, errorThrown) {
console.log(errorThrown);
return errorThrown
});
})
});
$.when.apply(display, images).then(function () {
var result = $.makeArray(arguments);
console.log(result.length, "uploads complete");
}, function err(jqxhr, textStatus, errorThrown) {
console.log(jqxhr, textStatus, errorThrown)
})
};
$(document)
.on("change", "input[name^=file]", processFiles);
// process `droppable` events
droppable.ondragover = function () {
$(this).addClass("hover");
return false;
};
droppable.ondragend = function () {
$(this).removeClass("hover")
return false;
};
droppable.ondrop = function (e) {
$(this).removeClass("hover");
var image = Array.prototype.slice.call(e.dataTransfer.files)
.every(function (img, i) {
return /^image/.test(img.type)
});
e.preventDefault();
// if `file`, file type `image` , process `file`
if (!!e.dataTransfer.files.length && image) {
$(this).find(".drop-area-label")
.css("color", "blue")
.html(function (i, html) {
$(this).delay(3000, "msg").queue("msg", function () {
$(this).css("color", "initial").html(html)
}).dequeue("msg");
return "File dropped, processing file upload...";
});
processFiles(e);
} else {
// if dropped `file` _not_ `image`
$(this)
.removeClass("hover")
.addClass("err")
.find(".drop-area-label")
.css("color", "darkred")
.html(function (i, html) {
$(this).delay(3000, "msg").queue("msg", function () {
$(this).css("color", "initial").html(html)
.parent("#drop").removeClass("err")
}).dequeue("msg");
return "Please drop image file...";
});
};
};
php
<?php
if (isset($_POST["file"])) {
// do php stuff
// call `json_encode` on `file` object
$file = json_encode($_POST["file"]);
// return `file` as `json` string
echo $file;
};
jsfiddle http://jsfiddle.net/guest271314/0hm09yqo/

Working on dynamically added input elements with Typeahead

This is my code in adding rows which also have the class='form-control mybur':
$("body").on("click", "#add_row_bur", function() {
$("#bur" + o).html("<td><input type='text' name='bur_account_code[]' placeholder='Account Code' class='form-control mybur' data-provide='typeahead' id='account_code" + o + "' required/><td>;
$("#tab_logic_bur").append('<tr id="bur' + (o + 1) + '"></tr>');
o++
});
$("body").on("click", "#delete_row_bur", function() {
if (o > 1) {
$("#bur" + (o - 1)).html("");
o--
}
});
I tried implementing typeahead on it but it doesn't work. I tried using this answers ( answer 1, answer 2), but still fails.
Here's my code:
var objects = [];
var map = {};
$('input.mybur').typeahead({
source: function(query, process) {
$.ajax({
url: 'proc_php/get_account_code.php',
type: 'POST',
dataType: 'JSON',
async: true,
success: function(data) {
objects = [];
map = {};
$.each(data, function(i, object) {
map[object.description] = object;
objects.push(object.description);
});
process(objects);
}
});
},
updater: function(item) {
$('input.mybur').blur(function() {
$(this).val(map[item].code);
});
return item;
}
});
I deleted all the code that I tried. Again, this will work on a pre-created elements:
<input type="text" name='bur_account_code[]' placeholder='Account Code' class="form-control mybur" data-provide="typeahead" required/>
The problem is for the dynamically added input elements, you need to initialize the plugin after they are created.
So one solution is first create a method which can be reused to initialize the plugin for a passed set of elements like
var objects = [];
var map = {};
function createTypeahead($els) {
$els.typeahead({
source: function (query, process) {
$.ajax({
url: 'proc_php/get_account_code.php',
type: 'POST',
dataType: 'JSON',
async: true,
success: function (data) {
objects = [];
map = {};
$.each(data, function (i, object) {
map[object.description] = object;
objects.push(object.description);
});
process(objects);
}
});
},
updater: function (item) {
$('input.mybur').blur(function () {
$(this).val(map[item].code);
});
return item;
}
});
}
//for the already present elements
createTypeahead($('input.mybur'));
then in the add new element code
$("body").on("click", "#add_row_bur", function() {
var $td = $("<td><input type='text' name='bur_account_code[]' placeholder='Account Code' class='form-control mybur' data-provide='typeahead' id='account_code" + o + "' required/><td>")
$("#bur" + o).html($td);
$("#tab_logic_bur").append('<tr id="bur' + (o + 1) + '"></tr>');
o++
createTypeahead($td.find('input.mybur'));
});
$("body").on("click", "#delete_row_bur", function() {
if (o > 1) {
$("#bur" + (o - 1)).html("");
o--
}
});

jquery ajax not populating the drop down on first call

I have an input text box which fires each time when the user enters data and fills the input text.I'm using bootstrap typehead. Problem is when i enter a letter a it does fire ajax jquery call and fetch the data but the input text box is not populated.Now when another letter aw is entered the data fetched against letter a is filled in the text area.
I have hosted the code here http://hakunalabs.appspot.com/chartPage
Ok so here is part of my html code
<script type="text/javascript">
$(document).ready(function () {
$('#txt').keyup(function () {
delay(function () {
CallData();
}, 1000);
});
});
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
</script>
<input type="text" id="txt" runat="server" class="span4 typeahead local remote" placeholder="Search..." />
And here is my javascript code
var DataProvider;
function CallData() {
DataProvider = [];
var vdata = $('#txt').val();
if (vdata != "") {
var urlt = "http://examples/search?keyword=" + vdata + "&callback=my_callback";
$.ajax({
type: "GET",
url: urlt,
jsonpCallback: "my_callback",
dataType: "jsonp",
async: false,
error: function (xhr, errorType, exception) {
var errorMessage = exception || xhr.statusText;
alert("Excep:: " + exception + "Status:: " + xhr.statusText);
}
});
}
}
function my_callback(data) {
var NameArray = new Array();
var descArray = new Array();
for (var i = 0; i < data.count; i++) {
NameArray.push(data.response[i].days_till_close + " Days Left | " + data.response[i].name + " | " + data.response[i].description);
}
for (var i = 0; i < data.count; i++) {
descArray.push(data.response[i].description);
}
DataProvider = [];
for (var i = 0; i < data.count; i++) {
var dataObject = { id: i + 1, name: NameArray[i], description: descArray[i] };
DataProvider.push(dataObject);
}
var vdata = $('#txt').val();
var urlp = "http://example.com/v1/members/search?keyword=" + vdata + "&my_callbackMember";
$.ajax({
type: "GET",
url: urlp,
jsonpCallback: "my_callbackMember",
dataType: "jsonp",
error: function (xhr, errorType, exception) {
var errorMessage = exception || xhr.statusText;
alert("Excep:: " + exception + "Status:: " + xhr.statusText);
}
});
}
function my_callbackMember(data) {
var memberArray = new Array();
for (var i = 0; i < data.count; i++) {
memberArray.push(data.response[i].name);
}
for (var i = 0; i < data.count; i++) {
var dataObject = { id: i + 1, name: memberArray[i] };
DataProvider.push(dataObject);
}
localStorage.setItem("name", JSON.stringify(DataProvider));
var sources = [
{ name: "local", type: "localStorage", key: "name", display: "country" }
];
$('input.typeahead.local.remote').typeahead({
sources: [{ name: "", type: "localStorage", key: "name", display: "name"}],
itemSelected: function (obj) { alert(obj); }
});
}
Your issue is that typeahead can only present to you the results that are already in localstorage at the moment when you do a key press. Because your results are fetched via AJAX, they only show up in localstorage a second or so AFTER you've pressed the key. Therefore, you will always see the results of the last successful ajax requests in your typeahead results.
Read the bootstrap documentation for type aheads http://twitter.github.com/bootstrap/javascript.html#typeahead and read the section about "source". You can define a "process" callback via the arguments passed to your source function for asynchronous data sources.

Categories