jQuery - post single files with loop from input multiple - php

I need to post with jQuery files from a multiform form.
The problem is I don't know how to send each file individually with a foreach loop, so I can get upload success from each file separately.
Here's my function to send each file to PHP:
var fileInput = document.getElementById ("images_upload_new_album");
if ('files' in fileInput) {
//console.log(fileInput.files);
$.each(fileInput.files, function(index, val) {
/* iterate through array or object */
console.log(fileInput.files[index]);
$.ajax({
url: config.site + "admin/photos/upload_test",
type: 'POST',
data: {file: fileInput.files[index].name},
dataType: 'json',
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
beforeSend: function (data) {
console.log("Before send.");
//console.log(data);
}, // AJAX request is about to be sent
complete: function (data) {
console.log("Complete.");
//console.log(data);
}, // AJAX request has completed
success: function(data, textStatus, jqXHR) // AJAX request has completed successfully
{
console.log("success.");
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) // AJAX request has completed with errors
{
console.log("error.");
}
});
});
};
And my PHP test function.
public function upload_test()
{
$received = $_FILES;
echo json_encode($received);
}
What I get from console:
File {webkitRelativePath: "", lastModified: 1418160606000, lastModifiedDate: Tue Dec 09 2014 20:30:06 GMT-0100 (Hora padrão dos Açores), name: "100371.jpg", type: "image/jpeg"…}
Before send.
Modal it's opened
success.
[]
Complete.
This is my multiform:
<form action="http://xxxxxxx.dev/admin/photos/upload" id="upload_form" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="file" name="images_upload_new_album[]" value="" id="images_upload_new_album" class="hidden_images_upload" style="visibility: hidden; width: 0px; height: 0px" multiple="multiple" accept=".jpg" />
</form>

I solved the problem by recreating the POST loop:
$('#new-album-modal').on('show.bs.modal', function (e) {
// Runs after show modal event is fired
var fileInput = document.getElementById ("images_upload_new_album");
if ('files' in fileInput) {
jQuery.each($('#images_upload_new_album')[0].files, function(i, file) {
var data = new FormData();
data.append('fileinput', file);
$.ajax({
url: config.site + "admin/photos/upload_test",
type: 'POST',
data: data,
dataType: 'json',
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
beforeSend: function (data) {
console.log("Before send.");
//console.log(data);
}, // AJAX request is about to be sent
complete: function (data) {
console.log("Complete.");
//console.log(data);
}, // AJAX request has completed
success: function(data, textStatus, jqXHR) // AJAX request has completed successfully
{
console.log("success.");
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) // AJAX request has completed with errors
{
console.log("error.");
}
});
});
};
});
This problem was solved based on this post: http://stackoverflow.com/questions/5392344/sending-multipart-formdata-with-jquery-ajax

Related

Ajax getting 400 Bad Request when submitting Form only on Firefox

I have written a php code in wordpress to submit a form using ajax. It working fine on chrome but getting 400 Bad request on Firefox. This is my code:
jQuery(document).ready(function($){
jQuery( 'form[name="contact-me"]' ).on( 'submit', function(e) {
e.preventDefault();
var form_data = {};
$(this).serializeArray().forEach( function(element){
form_data[element.name] = element.value;
});
$.post(zt_send_form_obj.ajax_url, {
action: "zt_save_campain_form_data",
_ajax_nonce: zt_send_form_obj.nonce,
type: "POST",
contentType: 'application/json; charset=utf-8',
values: JSON.stringify(form_data),
}, function(data) {
if (data.success) {
if(data.data.info.message=='no'){
$('#myModal').show();
console.log('cod is in')
}
if(data.data.info.message=='yes'){
$('#CodeModal').show();
$('.the_cod_div').append('<span>'+data.data.info.code+'</span>');
console.log('data saved');
}
}
else{
console.log("not working");
}
});
});
});
Try this
$('form[name="contact-me"]').submit(function (e) {
e.preventDefault();
var form = $('#form_id')[0]; //set form id
var varform = new FormData(form);
varform.append("action", "zt_save_campain_form_data");
$.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: varform,
processData: false,
contentType: false,
cache: false,
crossDomain: true,
success: function (response) {
//if success do this...
console.log(response);
},
error: function (xhr, textStatus, error) {
console.log(xhr, textStatus, error);
}
})
});
Inside your form you can put this code for nonce validation
<?php wp_nonce_field( 'name_of_my_action', 'name_of_nonce_field' ); ?>

CodeIgniter Upload File Ajax not working

No matter what I do I can't seem to get a file to upload via AJAX to CodeIgniter method. It always throws and never sees an uploaded file.
HTML
<div>
<h1>Upload Your Translation</h1>
</div>
<form method="POST" class="myForm" enctype="multipart/form-data">
<!-- add your span and pther stuff here-->
<input type="file" id="foto1" name="userfile" />
<input type="button" value="submit" onclick="submitFile();" />
</form>
<script>
function submitFile(){
var formUrl = "/system_administration/AJAX_upload_translation";
var formData = new FormData($('.myForm')[0]);
$.ajax({
url: formUrl,
type: 'POST',
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(data, textSatus, jqXHR){
//now get here response returned by PHP in JSON fomat you can parse it using JSON.parse(data)
},
error: function(jqXHR, textStatus, errorThrown){
//handle here error returned
}
});
}
</script>
PAYLOAD
Request Method:POST
Status Code:200 OK
------WebKitFormBoundaryvkN2BT8ZDxXmKj7Y
Content-Disposition: form-data; name="userfile"; filename="clippy-windows-8-10.jpg"
Content-Type: image/jpeg
function AJAX_upload_translation()
{
if (!isset($_FILES['userfile']['error']) || is_array($_FILES['userfile']['error']))
{
throw new RuntimeException('Invalid parameters.');
}
}
Try this code..
$('#upload').on('click', function() {
var file_data = $('#foto1').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'your_upload_php_file', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
Set form action path and use this for ajax(better not to use onclick function)
$(document).on("submit", ".myForm", function(event)
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),//set form action url at your form
type: $(this).attr("method"),//set form method at your form
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});

How to get the form file field in jquery to upload image

I have below html
This form allows you to upload a file to the server.<br>
<div class="imguploadpath" style="width:100%;height:200px;background-color:#CCC;">
<form name="myFormName" id ="myFormId" action="" method="post">
<input type="file" name="img" id = "image_pe">
<br/><br/><br/><br/>
<input id="cmdSubmit" value="Submit" type="submit" class="">
</form>
</div>
I am trying to get the file field values to upload the file in php using below script
jQuery( "#cmdSubmit" ).on( "click", function() {
var file = jQuery('#image_pe').val();
//i have to send file property to php file in jquery ajax
$.ajax({
url: 'submit.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
return false;
});
but var file only return some temp path c://fakepath/image.jpg
how do upload in jquery and php, I need to pass the form field in php file, I know value() jquery function is wrong.
what is the correct way to do it ?
for php file upload i was thinking of using this script http://www.tizag.com/phpT/fileupload.php
Try this:
JQuery:
var formdata = new FormData();
jQuery.each($('#image_pe')[0].files, function(i, file) {
formdata.append('image_pe', file);
});
$.ajax({
url: "/my.php",
data : formdata,
dataType : "json",
type : "post",
cache: false,
contentType: false,
processData: false,
success: function(data){
},
failure: function(){
$(this).addClass("error");
}
});
return false;
PHP Code:
$file = $_FILES['image_pe'];
Check this. This is might be very helpful for you
http://malsup.com/jquery/form/#file-upload

Upload file via ajax jquery php api

I am having the code with the below format.
PHP file :
<form action="http://clientwebapi.com/createEvent" id="form_createEvent" method="post" enctype="multipart/form-data">
<input type="text" name="image_title" />
<input type="file" name="media" accept="image/*,video/*"/>
</form>
JQUERY file:
$('#form_createEvent').submit(function () {
var form = $(this);
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
xhrFields: {
withCredentials: true
},
data: form.serialize()
}).done(function () {
showCurrentLocation();
alert('Event created successfully..');
location.reload();
}).fail(function () {
alert("fail!");
});
event.preventDefault();
});
The above Jquery code is submitting. Also While I am submitting the below format, It will redirect to the "http://clientwebapi.com/createEvent" and Event created successfully.
Form Submit and redirect to client page:
$('#form_createEvent').submit(function () {
var fd = new FormData();
fd.append('media', input.files[0]);
$.ajax({
url: form.attr("action"),
data: fd,
processData: false,
contentType: false,
type: form.attr("method"),
success: function (data) {
alert(data);
}
});
event.preventDefault();
});
Here How can I prevent while submit the form and create the event with the given image. Kindly help
You forgot to add event as argument to the submit function:
$('#form_createEvent').submit(function (event) {
I found the Answer for this. I made some mistake here. I resolved by using the below code..
$('#form_createEvent').submit(function() {
var form = new FormData($(this)[0]);
$.ajax({
url: 'http://clientwebapi.com/createEvent/',
type: 'POST',
xhrFields: {
withCredentials: true
},
async: false,
cache: false,
contentType: false,
processData: false,
data: form,
beforeSend: function () {
$("#output_process").html("Uploading, please wait....");
},
success: function () {
$("#output_process").html("Upload success.");
},
complete: function () {
$("#output_process").html("upload complete.");
},
error: function () {
//alert("ERROR in upload");
location.reload();
}
}).done(function() {
alert('Event created successfully..');
}).fail(function() {
alert("fail!");
});
event.preventDefault();
});
you can stop the form submission by return false;
$('#form_createEvent').submit(function () {
// some code
$.ajax({
// some code/objects
});
return false; // here, it will stop the form to be post to the url/action
});

jQuery posting to an external php file not working

I am not sure why but the post to my external PHP file is not working. The post request is not being received by the PHP file as nothing is being outputted.
Here's my jQUery;
$.post("AJAX/get_track_info.php", { url: "uploads/19c9aa51c821952c81be46ca9b2e9056.mp3"}, function(info){
$('#loadInfo').html(info);
});
And in the PHP file is just a
$trackurl = $_POST['url'];
Try something more like this
$.ajax({
type: 'POST',
url: 'AJAX/get_track_info.php',
data: { url: "uploads/19c9aa51c821952c81be46ca9b2e9056.mp3" },
dataType: 'text',
success: function (data, textStatus, jqXHR) { },
error: function (data, textStatus, errorThrown) { }
});

Categories