In product-master.php (view page), I have a few buttons: Add, Edit, Delete.
Each button got unique name: btnAddProduct, btnEditProduct, btnDelProduct
These buttons share the same action page as shown in the ajax code below: action/product-master.php (yes I named it according to the view page, just different folder)
Yes, I'm using ajax method to process form data. How to validate which button was pressed?
I tried using isset($_POST['btnAddProduct']) but it is not working. Below is my button:
btnAddProduct
<input type="submit" class="btn btn-success" id="btnAddProduct" name="btnAddProduct">
product-master.php
$('#btnAddProduct').on('click', function(e) {
var formData = new FormData($('#form-add-modal')[0]);
$.ajax({
url: "action/<?php echo basename(__FILE__); ?>",
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
},
error: function(){
//Display error here
}
});
});
Buttons aren't included when you create a FormData from a form, since the FormData constructor has no way of knowing which button was clicked. You need to add it to the FormData explicitly.
$('#btnAddProduct').on('click', function(e) {
var formData = new FormData($('#form-add-modal')[0]);
formData.set(this.name, "1");
$.ajax({
url: "action/<?php echo basename(__FILE__); ?>",
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
},
error: function(){
//Display error here
}
});
});
Related
So I have a form and I'm submitting the form through ajax using jquery serialization function
serialized = $(Forms).serialize();
$.ajax({
type : "POST",
cache : false,
url : "blah",
data : serialized,
success: function(data) {
}
but then what if the form has an <input type="file"> field....how do I pass the file into the form using this ajax serialization method...printing $_FILES doesn't output anything
Use FormData object.It works for any type of form
$(document).on("submit", "form", function(event)
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
A file cannot be uploaded using AJAX because you cannot access the contents of a file stored on the client computer and send it in the request using javascript. One of the techniques to achieve this is to use hidden iframes. There's a nice jquery form plugin which allows you to AJAXify your forms and it supports file uploads as well. So using this plugin your code will simply look like this:
$(function() {
$('#ifoftheform').ajaxForm(function(result) {
alert('the form was successfully processed');
});
});
The plugin automatically takes care of subscribing to the submit event of the form, canceling the default submission, serializing the values, using the proper method and handle file upload fields, ...
var form = $('#job-request-form')[0];
var formData = new FormData(form);
event.preventDefault();
$.ajax({
url: "/send_resume/", // the endpoint
type: "POST", // http method
processData: false,
contentType: false,
data: formData,
It worked for me! just set processData and contentType False.
HTML
<form name="my_form" id="my_form" accept-charset="multipart/form-data" onsubmit="return false">
<input id="name" name="name" placeholder="Enter Name" type="text" value="">
<textarea id="detail" name="detail" placeholder="Enter Detail"></textarea>
<select name="gender" id="gender">
<option value="male" selected="selected">Male</option>
<option value="female">Female</option>
</select>
<input type="file" id="my_images" name="my_images" multiple="" accept="image/x-png,image/gif,image/jpeg"/>
</form>
JavaScript
var data = new FormData();
//Form data
var form_data = $('#my_form').serializeArray();
$.each(form_data, function (key, input) {
data.append(input.name, input.value);
});
//File data
var file_data = $('input[name="my_images"]')[0].files;
for (var i = 0; i < file_data.length; i++) {
data.append("my_images[]", file_data[i]);
}
//Custom data
data.append('key', 'value');
$.ajax({
url: "URL",
method: "post",
processData: false,
contentType: false,
data: data,
success: function (data) {
//success
},
error: function (e) {
//error
}
});
PHP
<?php
echo '<pre>';
print_r($_POST);
print_r($_FILES);
echo '</pre>';
die();
?>
You can upload files via AJAX by using the FormData method. Although IE7,8 and 9 do not support FormData functionality.
$.ajax({
url: "ajax.php",
type: "POST",
data: new FormData('form'),
contentType: false,
cache: false,
processData:false,
success: function(data) {
$("#response").html(data);
}
});
$(document).on('click', '#submitBtn', function(e){
e.preventDefault();
e.stopImmediatePropagation();
var form = $("#myForm").closest("form");
var formData = new FormData(form[0]);
$.ajax({
type: "POST",
data: formData,
dataType: "json",
url: form.attr('action'),
processData: false,
contentType: false,
success: function(data) {
alert('Sucess! Form data posted with file type of input also!');
}
)};});
By making use of new FormData() and setting processData: false, contentType:false in ajax call submission of form with file input worked for me
Using above code I am able to submit form data with file field also through Ajax
HTML5 introduces FormData class that can be used to file upload with ajax.
FormData support starts from following desktop browsers versions. IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+
FormData - Mozilla.org
I want to upload an image to a local folder using jquery ajax. The complex part is i have the forms which are generated dynamically, and to those forms and fields i am giving the id to it so as to show which form is submitted as shown below. I am using following code but the image is not uploaded.
View: Upload_View.php
<script type="text/javascript">
function sendVideoData(frm_id)
{
var data = new FormData(document.getElementById("post_video_"+frm_id));
// make the AJAX request
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>"+"dashboard/do_upload",
data: data+'&form_id='+frm_id,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
dataType: 'json',
success: function (data) {
alert("data"+data);
},
});
return false;
}
</script>
<form name="post_video" id="post_video_<?=$row1['id']?>" method="post" onsubmit="return sendVideoData(<?=$row1['id']?>)">
<input type="file" name="save_movie_<?=$row1['id']?>" id="movie_<?=$row1['id']?>" />
<input name="type_lecture_id" class="get_lecture_id" id="get_lecture_id_<?=$row1['id']?>" value="<?=$row1['id']?>" type="hidden"/>
<input type="button" class="postbtn" id="submit_movie_<?=$row1['id']?>" value="Upload Video File"/>
</form>
Controller:
$formid=$_POST['form_id'];
$filename='save_movie_'.$formid;
$path_parts = pathinfo($_FILES[$filename]["name"]);
$extension = $path_parts['extension'];
$Random_file_name=$filename.".".$extension;
move_uploaded_file($_FILES[$filename]['tmp_name'], "http://localhost/dummy/uploads/".$Random_file_name);
save_movie_ this is the id of the file control and $formid shows from which form and which field we have to take data, but because i am new to Codeigniter i don't know from how to upload it. One thing more i want to display progress bar also to display the progress of image upload.Please reply. Thanks...
You must have to modify your jQuery ajax function in the following way
var data = new FormData(document.getElementById("post_video_"+frm_id)[0]);
jQuery("#progressbar").show(); // add your prgress bar here like this
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>"+"dashboard/do_upload",
data: data+'&form_id='+frm_id,
mimeType:"multipart/form-data",
contentType: false,
async: false,
cache: false,
processData:false,
dataType: 'json',
success: function (data) {
alert("data"+data);
jQuery("#progressbar").hide(); //hide your loader like this
},
});
return false;
Thank You.
Here is my form
<form name="uploadImg" id="uploadImg" class="profile-image" enctype="multipart/form-data">
<input type="file" name="profile" id="updProfileImg">
</form>
Here is my jquery event
$("#updProfileImg:file").change(function() {
$('#uploadImg').submit(function() {
var queryString = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {
},
success: function() {
}
})
})
})
But the change event is not triggering form submit so I tried trigger('submit') but the page is refreshing instead of submitting in ajax.
You are binding the events incorrectly. As you currently have it, changing the field will trigger the binding of the submit. It need to be like this:
// bind the submit event
$('#uploadImg').submit(function() {
var queryString = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {
},
success: function() {
}
});
});
// bind the change event to trigger a submit
$("#updProfileImg:file").change(function() {
$("#uploadImg").submit();
});
A simple modification works
$("#updProfileImg:file").change(function() {
//$('#uploadImg').submit(function() {
var queryString = new FormData($('#uploadImg')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {
},
success: function() {
}
})
//})
})
you should try this code:
$("#updProfileImg:file").on("change", function(){
var queryString = new FormData($('#uploadImg')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {},
success: function() {}
})
});
because i expect the ".change()" will be fired one time in the first change.
I'm using jQuery and Codeigniter to update the database via AJAX. The following code does not seem to do anything or send anything to my controller when the button is clicked...
jQuery:
$("#button_submit1").click(function(e) {
$.ajax({
type: "POST",
url: window.location.href,
dataType: "json",
data: $('#writereview_form').serialize() + '&ajax=true',
cache: false,
success: function(data) {
alert("yay");
//$("#writereview_box").fadeOut(1000);
}
});
return false;
});
HTML:
<form action="http://mysite.com/places/writereview/2107" id="writereview_form" method="post" accept-charset="utf-8">
...
...
<input type="submit" name="submit" value="Submit Review" class="button_submit" id="button_submit1">
Any ideas why the ajax data is not being sent?
In this case its better to bind to the 'submit' event on the form and then use preventDefault() to stop the HTML submission and use Ajax instead.
You should also use the form's action instead of window.location
$("#writereview_form").submit(function(e) {
var $this = $(this);
e.preventDefault();
$.ajax({
type: "POST",
url: $this.attr('action'),
dataType: "json",
data: $this.serialize() + '&ajax=true',
cache: false,
success: function(data) {
alert("yay");
//$("#writereview_box").fadeOut(1000);
}
});
});
Try withiut using window.location.href and giving url as url: "page.php",
So I have a form and I'm submitting the form through ajax using jquery serialization function
serialized = $(Forms).serialize();
$.ajax({
type : "POST",
cache : false,
url : "blah",
data : serialized,
success: function(data) {
}
but then what if the form has an <input type="file"> field....how do I pass the file into the form using this ajax serialization method...printing $_FILES doesn't output anything
Use FormData object.It works for any type of form
$(document).on("submit", "form", function(event)
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
A file cannot be uploaded using AJAX because you cannot access the contents of a file stored on the client computer and send it in the request using javascript. One of the techniques to achieve this is to use hidden iframes. There's a nice jquery form plugin which allows you to AJAXify your forms and it supports file uploads as well. So using this plugin your code will simply look like this:
$(function() {
$('#ifoftheform').ajaxForm(function(result) {
alert('the form was successfully processed');
});
});
The plugin automatically takes care of subscribing to the submit event of the form, canceling the default submission, serializing the values, using the proper method and handle file upload fields, ...
var form = $('#job-request-form')[0];
var formData = new FormData(form);
event.preventDefault();
$.ajax({
url: "/send_resume/", // the endpoint
type: "POST", // http method
processData: false,
contentType: false,
data: formData,
It worked for me! just set processData and contentType False.
HTML
<form name="my_form" id="my_form" accept-charset="multipart/form-data" onsubmit="return false">
<input id="name" name="name" placeholder="Enter Name" type="text" value="">
<textarea id="detail" name="detail" placeholder="Enter Detail"></textarea>
<select name="gender" id="gender">
<option value="male" selected="selected">Male</option>
<option value="female">Female</option>
</select>
<input type="file" id="my_images" name="my_images" multiple="" accept="image/x-png,image/gif,image/jpeg"/>
</form>
JavaScript
var data = new FormData();
//Form data
var form_data = $('#my_form').serializeArray();
$.each(form_data, function (key, input) {
data.append(input.name, input.value);
});
//File data
var file_data = $('input[name="my_images"]')[0].files;
for (var i = 0; i < file_data.length; i++) {
data.append("my_images[]", file_data[i]);
}
//Custom data
data.append('key', 'value');
$.ajax({
url: "URL",
method: "post",
processData: false,
contentType: false,
data: data,
success: function (data) {
//success
},
error: function (e) {
//error
}
});
PHP
<?php
echo '<pre>';
print_r($_POST);
print_r($_FILES);
echo '</pre>';
die();
?>
You can upload files via AJAX by using the FormData method. Although IE7,8 and 9 do not support FormData functionality.
$.ajax({
url: "ajax.php",
type: "POST",
data: new FormData('form'),
contentType: false,
cache: false,
processData:false,
success: function(data) {
$("#response").html(data);
}
});
$(document).on('click', '#submitBtn', function(e){
e.preventDefault();
e.stopImmediatePropagation();
var form = $("#myForm").closest("form");
var formData = new FormData(form[0]);
$.ajax({
type: "POST",
data: formData,
dataType: "json",
url: form.attr('action'),
processData: false,
contentType: false,
success: function(data) {
alert('Sucess! Form data posted with file type of input also!');
}
)};});
By making use of new FormData() and setting processData: false, contentType:false in ajax call submission of form with file input worked for me
Using above code I am able to submit form data with file field also through Ajax
HTML5 introduces FormData class that can be used to file upload with ajax.
FormData support starts from following desktop browsers versions. IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+
FormData - Mozilla.org