I'm trying to submit a single value as following?
HTML:
<form class="form-horizontal" role="form" method="POST" enctype="multipart/form-data" name="frmanalyse" id="frmanalyse">
{{ csrf_field() }}
<label for="marginsource" style="float: left; width:150px; text-align:left;">Margin Source</label>
<input type="file" name="marginsource" id="marginsource" >
<br />
</form>
script:
<script type="text/javascript">
$( "#frmanalyse" ).submit(function(event) {
$.post( "marginanalyser", {username: "medo ampir"}, function( data ) {
alert(data);
});
event.preventDefault();
});
in laravel routes:
Route::post('marginanalyser',function(Request $request){
echo $request->input('username');
$file = $request->file('marginsource');
echo 'File Name: '.$file->getClientOriginalName();
});
nothing shows in the message at all.
Change your JavaScript to use FormData as you aren't submitting the file
$( "#frmanalyse" ).submit(function(event) {
event.preventDefault();
var formData = new FormData();
formData.append('marginsource', $('#marginsource')[0].files[0]);
formData.append('username', "medo ampir");
$.ajax({
url : window.location.origin + "/marginanalyser",
type: "POST",
data : formData,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
processData: false,
contentType: false,
success:function(data, textStatus, jqXHR) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
//if fails
}
});
});
Related
A dropzone js need to create a new form but I want to use the same form to post both data and image, how can I achieve this, any idea.
<form method="POST" enctype="multipart/form-data">
<input type="text" name="name" id="name">
<!-- how to replace this field with dropzone but in this form in order to use the same ajax as below -->
<input type="file" name="photo" id="photo">
<button type="submit">send</button>
</form>
$("form").on('submit', function(e) {
$.ajax({
url: 'add.php',
type: 'POST',
data: new FormData(this),
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
}).done(function(data) {
if (data.success == false) {
if (data.errors.name) {
$('#name').append('<span class="text-danger">' + data.errors.name + '</span>');
}
if (data.errors.photo) {
$('#photo').append('<span class="text-danger">' + data.errors.photo + '</span>');
}
}
});
e.preventDefault();
});
You need to append dropzone files separately to FormData. Here is my solution,
$(document).ready(function () {
// get a reference to photo dropzone
var photoDropzone = Dropzone.forElement('#photo-dropzone');
$("form").submit(function (e) {
e.preventDefault();
// create the complete FormData here
var fd = new FormData(this);
// append dropzone files into the form data
for (var i = 0; i < photoDropzone.files.length; i++) {
fd.append('file[]', photoDropzone.files[i]);
}
$.ajax({
url: 'add.php',
type: 'POST',
data: fd,
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
}).done(function (data) {
console.log('done');
if (data.success == false) {
if (data.errors.name) {
$('#name').append('<span class="text-danger">' + data.errors.name + '</span>');
}
if (data.errors.photo) {
$('#photo').append('<span class="text-danger">' + data.errors.photo + '</span>');
}
}
});
});
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/dropzone.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/basic.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/min/dropzone.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
// prevent auto processing in dropzone configuration
Dropzone.options.photoDropzone = {
autoProcessQueue: false
};
</script>
<form method="POST" enctype="multipart/form-data">
<input type="text" name="name" id="name">
<button type="submit">send</button>
</form>
<!-- add dropzone form in the same page -->
<form action="add.php" class="dropzone" id="photo-dropzone">
I have created some ajax that uploads an image and loads it into the page.
It creates an images with an X button on the top corner, I am trying to get it so when this button is clicked I then run another peice of php code with will delete the correct image and reload the images.
I cant get my ajax code to pick up the php code and I am not sure why.
Any pointed would be very helpful.
I have found out that dymanically created elemets will not be picked up so had to change my ajax code to
$("body").on("click", "#deleteform button", function(e){
so I am hitting this point but but it sill is not picking up my php code and I dont know why.
Any pointers would be very helpful
AJAX JS:
$(document).ready(function(){
$("#uploadForm").on('submit',function(e) {
e.preventDefault();
$.ajax({
url: "include_advert/advert_new_gun_add_image.inc.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
},
error: function()
{
}
});
});
});
$(document).ready(function(){
$('button.deleteimage').on('click', function(){
var image_id = parseInt($(this).parent().attr('id').replace('deleteform', ''));
console.log(image_id); // You can comment out this. Used for debugging.
e.preventDefault();
$.ajax({
url: "include_advert/advert_new_gun_delete_image.php",
type: "POST",
data: {image_id: image_id},
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer"+image_id).html(data); // targetLayer is dynamic and is different for each record
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
});
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="include_advert/advert_js/advert_gun_load_save_images.js"></script>
<div class="bgColor">
<form id="uploadForm" action="include_advert/advert_new_gun_add_image.inc.php" method="post" class="login-form" enctype="multipart/form-data">
<div id="targetLayer" class=col> </div>
<div id="uploadFormLayer">
<input name="file" type="file" class="inputFile" /><br/>
<div class="text-center">
<input type="submit" name="submit" value="UPLOAD" class="btn btn-common log-btn">
</div>
</form>
advert_new_gun_add_image.inc.php:
<?php
$imagecount = 0;
echo ('<div class=row sm>');
foreach ($getadvertimages as $getadvertimages_row) {
echo ( '<div class="image-area" >
<form id="deleteform'.$getadvertimages_row['image_id'].'" method = "POST" action ="include_advert/advert_new_gun_delete_image.php" >
<img src="'. $getadvertimages_row['image_src'] . '" alt="Preview">
<button onclick = "" name="deleteimage" id="deleteimage" value="'. $getadvertimages_row['image_id'] . '" class="remove-image" style="display: inline;" >X</button>
</form>
</div>');
}
echo ('</div>');
advert_new_gun_delete_image.php:
<?php
if (isset($_POST['deleteimage']) ){
echo('hello');
}?>
I am expecting when I click the button on the image it will run the advert_new_gun_delete_image.php file without reloading the complete page
The Above Answer was almost there but I had to change the $('button.delete-button').on('click', function(){ to $("body").on("click", "#deleteimage", function(e){
And I also removed:contentType: false, cache: false,processData:false,
Thanks Ghulam for the push in the right direction
$(document).ready(function(){
$("body").on("click", "#deleteimage", function(e){
var image_id = parseInt($(this).parent().attr('id').replace('deleteform', ''));
console.log(image_id); // You can comment out this. Used for debugging.
e.preventDefault();
$.ajax({
url: "include_advert/advert_new_gun_delete_image.php",
type: "POST",
data: {image_id: image_id },
success: function(data)
{
$('#imageareadiv').hide();
$("#targetLayer").html(data); // targetLayer is dynamic and is different for each record
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
});
$(document).ready(function(){
$('button.delete-button').on('click', function(){
var image_id = parseInt($(this).parent().attr('id').replace('deleteform', ''));
console.log(image_id); // You can comment out this. Used for debugging.
e.preventDefault();
$.ajax({
url: "include_advert/advert_new_gun_delete_image.php",
type: "POST",
data: {image_id: image_id},
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer"+image_id).html(data); // targetLayer is dynamic and is different for each record
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
});
include 'advert_new_gun_save_image_script.inc.php';
include 'advert_new_dropdown_populate/advert_new_gun_image_populate.php';
$imagecount = 0;
echo ('<div class=row sm>');
foreach ($getadvertimages as $getadvertimages_row) {
echo ( '<div class="image-area" >
<form id="deleteform'.$getadvertimages_row['image_id'].'" method = "POST" action ="include_advert/advert_new_gun_delete_image.php" >
<img src="'. $getadvertimages_row['image_src'] . '" alt="Preview">
<button type="button" name="deleteimage" value="" class="remove-image delete-button" style="display: inline;" >X</button>
</form>
</div>');
}
echo ('</div>');
Similarly you can make "targetLayer" dynamic with image_id value just like I did with form's attribute id deleteform.
$(document).delegate('#deleteform button', 'click', function (e) {
instead of
$("body").on("click", "#deleteform button", function(e){
I'm trying to add an image to a post with Ajax / Laravel 5.4.
This is my HTML:
<form class="comments-form" action="/upload/comments/{{$post->id}}" method="post" data-id ="{{$post->id}}" enctype="multipart/form-data">
#csrf
<div class="user-picture">
<img src = '/images/avatars/{!! Auth::check() ? Auth::user()->avatar : 'null' !!}'>
</div>
<div class="comment-input">
<textarea name="comment" rows="8" cols="80" placeholder="Write a Comment"></textarea>
<input type="file" name="meme" value="">
</div>
<div class="comment-button">
<button class = 'add-comment' type="button" name="add-comment">Post</button>
</div>
Here is the Ajax code:
$('.add-comment').click(function(){
var comment_data = $('.comments-form').serialize();
var post_id = $('.comments-form').data('id');
var formData = new FormData('.comments-form');// i think here is problem
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
},
method: 'POST',
url: '/upload/comments/' + post_id,
data: comment_data,formData,
success: function(data)
{
console.log(data);
$('.all-comments').append(data);
},
error: function(data)
{
console.log('error');
}
});
This doesn't work – what am I doing wrong?
The FormData constructor takes a form not a string(you passes a css selector)
var formData = new FormData($('.comments-form').get(0));
If you use FormData in this way all fields in the form will be automatically added to the FormData object.
If there are items outside of the form fields that needs to be sent use the append method
formData.append('comment_data', $('.comments-form').data('id'));
When passing a FormData object to jQuery ajax you pass it alone and add processData and contentType set to false
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
},
method: 'POST',
url: '/upload/comments/' + post_id,
data: formData,
contentType: false,
preocessData: false,
success: function(data)
{
console.log(data);
$('.all-comments').append(data);
},
error: function(data)
{
console.log('error');
}
});
If you want to store data using ajax.. you shouldn't need to put your action in your form component
<form class="comments-form" data-id ="{{$post->id}}">
{{ csrf_field() }}
<div class="user-picture">
<img src = '/images/avatars/{!! Auth::check() ? Auth::user()->avatar : 'null' !!}'>
</div>
<div class="comment-input">
<textarea name="comment" rows="8" cols="80" placeholder="Write a Comment"></textarea>
<input type="file" name="meme" value="">
</div>
<div class="comment-button">
<button class = 'add-comment' type="button" name="add-comment">Post</button>
</div>
</form>
I think if you want to submit your form, better to use jquery submit method
$('.add-comment').submit(function(){
var post_id = $('.comments-form').data('id');
var comment_data = new FormData($(".comments-form")[0]);
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
},
method: 'POST',
url: '/upload/comments/' + post_id,
data: comment_data,
dataType: 'json'
success: function(data)
{
console.log(data);
$('.all-comments').append(data);
},
error: function(data)
{
console.log('error');
}
});
you can solve it as the following:
var formData = new FormData($("#FormId")[0]);
$.ajax({
url: '/upload/comments/' + post_id,
type: "POST",
data: formData,
processData: false,
contentType: false,
dataType: 'application/json',
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
success: function (data, textStatus, jqXHR) {
console.log(data);
$('.all-comments').append(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('error');
}
});
return false;
the formData variable contains all data of the form if you want to send the post id with the data sent you can put hidden field inside form called post id
like this
<input type="hidden" name="post_id" value="{{$post->id}}">
and then apply the above code
Multiple file upload is not working if all files are not the same extension !! If I chose two png files , it works . But choosing two different file extensions (png,pdf) got empty array in $_FILES !
index.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" > </script>
</head>
<body>
<form>
<input name="file[]" type="file" multiple/>
<input type="button" value="Upload" />
</form>
<progress></progress>
<script>
$(':button').on('click', function() {
$.ajax({
// Your server script to process the upload
url: 'upload.php',
type: 'POST',
// Form data
data: new FormData($('form')[0]),
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
} , false);
}
return myXhr;
},
});
});
</script>
</body>
</html>
upload.php
<?php var_dump($_FILES); ?>
Result image
Hope to help you.
demo.php
<?php
if(isset($_FILES)&&!empty($_FILES)){
for($i=0;$i<count($_FILES);$i++){
echo "File ".($i+1)." is ".$_FILES["file-".$i]['name']."\n";
}
die;
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Updated part
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
// Full Ajax request
$(".update").click(function(e) {
// Stops the form from reloading
e.preventDefault();
$.ajax({
url: 'demo.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
});
});
</script>
</head>
<body>
<form enctype="multipart/form-data" method="post">
<input id="file" name="file[]" type="file" multiple/>
<input class="update" type="submit" />
</form>
<body>
</html>
I think you can use following code :-
<button id="upload">Upload</button>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var form_data = new FormData();
var ins = document.getElementById('multiFiles').files.length;
for (var x = 0; x < ins; x++) {
form_data.append("files[]", document.getElementById('multiFiles').files[x]);
}
$.ajax({
url: 'uploads.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the PHP script
},
error: function (response) {
$('#msg').html(response); // display error response from the PHP script
}
});
});
});
</script>
I have been trying to upload an image with AJAX but somehow it's not working. CodeIgniter always throwing 'You have not selected any file'.
Thanks in advance.
Here's my Controller -
class Upload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('url');
}
public function index() {
$this->load->view('upload/upload');
}
public function upload_file() {
$config['upload_path'] = './uploads/Ajax/';
$config['allowed_types'] = 'gif|jpg|png|doc|txt';
$config['max_size'] = 1024 * 8;
$this->load->library('upload', $config);
$title=$this->input->post('title');
if (!$this->upload->do_upload('userfile')) {
echo $this->upload->display_errors()."<br>".$title;
}
else {
$data = $this->upload->data();
echo $data['file_name']." uploaded successfully";
}
}
}
/* end of file */
And here's the view
<!DOCTYPE HTML>
<html>
<head>
<title>AJAX File Upload</title>
<script src="<?php echo base_url(); ?>assets/js/jquery-1.11.3.js"> </script>
<script src="<?php echo base_url(); ?>assets/js/AjaxFileUpload.js"> </script>
<script>
$(document).ready(function() {
$('#upload-form').submit(function(e) {
e.preventDefault();
if (typeof FormData !== 'undefined') {
$.ajax({
url : '<?php echo base_url(); ?>upload/upload/upload_file',
type : 'POST',
data : FormData,
beforeSend: function () {
$("#result").html("Uploading, please wait....");
},
error: function () {
alert("ERROR in upload");
},
success : function(data) {
$('#result').html(data)
}
});
}
else {
alert("Your browser doesn't support FormData API!");
}
});
});
</script>
</head>
<body>
<h1>Upload File</h1>
<form method="post" action="" id="upload-form" enctype="multipart/form-data" accept-charset="utf-8">
<p>
<label for="title">Title</label>
<input type="text" name="title" id="title" value="" autocomplete="off">
</p>
<p>
<label for="userfile">File</label>
<input type="file" name="userfile" id="userfile">
</p>
<input type="submit" name="submit" id="submit">
</form>
<h2>Result</h2>
<span id="result"></span>
</body>
I have tested in Firefox 43, IE11 & Chrome 43
<script>
$(document).ready(function() {
$('#upload-form').submit(function(e) {
e.preventDefault();
if (typeof FormData !== 'undefined') {
$.ajax({
url : '<?php echo base_url(); ?>upload/upload/upload_file',
type : 'POST',
secureuri :false,
fileElementId :'userfile',
data : FormData,
beforeSend: function () {
$("#result").html("Uploading, please wait....");
},
error: function () {
alert("ERROR in upload");
},
success : function(data) {
$('#result').html(data)
}
});
}
else {
alert("Your browser doesn't support FormData API!");
}
});
});
</script>
You need to add xhr function in ajax request
$(document).on('submit','#form_id',function(){
var formData = new FormData(this);
$.ajax({
type:'POST',
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
return xhrobj;
},
url: $(this).attr('action'),
data:formData,
cache:false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
});
you can use
$(document).on('submit','#form_id',function(){
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
});
no plugin required for this, for easiness you can use ajaxForm jquery plugin and just use
$('#form-id').ajaxSubmit({
// same config as ajax call but dont use data option right here
});
have a look on http://malsup.com/jquery/form/ to for more information about plugin
Use this
$("#upload-form").on('submit' ,function(){
var form = $(this);
$.ajax({
url: form.attr('action'),
data: new FormData(form[0]),
dataType: 'json',
method: 'POST',
cache: false,
contentType: false,
processData: false,
success: function(data){
}
});
});
Use $.ajaxFileUpload instead $.ajax, this should work, if not please let me see your AjaxFileUpload.js
$(document).ready(function() {
$('#upload-form').submit(function(e) {
e.preventDefault();
if (typeof FormData !== 'undefined') {
$.ajaxFileUpload({
url :'./upload/upload_file/',
fileElementId : 'userfile', // your input file ID
dataType : 'json',
//
data : {
'title' : $('#title').val() // parse title input data
},
beforeSend: function () {
$("#result").html("Uploading, please wait....");
},
error: function () {
alert("ERROR in upload");
},
success : function(data) {
$('#result').html(data)
}
});
}
else {
alert("Your browser doesn't support FormData API!");
}
});
});