I'm beginner in OpenCart and I'm trying to upload the file in server using PHP. I have done the following code. My problem is, files are sucessfully uploading in server but if there is some error I'm trying to loading the LoadA() function, but the result is not showing in site instead it is showing in console.log I don't know what is the error.
controller/boxupload/upload.php
public function add()
{
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file))
{
if(success) //files are succesfully uploading
{
//doing stuff
}
if (it is fail)
{
$this->LoadA(); // this is not loading in site. Instead it is showing in console.log
}
}
}
public function LoadA()
{
$data['token'] = $this->session->data['token'];
$this->document->setTitle("!!!!!!!!!!!!Upload failed!!!!!!!!");
$data['add'] = $this->url->link('boxupload/upload/add', 'token=' . $this->session->data['token'], 'SSL');
$data['header'] = $this->load->controller('common/header');
$data['column_left'] = $this->load->controller('common/column_left');
$data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('boxupload/upload.tpl', $data));
}
Then the tpl file for this one
controller/boxupload/upload.tpl
$('#button-upload').on('click', function() {
$('#progress-bar').css('width', '0%');
$('#form-upload').remove();
$('body').prepend('<form enctype="multipart/form-data" id="form-upload" style="display: none;"><input type="file" name="file" /></form>');
$('#form-upload input[name=\'file\']').trigger('click');
if (typeof timer != 'undefined') {
clearInterval(timer);
}
var WID = 30;
timer = setInterval(function() {
if ($('#form-upload input[name=\'file\']').val() != '') {
clearInterval(timer);
// Reset everything
$('.alert').remove();
$('#progress-bar').css('width', '0%');
$('#progress-bar').removeClass('progress-bar-danger progress-bar-success');
$('#progress-text').html('');
$.ajax({
url: '<?php echo "index.php?route=boxupload/upload/add&token=$token"; ?>',
type: 'post',
//dataType: 'json',
data: new FormData($('#form-upload')[0]),
cache: false,
contentType: false,
processData: false,
beforeSend: function() {
$('#button-upload').button('loading');
$('#progress-bar').css('width', '50%');
},
complete: function() {
$('#button-upload').button('reset');
$('#progress-bar').css('width', '100%');
},
success: function()
{ $('#progress-bar').css('width', '80%');
},
});
}
}, 500);
});
Please see the highlighted area in image.
Try this:
dataType: 'html',
success: function(html)
{
$('#progress-bar').css('width', '80%');
$('#your-div').html(html);
},
Your .tpl file should be in a view.
$this->response->setOutput($this->load->view('boxupload/upload.tpl', $data));
loads the file
view/theme/default/template/boxupload/upload.tpl
Also, look at some other template files. They're generally mostly HTML.
Also, you're going to want to refactor your names so they use normal OpenCart naming conventions.
controller/extension/boxupload/upload.php
view/theme/default/template/extension/boxupload/upload.tpl
etc.
Related
I have a C# method that exports a database table and a JS function that starts a download. The JS is this:
function Export()
{
$.ajax({
cache: false,
type: "POST",
url: '#Url.Action("exportDatabaseTable", "MyController")',
data:
{
'type': "xls"
},
dataType: "text",
beforeSend: function () //Display a waiting message
{
$('#wait').show();
},
success: function (result) //Result is "Message|FilePath"
{
var res = result.split('|');
if(res[0]!="Nothing found")
window.location = "DownloadDatabaseTable?fileName=" + res[1];
alert(res[0]);
},
error: function ()
{
alert("Export failed");
},
complete: function () //Hide the waiting message
{
$('#wait').hide();
}
});
}
While the C# one, called in the success function, is this:
[HttpGet]
public ActionResult DownloadDatabaseTable(string fileName)
{
System.IO.FileInfo file = new System.IO.FileInfo(fileName);
byte[] fileBytes = System.IO.File.ReadAllBytes(fileName);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, System.IO.Path.GetFileName(fileName));
}
Everything works, but the download starts automatically. Is there a way to show the download windows and let the user choose to download (and where to download it) or to open the file?
This question already has answers here:
Clearing <input type='file' /> using jQuery
(27 answers)
Closed 7 years ago.
================Edit=====================================================Hello! Thanks so much for everyone who answered and tried to help me. I was able to get what I needed by using iframe as suggested by #Kaiido since my previous code doesn't work in ie8. Thanks to this as well: JQuery file posting using iframe Again. Thanks so much! =======================================================================
I have an upload form. I am able to upload the file on submission. The problem is I am trying to add/append a delete button once the user chooses a file to upload. I need it to look like this:
Goals:
1. When user clicks on Delete button, the filelist should go back to empty.
2. Changing the file should behave like clicking on the Delete button.
3. It needs to work in IE 8. It sucks.
Input Form:
Attachment: <input type="file" name="upload" id="upload">
Submit
JS:
var files;
$('input[type=file]').on('change', prepareUpload);
function prepareUpload(event)
{
files = event.target.files; // I'm not sure but the problem might be on this part. Maybe I could get the opposite of this or negate this?
}
function uploadFiles(event)
{
event.stopPropagation();
event.preventDefault();
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'execs/upload.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(data)
{
console.log('Uploaded');
},
error: function()
{
console.log('Failed');
}
})
}
$("#btnSubmit").click(function(e)
{
uploadFiles(event);
})
Thank you so much for your help!
You need to reset your upload control like this
$(document).ready(function() {
de();
$("#fileU").on("change", function() {
if ($("#fileU").val() != "") {
$("input[type=button]").attr("style", "display:block");
} else {
de();
}
});
$("input[type=button]").click(function() {
$("#fileU").val('');
de();
})
})
function de() {
$("input[type=button]").attr("style", "display:none");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="fileU" multiple/>
<input type="button" value="delete FIle" />
When you select a file, and you want to remove it, you just need to assign '' to your value of upload control.
I've made a fiddle & now working,check this. Hope this helps. I've modified the js as below(commented). By the way, I don't see the Delete button.
var files;
$('#btnSubmit').hide(); // ADDED
$('input[type=file]').change(function(){ // MODIFIED
if(this.value!=''){
prepareUpload();
}else $('#btnSubmit').hide();
});
function prepareUpload(event)
{
$('#btnSubmit').show();
files = event.target.files;
}
function uploadFiles(event)
{
event.stopPropagation();
event.preventDefault();
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'execs/upload.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(data)
{
console.log('Uploaded');
},
error: function()
{
console.log('Failed');
}
})
}
$("#btnSubmit").click(function(e)
{
uploadFiles(event);
})
im having troubles with getting script from another file in jquery.
i've tried with $.getScript and $.ajax();
how can i include one script like require.js in jquery?
util.js
function getSessionInformation () {
$.ajax({
url: '../controller/controller.php',
type: 'POST',
dataType:'JSON',
data: {
action: 'getInfoCompany'
},
})
.done(function(data) {
try{
return data;
}catch(e){
console.log(e);
}
})
.fail(function() {
console.log("error");
});
}
file.js
$(document).ready(function() {
_getAllUsers();
});
function _getAllUsers()
{
jQuery.ajax({
url: "util.js",
dataType: "script",
cache: true
}).done(function() {
alert("im in");
jQuery.cookie("cookie_name", "value", { expires: 7 });
});
}
Try again, the getScript method is the right tool for this:
function _getAllUsers()
{
jQuery.getScript("util.js", function() {
alert("im in");
jQuery.cookie("cookie_name", "value", { expires: 7 });
});
}
Update:
The reason that you get a HTTP 404 error is that the URL that you are using will look for the script in the same folder as the page. You need a ../ to get out of the view folder and a js to get into the script folder:
jQuery.getScript("../js/util.js", function() {
My javascript class contain the following code and i saved it as globalrates.js file
$(function() {
setInterval('rates.set_rates()',1000);
});
rates = {
marketstatus: {
'goldrate': '',
'status': ''
},
set_rates : function() {
var my_Date = new Date();
$.ajax({
type: "GET",
url: "http://localhost:90/appname/rateXml.xml"+"?nocache=" + my_Date.getUTCSeconds(),
dataType: "xml",
cache: false,
success: function(xml) {
try {
var data = $.xml2json(xml);
if(data.trade_type == 3 || data.rate_display ==0){
rates.marketstatus['goldrate'] = "";
rates.marketstatus['status'] = "0";
}else {
rates.marketstatus['goldrate'] = data.goldrate;
rates.marketstatus['status'] = "1";
}
}catch(error){
console.log(error);
}
},
error: function(request,error) {
console.log(error);
}
});
}
}
This js file is my global file and included into my header.php file
and i have another page like goldbuy.php, here i have to get current gold rates from globalrates.js.
so that i have tried following code in buygold.js file
console.log(rates.marketstatus['goldrate']);
But it didn't work, how to use get and set method for javascript class.(class object created as like globalrates.js file)
Hi Im attempting a simple ajax request but I keep getting a null value for json.
Here is my javascript...
<script>
$(document).ready( function() {
$('#donate-box-submit').on('click', function() {
var donate_code = $('#charity-campaign-code').val();
var donate_amount = $('#charity-campaign-amount').val();
$.ajax({
url: 'index.php?route=donate/donatenow',
type: 'post',
data: {
donate_code: donate_code,
donate_amount: donate_amount
},
dataType: 'json',
beforeSend: function() {
},
complete: function() {
},
success: function(json) {
console.log(json);
alert(json['test']);
},
error: function() {
}
});
});
});
</script>
and my php...
public function donatenow() {
$json = array(
'test' => 'Output this text'
);
$this->response->setOutput(json_encode($json));
}
I have also tried echo json_encode($json); just to rule out any issues with that OpenCart function, but the same issue is still there.
The problem is the route you are using to call the method. Not sure on exactly what class you are using as the controller, but there should be three parts to the route: route=aaa/bbb/donatenow where as you've got aaa/donatenow