Jquery change not working with Ajax call inside [duplicate] - php

For past few days i have been struggling to submit a form with jQuery and AJAX. The problem i'm facing is to upload the image in the form field.
My form is something like this:
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
and my jQuery script for getting the form value is something like this:
$("form").submit(function (event) {
$.dataArray = $(this).serializeArray(); // array of form data
console.log($.dataArray);
event.preventDefault();
});
But this returns all the field values except image one, in case of image is return null.
How do I store in the dataarray?
I want to store so I can send the value to the server through the AJAX.

For uploading single image its like this
<html>
<head>
<meta charset="UTF-8">
<title>AJAX image upload with, jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'http://localhost/ci/index.php/welcome/upload', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
</script>
</head>
<body>
<p id="msg"></p>
<input type="file" id="file" name="file" multiple />
<button id="upload">Upload</button>
</body>
</html>
For multiple images u will have to loop its kinda different

I have found a similar question, hope it will help you.
Upload image using jquery
Another option to consider is to use some sort of jQuery plugin to upload images like Cloudinary and include it in your HTML pages :
<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>
and then include all required jQuery files:
<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.ui.widget.js' type='text/javascript'></script>
<script src='jquery.iframe-transport.js' type='text/javascript'></script>
<script src='jquery.fileupload.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>

try this code, it's work for me.
$("form").submit(function (event) {
var form_data = new FormData($(this));
$.ajax({
url : url,
type : 'POST',
data : form_data,
processData: false, // tell jQuery not to process the data
contentType: false,
success : function(resp){
}
});
});

Try this code. using formData()
$("form").submit(function (event) {
var formData = new FormData($(this));
$.ajax({
url: url,
type: 'POST',
data: formData,
async: false,
success: function (data) {
//success callback
},
cache: false,
contentType: false,
processData: false
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>

serialize() method not able to post file data.
For sending file using ajax use FormData instead of serializing
HTML5 introduces FormData to allow developers to build forms objects dynamically, and then to send this form object via AJAX.
your Html
<form action="upload_image.php" id="form_img" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
AJAX call
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form_img").submit(function(e){
e.preventDefault();
var formData = new FormData($("#form_img")[0]);
$.ajax({
url : $("#form_img").attr('action'),
type : 'POST',
data : formData,
contentType : false,
processData : false,
success: function(resp) {
console.log(resp);
}
});
});
});
</script>
upload_image.php
print_r($_FILES) //check you get file data or not
Try this way.Hope it will help you

Please check the follow the code, which i am using to upload image.
$.ajax({
url: UPLOADURL, // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this),// Data sent to server, a set of key/value pairs representing form fields and values
contentType: false,// The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
cache: false,// To unable request pages to be cached
processData:false,// To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
success: function(data)// A function to be called if request succeeds
{
data = JSON.parse(data);
console.log(data);
if(data.status == "Success"){
attachmentListing();
//$("#mailerMessage").html(data.data.mailStatus);
//$("#mailerMessage").fadeIn();
setTimeout(function () {
$("#mailerMessage").fadeOut();
},5000);
}else{
toastr.warning(data.status);
}
$("#ajaxloader").addClass("hideajaxLoader");
},
error: function (jqXHR, errdata, errorThrown) {
log("error");
$("#ajaxloader").addClass("hideajaxLoader");
}
});

Related

Print the filename of the inputted file without refreshing the page

I'm trying to display the filename of the file that I submitted without refreshing the page using JQUERY, AJAX and PHP. But for some reason, it is not displaying.
Here's my HTML form
<form>
<input type="file" id="stegoImage" name="stegoImage">
</form>
<button type="button" id="desteganize" name="desteganize">DESTEGANIZE</button>
<div id="result"></div>
Here's my JQuery and AJAX
$(document).ready(function(){
$('#desteganize').click(function(){
var stegoImage = $("#stegoImage").prop("files")[0];
var form = new formData();
form.append("stegoImage", stegoImage);
$.ajax({
url: 'process.php',
type: 'POST',
data: form,
contentType: false,
processData:false,
success:function(result){
$("#result").html(result);
}
})
});
});
And Here's my PHP code (process.php)
$filename = $_FILES['stegoImage']['name'];
echo $filename;
$(document).ready(function() {
$('input[type="file"]').change(function(e) {
var fname = e.target.files[0].name;
$("h4").text(fname);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="file">
<h4></h4>

Appending form inputs to Formdata Object not working

I have a form which is for sending mails.It contain fields such as to_name,subject,message and attachment button.I will create a file input field on clicking the button with class .file_add_btn.
//click event for add files
$(".file_add_btn").click(function(){
if($("#file_div").html() == '')
{
$("#file_div").append('<div class="file_btn_div" id="file_btn_div_first"><input type="file" class="btn_browse" name="file_uploads[]">'+
'<input type="button" class="del_file" value="X"></div>');
}
else
{
if($(document).find('.btn_browse:last').get(0).files.length !==0)
{
$("#file_div").append('<div class="file_btn_div"><input type="file" class="btn_browse" name="file_uploads[]">'+
'<input type="button" class="del_file" value="X"></div>');
}
}
});
I write the following function to include file inputs into formData.
$.fn.serializefiles = function() {
var obj = $(this);
var form_data = new FormData(this[0]);
$.each($(obj).find('.btn_browse'), function(i, tag) {
$.each(tag.files, function(i, file) {
console.log(tag.name+' '+file.name)//this is printing in console
form_data.append(tag.name, file);
});
});
var params = $(obj).serializeArray();
$.each(params, function (i, val) {
console.log(val.name+'<br/>');
console.log(val.value+'<br/>');
**//here file names are not coming.All other elements are coming.They are not adding to form_data object**
form_data.append(val.name, val.value);
});
return form_data;
};
My ajax call is like the following:
$.ajax({
type: "POST",
url: 'process.php',
data: $("#compose_message").serializefiles() ,//formID=#compose_message
asyn: true,
cache: false,
processData: false,
contentType: false,
success:function()
....
I am not able to append the inputs into the form_data object.In console,I see [object FormData] inside the POST on button click.
Edit: My initial comment above was correct. You don't need to do anything fancy except pass the form object into FormData constructor as shown in my example below.
console.log(JSON.stringify(formData)); will never show the values of the FormData. However, if you look in your browser's network tab, the request that gets sent will show the values being passed.
If you want to check the data before it is being passed, you could use this answer.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<style>
input {
float: left;
clear: left;
}
</style>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="text" name="text" value="text">
<input type="hidden" name="hidden" value="hidden">
<input type="file" name="file_uploads[]" value="">
<input type="file" name="file_uploads[]" value="">
<input type="file" name="file_uploads[]" value="">
<input type="button" value="Add">
<input type="submit" value="Submit">
</form>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var formData = new FormData(this);
console.log(JSON.stringify(formData)); // will always be {}
$.ajax({ url: '404', type: 'post', data: formData, processData: false, contentType: false });
});
$('[type=button]').on('click', function () {
$(this).before('<input type="file" name="file_uploads[]" value="">');
});
});
</script>
</body>
</html>
specify exact data for formdata
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Main magic with files here
formData.append('image', $('input[type=file]')[0].files[0]);
Ajax request with jquery will looks like this:
$.ajax({
url: 'Your url here',
data: formData,
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
})
try this
var form = $("form")[0]; // You need to use standard javascript object here
var formData = new FormData(form);
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Main magic with files here
formData.append('image', $('input[type=file]')[0].files[0]);

Upload files with Ajax and Jquery

I've been trying to figure out how to upload a file through ajax for the past several hours and nothing.
Here's the code:
HTML:
<form action="" method="post" id="uploadForm" enctype="multipart/form-data">
<input type="file" name="image" id="image">
<input type="submit">
</form>
JS:
<script>
jQuery(document).ready(function(){
jQuery('form#uploadForm').on('submit', function(e){
e.preventDefault();
var file = jQuery('#image')[0].files[0];
var form_data = new FormData( jQuery("form#uploadForm")[0] );
form_data.append( 'image', file );
jQuery.ajax({
url: 'index.php?a=do',
type: 'POST',
processData: false,
contentType: false,
cache: false,
data: form_data,
success: function(response) {
console.log(response);
},
});
return false;
});
});
</script>
PHP:
<?php
$a = isset($_GET['a']) ? $_GET['a'] : '';
if($a <> '') {
echo "result - ";
var_dump($_POST);
die();
}
?>
As a result I get an empty array, however if I leave the file field empty, then I get:
result - array(1) {
["image"]=>
string(9) "undefined"
}
I've tried serialize(), serializeObject(), serializeArray(), $.param and every damn time I get "undefined function" error in console.
I went through dozens of similar questions on stackoverflow and nothing helped. I tried doing $.post instead of $.ajax and the "data" field which contains form_data is empty.
I need this for a Wordpress plugin and I'm trying to avoid using 3rd party JS plugins for the upload part.
$_FILES is where you check for uploaded files not $_POST.
Also in your code you actually upload the file twice as it is in the form you instantiated the form data object with then you add it again with append.
Do either
var form_data = new FormData( jQuery("form#uploadForm")[0] );
or
var form_data = new FormData();
form_data.append( 'image', file );
<html>
<head>
<title>Ajax file upload</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert(data);
}
});
}));
</script>
</head>
<body>
<div class="main">
<h1>Ajax Image Upload</h1><br/>
<hr>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
</div>
</body>
</html>

how to make new FormData() work on IE browsers

How can I make this work on IE?
This won't work on IE, new FormData() api is not supported by IE browsers, is there any other api equivalent to new FormData() in IE?
var fd = new FormData();
fd.append( "userfile", $("#userfile")[0].files[0]);
$.ajax({
url : '/user/ajax_upload/',
type: 'POST',
contentType:false,
cache: false,
data: fd,
processData: false,
beforeSend :function(){
},
success : function( data ) {
$('#popupbox').html(data);
}
});
Its better to use jquery form Js for submitting images over ajax. I found it better than FormData()
<script type="text/javascript" src="/js/jquery.form.js"></script>
function update_professional_details(){
var options = {
url : '/validateform/personal',
type : $("#personal_edit_form").attr('method'),
dataType: 'json',
success:function( data ) {
var msg = data.msg;
if(data.status == 'success'){
$("#msg_data").html("Updated successfully, redirecting...")
$("#personal_edit_form").submit();
}else{
$('p[class$="_error2"]').html('');
var msg = data.msg;
$.each(msg, function(k, v) {
$('.'+k+'_error2').html(v);
});
}
},
};
$('#personal_edit_form').ajaxSubmit(options);
return false;
}
$('#updatepersonal').click(function(){
update_professional_details();
return false;
});
Actually i made an alteration to my code to be able to use $.ajax in all other browsers and just made an iframe for the IE browsers like this.
mailer.php
<!--[if IE]>
<iframe src="form.php"></iframe>
<![endif]-->
<![if !IE]>
<script>
$(document).ready( function() {
//Program a custom submit function for the form
$("#form").submit(function(event){
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = new FormData($(this)[0]);
$.ajax({
url: $("#form").attr('action'),
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(returndata);
}
});
return false;
});
});
</script>
<?php include_once ('form.php'); ?>
<div id="email-success"></div>
<![endif]>
form.php
<form id="form" action="form-exec.php" target="_self" method="post" enctype="multipart/form-data">
<input type="text" name="email-to" value="" />
<input type="text" name="email-subject" value="" />
<input type="text" name="email-message" value="" />
<input type="file" name="file" />
<input type="file" name="file2" />
<button type="submit" name="email-send">Skicka</button>
</form>
and the form-exec.php is, in my case, my PHPmailer sender!
AFAIK it is possible in IE9+ only.
To upload file 'ajax like' you should use iframe trick for that.
I used that as source when implementing it:
http://ramui.com/articles/ajax-file-upload-using-iframe.html
Apparently, FormData is not supported in IE. You may, however, be able to use jQuery's serialize like so:
var FD = $('form').serialize();

Display content dynamically based on user input using php and jquery

I have a form that will display a list of transactions based on the name and date.
<form id="form1" name="form1" method="post" action="<?php echo base_url() ?>options/history">
Name
<input name="name" type="text" id="name" />
date
<input name="date" type="text" id="date" />
<input name="find" type="submit" id="find" value="find" />
</form>
Once the form is submitted all the relevant details are being displayed.
Can someone explain to me how I can use jquery to loads the data on the same page?
I'm new to jquery and learning stuff. I did some research and below is what I have found:
<script type="text/javascript">
$(document).ready(function() {
$('#find').click(function() {
$.ajax({
type: "GET",
cache: false,
url: "<?php echo base_url() ?>options/history",
success: function(data) {
alert('Data Loaded');
}
});
});
});
</script>
And also how do I pass the form variables to my controller? Is it possible to directly pass the values to the controller or do I have to pass it along with the URL?
<script type="text/javascript">
$(document).ready(function() {
$('#form1').submit(function() {
// get the data of the form
var data_form = $('#form1').serialize();
$.ajax({
type: "GET",
cache: false,
data: data_form,
url: "<?php echo base_url() ?>options/history",
success: function(data) {
alert('Data Loaded');
// Your data is in the var data returned, you can use it with, for example: $("#content").html(data);
}
});
// Prevent default behaviour
return false;
});
});
</script>
I am a bit confused here. But I suppose you actually want this:
$('form#form1').submit(function(evt){
$.ajax({
type: "GET",
data: $(this).serialize(),
cache: false,
url: "<?php echo base_url() ?>options/history",
success: function (data) {
alert('Data Loaded');
}
});
evt.preventDefault();
return false;
});
You can use .submit() to bind to the JavaScript's submit event instead. By returning false at the end of this handler you can stop the form submission as shown above; or, by using evt.preventDefault().
The data property in $.ajax specifies the data to be sent to the server. As for getting this data you can use .serialize(), it will encode the form elements ready for submit them.

Categories