JQuery ajaxfileupload with codeigniter - javascript

Good morning.
I wanna ask about JQuery ajax fileUpload. I have some issues regarding this.
I want to pass some variable from javascript function
Insert the variables and value from uploading file through jquery ajax
Here are the javascript function :
var baseurl = 'http://fadli.com/';
function upload_item(kode,field,table)
{
$("#upload_item_"+table+"_"+kode).hide(); //hide submit button
$("#loading_image_upload_"+table+"_"+kode).show(); //show loading image
console.log('masuk ke fungsi upload');
$.ajaxFileUpload({
url : baseurl+"admin/level/upload_item/"+kode+"/"+field+"/"+table,
//url :'./admin/level/upload_file/',
secureuri : false,
fileElementId :'userfile_'+table+'_'+field+'_'+kode,
dataType : 'json',
data : {
'title' : $('#sub_modul_title_'+kode).val()
},
success : function (data, status)
{
if(data.status != 'error')
{
// $('#files').html('<p>Reloading files...</p>');
// refresh_files();
// $('#title').val('');
alert('sukses brow');
$("#upload_item_"+table+"_"+kode).show(); //show submit button
$("#loading_image_upload_"+table+"_"+kode).hide(); //hide loading image
}
console.log(data.msg);
},
error:function (xhr, ajaxOptions, thrownError){
console.log(thrownError);
$("#upload_item_"+table+"_"+kode).show(); //show submit button
$("#loading_image_upload_"+table+"_"+kode).hide(); //hide loading image
}
});
return false;
}
And here is the HTML code :
<input type="file" name="userfile" id="userfile_sub_modul_sub_modul_id_<?php echo $sub->sub_modul_id?>" class="styled-finputs">
<button class="btn btn-labeled btn-success btn-xs" type="button" id="upload_item_sub_modul_<?php echo $sub->sub_modul_id; ?>" onclick="upload_item('<?php echo $sub->sub_modul_id?>','sub_modul_id','sub_modul')"><span class="btn-label icon fa fa-picture-o"></span> Upload gambar</button>
<img src="http://fadli.com/assets/img/input-spinner.gif" id="loading_image_upload_sub_modul_<?php echo $sub->sub_modul_id?>" style="display:none" />
The problem is after the first console log, it's not working all way down.
Any help would be appreciate.
Thanks

For ajaxFileUpload, it is starting with capital A, try to change ajaxFileUpload to AjaxFileUpload

You can simply submit the form with ajax(without page reload).
Just use this code.It will submit your files data too.
$(document).on("submit", "form", function(event)//I wrote it for any form.You can change it for specific form
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),//make sure your form has action url
type: $(this).attr("method"),//Your form method type GET OR POST
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
Also you can add addition data with FormData. https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
You can modify the above function like this
$(document).on("submit", "form", function(event)
{
var formData = new FormData(this);
formData.append("MORE_INPUT_KEY", "MORE_DATA");
event.preventDefault();
$.ajax({
url: $(this).attr("action"),//set any link
type: $(this).attr("method"),//set any metho
dataType: "JSON",
data: formData ,
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});

Related

Validation form with ajax

This is my submit form code. I want when clicking submit it will be validation form first before it is saved to the database. How can i make script validation form with ajax in function script bellow?
<script>
function simpan_data() {
var url;
save_method == 'add';
url = "<?php echo base_url();?>jurusan/getInsert";
// ajax adding data to database
$.ajax({
url: url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data) {
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
swal({
title: "Data telah disimpan",
type: "success",
timer: 1000,
showConfirmButton: false,
},
function() {
location.reload();
}
);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error adding / update data');
}
});
}
</script>

Prestashop: Delete user uploaded file via AJAX instead of reloading page

The default way a user uploaded image displays, shows a small black X that looks like this (to delete the image):
<a href="path/to/yourproduct?deletePicture=1" title="Delete" >
When the user clicks that button, the page 'reloads' and the users uploaded file is deleted.
I can't figure out where the code is that is deleting that file - so I figured maybe AJAX would be a better way to go about it. Plus, just in case the user had entered information on the page, they wouldn't have to reenter it.
I changed the little black X to this:
<a id="deletePictureTrigger" href="javascript:void(0)" title="Delete" >
I also added this in product.js:
$('#deletePictureTrigger').click(function(e){
alert('now it deletes');
});
This works and an alert pops up.
What would be the best way for this to continue?
Would it be something like this? :
$('#deletePictureTrigger').click(function(e){
alert('now it deletes');
$.ajax({
url: "path/to/product?deleteProduct=1",
type: 'GET',
cache: false,
dataType: 'json',
processData: false,
contentType: false,
//enable for saving on 'add to cart'
//async: true,
success: function(data, textStatus, jqXHR)
{
alert ("Deleted");
$('.customizationUploadBrowse').remove();
},
error: function(jqXHR, textStatus, errorThrown)
{
alert ("there was an error:"+errorThrown);
// ***** THIS GETS AN ERROR ***** //
}
});
});
Where is the method deletePicture that is getting called when that page is requested?
I'd like to automate this so the ajax deletes it without reloading the page.
I had to make some changes to my ajax call like this:
$('body').on('click', '#deletePictureTrigger', function(event){
event.preventDefault();
var data = new FormData();
data.append('ajax', 1);
$.ajax({
url: window.location.href+"?deletePicture=1",
type: 'GET',
data: data,
cache: false,
//dataType: 'json',
processData: false,
contentType: false,
//enable for saving on 'add to cart'
//async: true,
success: function(data, textStatus, jqXHR)
{
$('#preview-img0').remove();
$('#customImages').remove();
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log( jqXHR);
alert ("there was an error:"+errorThrown);
}
});
});

upload an image with other parameters as JSON type using javascript

I have an object that contains parameters . I want to upload an image to a server but just using javascript.
how can I do that?
<input id="imgItem" type="file" class="form-control">
<input type="text" id="title">
<input type="text" id="description">
<button onclick="handle();">
<script>
function handle(){
var params={
title:document.getElementById('title').value,
desc: document.getElementById('description').value,
img://i don't know what I must do,
};
postItem(params, function(data){
alert(JSON.stringify(data));
});
}
function postItem(param, callbackFunction){
$.ajax({
url:myUrl,
data:param,
type:'POST',
contentType:'application/x-www-form-urlencoded',
xhrFields:{withCredentials: false},
success: function(response){
callbackFunction(response);
}
});
}
</script>
You can use FormData
var data = new FormData();
data.append('title', document.getElementById('title').value);
data.append('desc', document.getElementById('description').value);
$("input[type='file']").each(function (index) {
try {
data.append($(this).attr('name'), $(this)[0].files[0], $(this).attr('name'));
} catch (ignore) {}
});
$.ajax({
method: 'POST',
url: url,
data: data,
cache: false,
contentType: false,
processData: false
}).done(function () {
//your code here
}).fail(function (xhr, status, error) {
//your code here
}).always(function () {
//your code here
});
Or use it as regular form submission and fill in title and description values in submit event.

jQuery Submit Form (w/ file and text) without redirecting from current window

I want to build an application form where on can attach an image - it's just a couple of input elements - within a div (not an form element). The form shall be processed without an page redirect. So I use ajax. Everything works fine so far. But now I need to add an image.
$('#submit_application').click(function () {
//...
$.ajax({
url: 'submit.php',
type: 'post',
data: {
'action': 'submit',
'image': $('#image_upload').val(),
// ..
'someStringifiedJSON': JSON.stringify(foo)
},
success: function (data, status) {
// ...
},
error: function (xhr, desc, err) {
// ...
}
});
});
How can I get my file into php's $_FILES variable? Or how can I pass the file to php so that I can upload it?
you can send files using formData.
var file = $('#image_upload')[0].files[0];
var fData = new FormData();
fData.append('action', 'submit');
fData.append('image', file);
fData.append('someStringifiedJSON', JSON.stringify(foo));
and your ajax request will be:
$.ajax({
url: 'submit.php',
type: 'post',
data: fData ,
contentType: false,
processData: false,
success: function (data, status) {
// ...
},
error: function (xhr, desc, err) {
// ...
}
});
Explanation:
as specefied here.if you set processData to true it will pass it as query string.if you want to send non-processed data set it to false.
default for contentType is application/x-www-form-urlencoded; charset=UTF-8.which won't work for files (because it sends heder like multipart/form-data; boundary=---------------------------125911542220235) when you set it to false browser generate right content-type header automatically
Try this:
$('#submit_application').click(function () {
var formData=new FormData();
formData.append('action','submit');
formData.append('someStringifiedJSON', ''+JSON.stringify(foo));
formData.append($('#image_upload').files[0]);
$.ajax({
url: 'submit.php',
type: 'post',
contentType:false,
data: formData,
success: function (data, status) {
// ...
},
error: function (xhr, desc, err) {
// ...
}
});
});
Make sure to add this contentType:false in ajax request.

jquery submit form and then show results in an existing div

I have a simple one text input form that when submitted, needs to fetch a php file (passing the inputs to the file) and then take the result (just a line of text) and place it in a div and fade that div into view.
Here is what I have now:
<form id=create method=POST action=create.php>
<input type=text name=url>
<input type="submit" value="Create" />
<div id=created></div>
What I need is the results of create.php?url=INPUT, to be dynamically loaded into the div called created.
I have the jquery form script, but I haven't been able to get it to work right. But I do have the library loaded (the file).
This code should do it. You don't need the Form plugin for something as simple as this:
$('#create').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
This works also for file upload
$(document).on("submit", "form", function(event)
{
event.preventDefault();
var url=$(this).attr("action");
$.ajax({
url: url,
type: 'POST',
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
$('#created').html(data); //content loads here
},
error: function (xhr, desc, err)
{
console.log("error");
}
});
});
You must use AJAX to post the form if you don't want the page to be refreshed.
$('#create').submit(function () {
$.post('create.php', $('#create').serialize(), function (data, textStatus) {
$('#created').append(data);
});
return false;
});

Categories

Resources