Submit form having file using java script submit button - javascript

java-script :
i have a form that feed value to a controller via ajax call .
The form get serialized in ajax call and the controller return 'true' on success but the problem is that my form have a file and the file can't be serialized . I am working out how i can receive the file in my controller using this ajax call .
function save()
{
if(save_method == 'On_submitted')
{
url = "<?php echo site_url('MyController/insertForm')?>";
$.ajax({
url : url,
type: "POST",
data:$('#form_name').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_name').modal('hide');
alert('added successfully');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
}
When i omit the input file fields than its working fine , the main problem is to send the file to controller via java-script .
i have tries but i am don't know what is wrong and how can i do it .

you should not use dataType: "JSON" if you sending files.
you can form data for request using (filesForm = name of form):
var formData = new FormData(document.forms.filesForm);
then add other keys:
formData.append("key", keyValue);
and to send this data, add this options to ajax call:
contentType: false,
cache: false,
processData: false,
you need contentType = false (it will be multipart/form-data in fact) if you wish to upload files.
and final ajax call should be like this:
$.ajax({
url: url,
data: formData,
contentType: false,
cache: false,
processData: false,
type: 'POST',
success: function (result) {
$("#result").html(result)
},
error: function (result) {
$("#result").html(result)
}
});

Related

how to add files added to the dropzone and send them in an ajax request as if they were input file fields

I want to receive the files in a formData and send in an ajax request and I want the server to receive it as if it were an input file field.
I tried this: Add files from Dropzone to form
but when I make the request, my server doesn't recognize it as an input file field
$.ajax({
url: args.url,
data: formData, /*I want the file inside this formData */
success: function(data){
}, error: function() {
}
});
You can try to add processData : false and contentType : false to your ajax
As below:
$.ajax({
url: args.url,
data: formData, /*I want the file inside this formData */
processData : false,
contentType : false,
success: function(data){
}, error: function() {
}
});

How can I pass JavaScript variable value in php with same page using modal window

Here is my Javascript for fetching value to input box,
$('#edituserModal').on('show.bs.modal', function(e) {
var userid = $(e.relatedTarget).data('userid');
var u_id = document.getElementById('hdn_user_id').value = userid;
alert(userid);
});
I want this value to use for SQL query in modal window which is on same page.
I fetched value in modal window but unable to use it. What the format to use it.
You can pass js variable into php page using ajax.
$('#edituserModal').on('show.bs.modal', function(e) {
var userid = $(e.relatedTarget).data('userid');
var u_id=document.getElementById('hdn_user_id').value=userid;
$.ajax({ //create an ajax request to load page.php
type: "GET",
url: "page.php",
data:"varabletophp="+u_id, //Here is the value you wish to pass in to php page
dataType: "html", //expect html to be returned
success: function(response){
alert(response);
}
});
});
No you can get this variable into your page.php (php page) using
$fromjs=$_GET['varabletophp'];
echo $fromjs;
you can use input hidden and set userid value in on this input so , post form
Varying modal content based on trigger button :
http://getbootstrap.com/javascript/#modals-related-target
var data = new FormData($('form#' + formId)[0]);
$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
processData: false,
contentType: false,
beforeSend: function () {
},
success: function (response) {
},
error: function (response) {
}
});

JQuery form submit not calling success

After click on submit beforeSend: works but it does not call success: also there is no console error . The data also submit to database correctly ! Then why it not call the success: . Please Help
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$(".alert").removeClass("hide");
var msg = $.ajax({
type: "GET",
url: actionurl,
async: false
}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function() { // wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
});
});
Console Message
Object {readyState: 4, responseText: "<strong>Seat Booked Successfully</strong>", status: 200, statusText: "OK"}
In a Ajax call 'dataType' attributes means what data format can be expect from client(browser). As per error message server is returning 'string' instead 'json'.
But on the other hand, given ajax call is expecting json data to be returned by backend server. Either provide a
valid JSON in response or change datatype to html.
In your AJAX call settings you set dataType to json, but in return you provide a string.
dataType (default: Intelligent Guess (xml, json, script, or html)) The
type of data that you're expecting back from the server. If none is
specified, jQuery will try to infer it based on the MIME type of the
response
So, you have two solutions:
Provide a valid JSON in response
Do not ask for JSON by changing your dataType value (to html), or by removing it.
I had similar problem. As you are redirecting page in success you need to use
e.preventDefault(); // to prevent page refresh
after the ajax call or
return false; // to prevent page refresh
Something like this :
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$( ".alert" ).removeClass( "hide" );
var msg = $.ajax({type: "GET", url: actionurl, async: false}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function(){// wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
return false; e.preventDefault(); //any one of this options to prevent page refresh after ajax call
});
});

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