File not reaching till handler's method - javascript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
$(document).ready(function () {
$("#Button1").click(function (evt) {
var fileUpload = $('[id$=FileUpload1]')[0].value.split(",");
var data = new FormData();
for (var i = 0; i < fileUpload.length; i++) {
data.append(fileUpload[i].name, fileUpload[i]);
}
var options = {};
options.url = "Handler.ashx";
options.type = "POST";
options.data = data;
options.contentType = false;
options.processData = false;
options.success = function (result) { alert(result); };
options.error = function (err) { alert(err.statusText); };
$.ajax(options);
evt.preventDefault();
});
});
This was my jquery and below is my handler file code ......
till end i am getting value while debugging but in motto of making upload multiple images at a while i am unable to have any value in handle
handler code
public void ProcessRequest (HttpContext context) {
string filePath = "FileSave//";
foreach (string file in context.Request.Files)
{
HttpPostedFile filed = context.Request.Files[file];
filed.SaveAs(context.Server.MapPath(filePath + filed.FileName));
context.Response.Write("File uploaded");
}
}

You can try this way if you would like to.
$(document).ready(function () {
$("#Button1").click(function (evt) {
evt.preventDefault();
var formdata = new FormData();
var fileInput = $('#sliderFile'); //#sliderFile is the id of your file upload control
if ($(fileInput).get(0).files.length == 0)
{ //show error
return false;
}
else
{
$.each($(fileInput).get(0).files, function (index,value) {
formdata.append(value.name, value);
});
$.ajax({
url: 'Handler.ashx',
type: "POST",
dataType: 'json',
data: data,
processData: false,
contentType:false,
success: function (data) {
if (data.result) {
//return true or any thing you want to do here
}
else {
//return false and display error
}
},
error: function (data) {
//return false and display error
}
});
}
});//button click close
});//document.ready close
Try it and let me know
EDIT: Remember but, HTML5 FormData is not available in older browsers and your code will silently fail. If you need to support older browsers you might need to perform progressive enhancement by testing the capabilities of the browser and falling back to a standard form POST if the browser doesn't support FormData:
if(window.FormData === undefined) {
// The browser doesn't support uploading files with AJAX
// falling back to standard form upload
} else {
// The browser supports uploading files with AJAX =>
// we prevent the default form POST and use AJAX instead
e.preventDefault();
...
}
For more information on this you can see answer I have accepted for one of my questions. It's pretty much clear there what is the issue regarding. Here is the link
EDIT : Just adding these LINK1 and LINK2 for those who come looking for the answer.

use HttpContextBase[] instead of just HttpContext

Related

When submitting an ajax request, how can you "put the original request on hold" temporarily until a condition is met?

I am wanting to implement a recaptcha process that captures all ajax requests before they go through - the desired process would be as follows:
User completes an action which is going to cause an ajax request of some sort.
If the user has already completed the recaptcha process, the ajax request proceeds without further delay
If the user has not completed the recaptcha process, put the ajax request "on hold" temporarily until the recaptcha process is completed, then continue the ajax request.
I have got things to a state where I intercept the call, however I don't know how to put it on hold temporarily. Here's the relevant code:
<script>
var captchaValidated = null;
var currentRequests = [];
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (options.url != "/ValidateCaptcha") {
if (captchaValidated == null || captchaValidated == false) {
if (captchaValidated == null){
openRecaptcha();
} else {
verifyCaptcha(); //see async question in method
}
if (!captchaValidated) {
jqXHR.abort();
} else {
//let the original request proceed now - but how?!
}
}
}
});
function verifyCaptcha() {
var grecaptcha = $("g-recaptcha-response");
var encodedResponse;
if (grecaptcha != null) {
encodedResponse = grecaptcha.val();
$.ajax({
async: false, //set to false so that the calling method completes rather than async - what do you think?
headers: headers,
cache: false,
url: "/ValidateCaptcha",
type: 'POST',
contentType: 'application/json',
success: function (data) {
//parse the data - did we get back true?
captchaValidated = data;
},
error: function (raw, textStatus, errorThrown) { captchaValidated = null; alert("Validate ReCaptcha Error: " + JSON.stringify(raw)); },
data: JSON.stringify({ "encodedResponse": encodedResponse })
});
}
}
function invalidateCaptcha(){
captchaValidated = null;
}
function openRecaptcha() {
grecaptcha.render('recaptcha', {
'sitekey': "thekey",
'callback': verifyCaptcha,
'expired-callback': invalidateCaptcha,
'type': 'audio image'
});
$("#recaptchaModal").modal('show');
}
</script>
Any suggestions of how to proceed would be appreciated, thanks in advance!
Thank you #Loading and #guest271314 for your help in pointing me in the right direction that helped me get things figured out. I've pasted how I accomplished it below - perhaps it will be of help to someone else. Of course if anyone would like to weigh in on my implementation please do.
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCaptcha&render=explicit&hl=en" async defer></script>
<script>
var captchaValidated = null;
var currentRequests = [];
var captchaPrompted = false;
var captchaReady = false;
var resetCaptcha = false;
function onloadCaptcha() {
captchaReady = true;
captcha = grecaptcha.render('recaptcha', {
'sitekey': '<yoursitekey>',
'callback': verifyCaptcha,
'expired-callback': invalidateCaptcha,
'type': 'audio image'
});
}
var deferredCaptcha = null;
var promiseCaptcha = null;
var captcha = null;
function openRecaptcha() {
if (!captchaReady) {
setTimeout(openRecaptcha, 50);
}
if (captchaPrompted) {
return;
}
captchaPrompted = true;
var captchaTimer = setInterval(function () {
if (captchaValidated != null) {
if (captchaValidated) {
deferredCaptcha.resolve();
} else {
deferredCaptcha.reject();
captchaValidated = null;
}
}
}, 100);
if (resetCaptcha) {
captcha.reset();
}
deferredCaptcha = $.Deferred();
promiseCaptcha = deferredCaptcha.promise();
promiseCaptcha.done(function () {
//captcha was successful
clearInterval(captchaTimer);
//process the queue if there's items to go through
if (currentRequests.length > 0) {
for (var i = 0; i < currentRequests.length; i++) {
//re-request the item
$.ajax(currentRequests[i]);
}
}
});
promiseCaptcha.fail(function () {
//captcha failed
clearInterval(captchaTimer);
currentRequests = []; //clear the queue
});
$("#recaptchaModal").modal('show');
}
function verifyCaptcha() {
resetCaptcha = true;
var response = $("#g-recaptcha-response").val();
var encodedResponse;
// confirm its validity at the server end
$.ajax({
headers: headers,
cache: false,
url: "/ValidateCaptcha",
type: 'POST',
contentType: 'application/json',
success: function (data) {
captchaValidated = data;
if (!data) {
captchaPrompted = false;
}
},
error: function (raw, textStatus, errorThrown) { captchaValidated = false; captchaPrompted = false; alert("WTF Validate ReCaptcha Error?!: " + JSON.stringify(raw)); },
data: JSON.stringify({ "encodedResponse": response })
});
}
function invalidateCaptcha(){
deferredCaptcha.reject();
captchaValidated = null;
resetCaptcha = true;
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (settings.url == '/ValidateCaptcha' || captchaValidated) {
// we're validating the captcha server side now or it's already been validated - let it through
} else {
if (typeof settings.nested === 'undefined'){
settings.nested = true; //this flag is to determine whether it's already in the queue
currentRequests.push(settings); //add the request to the queue to be resubmitted
//prompt them with the captcha
openRecaptcha();
}
return false; // cancel this request
}
}
});
</script>
At $.ajaxPrefilter() use .then() chained to openCaptcha to call verifyCaptcha
if (captchaValidated == null){
openRecaptcha().then(verifyCaptcha);
}
at verifyCaptcha use .is() with parameter "*" to check if an element exists in document
if (grecaptcha.is("*")) {
at openRecaptcha(), if grecaptcha.render does not return asynchronous result return jQuery promise object using .promise(); else chain to grecaptcha.render and $("#recaptchaModal").modal('show'); using $.when()
return $("#recaptchaModal").modal('show').promise()
or
return $.when(grecaptcha.render(/* parameters */)
, $("#recaptchaModal").modal('show').promise())
Something like this? (pseudo-code)
verified = false;
$('#myButton').click(function(){
if (!verified) verify_by_captcha();
if (verified){
$.ajax(function(){
type: 'post',
url: 'path/to/ajax.php',
data: your_data
})
.done(function(recd){
//ajax completed, do what you need to do next
alert(recd);
});
}
});//end myButton.click

$.ajax json GET reverts all jquery after page load

So I have a one page site, that only shows a login with username and password.
I have the $.ajax fire on the submit click.
What I want is for it remove the login box and load in the page that will have all the content ready for the ajax content to go into.
$.ajax function works and was tested by alert(n); the number for my json array.
What happens is after the box disappears and the page loads, it reverts back to the login box.
$(document).ready(function() {
$('#launchform').click(function() {
$.ajax({
url: 'campaign.json',
dataType: 'JSON',
type: 'GET',
success: function (data) {
console.log(data);
var string = JSON.stringify($('form').serializeArray());
var login = JSON.parse(string);
var username = login[0].value;
var password = login[1].value;
var n = '';
for (var i = 0; i < data.result.length; i++){
if (data.result[i].name == username){
if (data.result[i].id == password){
var n = i;
}
}
}
if(n!=='') {
$(".container").remove();
$("#loginfade").load("test.html");
} else {
alert('Invalid Username/Password Combination.');
}
}
});
});
});
This is a pretty common problem. When you bind to a submit event, you are effectively able to run some logic, but unless you stop it, the event will continue to propagate and will also run the normal submit logic, which causes a full page refresh. This is fairly easy to prevent:
$(document).ready(function() {
$('#launchform').on('click', function(e) {
e.preventDefault(); // Add this
});
});
As stated in another answer, you can also return false;. That is sometimes a better way to do it when using jQuery as it effectively cancels everything. Although, in non-jQuery solutions, it doesn't stop the event bubbling. You can read more details about why here: event.preventDefault() vs. return false
If you are performing this within a <form> element then the form is probably submitting after the ajax call and reloading the page. Try adding:
return false;
to the end of the click event function to prevent the form submitting.
So the above code would look like:
$(document).ready(function() {
$('#launchform').click(function() {
$.ajax({
url: 'campaign.json',
dataType: 'JSON',
type: 'GET',
success: function (data) {
console.log(data);
var string = JSON.stringify($('form').serializeArray());
var login = JSON.parse(string);
var username = login[0].value;
var password = login[1].value;
var n = '';
for (var i = 0; i < data.result.length; i++){
if (data.result[i].name == username){
if (data.result[i].id == password){
var n = i;
}
}
}
if(n!=='') {
$(".container").remove();
$("#loginfade").load("test.html");
} else {
alert('Invalid Username/Password Combination.');
}
}
});
return false;
});

How to do Image type validation in magento.?

I am new to magento. I just want to do image validation in magento but i am struggling alot. I used ajax validation but append() function in jquery is not supporting in magento, So i dont know how to do this.
My ajax code:
jQuery(function () {
var url = jQuery('#image_url').val();
var vendorImage = jQuery('#vendor_logo');
vendorImage.on("change", function () {
var fd = new FormData();
var file = jQuery('#vendor_logo')[0].files[0];
if (file) {
fd.append('vendor_logo', file);
}
jQuery.ajax({
url: url,
type: 'POST',
cache: false,
data: fd,
success: function (result) {
alert(0);
alert(result);
jQuery("#output").html("Upload success.");
}
});
});
});
I am getting error for append() function.
I think It would be better if i use add rule in validation.js file
My code here:
Validation.add('validate-imgtype', 'Please choos valid image', function(v) {
var Image = jQuery(v).val();
var extension = Image.split('.').pop().toUpperCase();
if (extension!="PNG" && extension!="JPG" && extension!="GIF" && extension!="JPEG"){
return extension;
}
});
But the above add rule code also not working.
Can anyone help me to resolve this???
Thanks in advance.
If you are asking for image validation in magento you can try doing
if($this->getRequest()->isPost())
{
if(isset($_FILES['myfileupload']['name']) and (file_exists($_FILES['myfileupload']['tmp_name'])))
{
$path = Mage::getBaseDir() . '/myfileupload';
if(!file_exists($path))
{ mkdir($path, 777, true); }
try {
$myfileupload = $_FILES['myfileupload']['name'];
$uploader = new Varien_File_Uploader('myfileupload');
$uploader->setAllowedExtensions(array('png', 'gif', 'jpeg', 'jpg', 'pdf'));
$uploader->setAllowCreateFolders(true);
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$uploader->save($path, $myfileupload);
} catch (Exception $e) {
echo 'Error';
}
}
}

How Do I Send The File Data Without Form With Ajax On Server?

I've coded a javascript code which nicely collects every file user wants to upload. But things turned when I added drag/drop file option.
By default, I had a code which monitored input[type='file'] change event handler and once it was detected, actions were performed and files were sent to server for upload.
But since drag/drop doesn't change the input[type='file'] value and neither I can change it programmatically due to security reasons, I'm struck how do I send files which are dragged and dropped on the site.
Here's some of my code:
document.getElementById('drop').addEventListener('drop', function (e) {
e = e || window.event;
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
for (var i=0; i<files.length; i++) {
var file = files[i];
var reader = new FileReader();
reader.readAsDataURL(file);
addEventHandler(reader, 'loadend', function(e, file) {
var bin = this.result;
var filename = file.name;
var filesize = (file.size/1048576).toFixed(2) + ' MB';
alert(' '+filename+' '+filesize+' '); // DEBUGGING ONLY
console.log("YEAY");
if(filecheck(filename)) { // Additional Function
step2(filesize, filename, bin); // Additional Function
$('.btn').click(function() { // Button to be clicked to start upload
$('#main_img_upload').submit(); // Form with that input[type='file']
});
}
else {
alert("Wrong File");
return false;
}
}.bindToEventHandler(file), false);
}
return false;
});
Obviously, it starts upload but server doesn't receive anything as no change has been made to form. But I have all the necessary details (name of file, size of file, etc..)
Any help would be appreciated.
Try out this code.
data.append("FileName", files[0]);
$.ajax({
url: "../",
type: "POST",
processData: false,
contentType: false,
data: data,
success: function (data) {
if (data) {
}
},
error: function (er) {
MSGBox(er);
}
});
}

Submiting a form via json/ajax/jquery

Here is my code
function generate_clicked()
{
var txt_text_color = $('#txt_text_color').val();
var url='process.php?';
url+='txt_text_color='+encodeURIComponent(txt_text_color);
$.ajax({
url: url,
beforeSend: function ( xhr ) {
xhr.overrideMimeType("application/json; charset=x-user-defined");
}
}).done(function ( data ) {
try{
$('#preview').val(data.css);
$('#my_iframe').srcdoc = data1;
}
catch(err)
{
console.log(err);
}
document.getElementById("my_iframe").src = data.live_preview_html_page;
});
}
This works for my purposes but if I added another form element I would tediousily have to add var example =$('....').val();
and
url+='example'+endcodeU.....
Which I will be having over 100 elements, then I would retreview them on process with
$txt_text_color = $_REQUEST['txt_text_color'];
My question is, how can I serialize this (I think that's what I need to do) so that I don't have to write those two varibles names each time I make a new form object.
I need to save get/post those varibles in process.php to use them.
Sorry if this doesn't make sense, I'm still learning.
Try form.serialize()
http://api.jquery.com/serialize/
Your code would look something like this:
function generate_clicked()
{
var formData = $('#form').serialize();
var url='process.php?';
url+=formData;
$.ajax({
url: url,
beforeSend: function ( xhr ) {
xhr.overrideMimeType("application/json; charset=x-user-defined");
}
}).done(function ( data ) {
try{
$('#preview').val(data.css);
$('#my_iframe').srcdoc = data1;
}
catch(err)
{
console.log(err);
}
document.getElementById("my_iframe").src = data.live_preview_html_page;
});
}

Categories

Resources