How to send image to .net Webservice using Ajax in IE8? - javascript

The folowing post is related to: How to send image to PHP file using Ajax?
I managed to get this working as per the above post, but it fails to work on IE8.
Is there a way to get this to work on ie8+?
Here is my code:
$("form[name='uploader']").submit(function(e) {
var formData = new FormData($(this)[0]);
$.ajax({
url: dotnetpage,
type: "POST",
data: formData,
async: false,
success: function (msg) {
$('.js-ugc-image').attr('src', msg);
},
cache: false,
contentType: false,
processData: false
});
e.preventDefault();
});

IE 8 does not have formdata, you can use a hidden iframe and post it and read the results.
I've used a technique that was something like this
Clone the form, move original form into a hidden iframe (this needs to be done because you cant clone or set input type files value on IE) and then submit and read the result of the submit.
Something like this which is a code i used before and worked:
var $form = $('your form');//GET YOUR FORM
//Create Hidden iframe
var _hiddenIframe = $('<iframe id="_hiddenframe" style="display:none;"></iframe>');
//Create Copy Form and add the attributes of the original
var _copyForm = $('<form id="_copyForm" name="_copyForm" style="">');
_copyForm.attr({'method':$form.attr('method'),'action':$form.attr('action'), 'enctype':$form.attr('enctype')});
//Get original fields
$original = $form.children('*');
//Clone and append to form
$original.clone(true).appendTo($form);
//send the original fields to hidden form
$original.appendTo(_copyForm);
//Add the iframe to the body
_hiddenIframe.appendTo('body');
//Add the form to the hidden iframe
_copyForm.appendTo(_hiddenIframe.contents().find('body'));
var $r;
//submit the form
_copyForm.submit();
//after it reloaded(after post)
_hiddenIframe.on('load',function(){
//read result (maybe a json??)
$r = $.parseJSON(_hiddenIframe.contents().find('body').text());
//Do something with the result
if($r.result=='ok'){
//Do Something if ok
}
else{
//Do Something if error
}
});

No,sorry, IE8 doesn't support the FormData object. (See http://caniuse.com/#search=formdata)
Whay you can do is embed the <input type='file > tag in a separate form and submit it using jQuery.

Related

When performing a replaceWith via Ajax, the html of the fields is not being replaced correctly

Before submitting with Ajax, I am changing the ids of all inputs on the form, due to a need.
The problem is when I submit using Ajax, I need to replace the html of all fields in the form using the replaceWith function, but it is not doing that. It is simply changing the html, but it seems to be keeping the original html when I inspect it in the browser.
HTML should be replaced as shown in image 2.
Why can't HTML be replaced correctly? Shouldn't the replaceWith function be used for such a situation?
var genericModal = getLastGenericModalObject();
var frmFormaContato = genericModal.find('.frm-create-edit');
var valdata = frmFormaContato.serialize();
$.ajax({
url: url,
type: "POST",
traditional: true,
data: valdata,
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
success: function (data) {
frmFormaContato.replaceWith(data);
stopLoadGlobal();
},
error: function (e) {
stopLoadGlobal();
redirectToError(e.status);
return false;
}
});
Thank you :)
The solution was to change the IDs before replacing the HTML according to the DOM.
var dataChanged = changeIds($(data));
frmFormaContato.replaceWith(dataChanged);

Create FormData excluding not provided input file

I submit a form manually via jQuery. I use FormData with all input elements from this form.
See code below:
$("#submit-form").on('submit', function (event) {
event.preventDefault();
var form = $('#submit-form')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
url: "my-best-handler",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 60000
});
});
One of input elements is file and it's optional to set it. When it's not set, I don't need to use it in FormData and be sent with other elements to request handler.
The problem is that currently it will be sent even if it's not set.
I'm curious how I can exclude it from FormData if it's not set.
In worst case I can create FormData manually like here.
But I hope there is "black list" like approach by removing just not set file from FormData OR any other elegant way.
Update:
I came with the following solution:
if (!$("#input-file").val()) {
data.delete('input-file');
}
You can use the delete() function to remove your field
var form = $('#submit-form')[0];
var data = new FormData(form);
if (!$("#input-file").val()) {
data.delete('input-file');
}
Disabling input approach.
Disabled form controls never get submitted
$("#submit-form").on('submit', function (event) {
event.preventDefault();
// disable before creating FormData
$(this).find(':file').prop('disabled', function(){
return !this.files.length;
});
var form = $('#submit-form')[0];
var data = new FormData(form);
As mentioned in comments should re-enable in ajax success callback

Submit form data as JSON

I have to recreate a form that was originally created using Jotform - it is here. I am struggling in one area. It is a pretty simple form, the only caveat being the ability to duplicate a form field form multiple entries. That part can be seen here. When the form is duplicated, I need to submit the form data as a JSON array. In the fiddle, I didn't put the regular form fields, here is how they and the cloned field need to submit the data.
q2_fullName[first]:test
q2_fullName[last]:test
q1_currentCommission1:[{"Instruments":"a","Commissions":"1","Margins":"a"},{"Instruments":"b","Commissions":"2","Margins":"b"},{"Instruments":"c","Commissions":"3","Margins":"c"}]
normally in my $.ajax handler, I just serialize the data, but that doesn't work in creating the json array for the cloned fields. Normally like so:
submitHandler: function(form) {
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url: form.action,
data: dataString,
dataType: "json",
beforeSend: function(data){
//before send
},
success: function(data){
//success function
}
});
return false;
},
I need to somehow serialize the non cloned fields (I think) and create a json array out of the cloned values and assign them a key name
You can build the post data and the json string like this :
var data = {
// get/set the firstname etc
"q2_fullName":{
"first":"", // get firstname ie $("#first_2").val(),
"last":""
},
"q1_currentCommission1" :""
},
commisions = [];
$('.InsContain').each(function() {
var $inputs = $(this).find('input');
commisions.push({
"Instruments" : $inputs.eq(0).val(),
"Commissions" : $inputs.eq(1).val(),
"Margins" : $inputs.eq(2).val()
});
});
data.q1_currentCommission1 = JSON.stringify(commisions);
Posted data :
q2_fullName[first]:aaa
q2_fullName[last]:123
q1_currentCommission1:[{"Instruments":"1","Commissions":"1","Margins":"1"}]
Update fiddle here

jquery file upload without redirect

I know that I cannot upload a file with jquery so I come up with this solution:
var ifframe = $("<iframe></iframe>");
var input = $('<input type="file" id="file" name="file" size="10"/>');
var form = $('<form action="/upload" method="post" enctype="multipart/form-data"></form> ');
form.append(input);
ifframe.append(form);
input.change(function(){
form.submit();
}
);
input.trigger("click");
Basically I try to create a form insde the iframe and the trigger a click on the file field so the user is given a window where he can select image. then the form is automatically submitted and the main page does not get redirected since the form is in an iframe. The problem is that the main page does get redirected. Can anybody help me out here?
Actually, JQ can submit a form w. attachment asynchronously. Take a look at this example. Much better than an iframe approach.
$("#addProductForm").submit(function (event) {
event.preventDefault();
//grab all form data
var formData = $(this).serialize();
$.ajax({
url: 'addProduct.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
$("#productFormOutput").html(returndata);
alert(formData);
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});

AJAX to PHP without page refresh

I'm having some trouble getting my form to submit data to my PHP file.
Without the AJAX script that I have, the form takes the user through to 'xxx.php' and submits the data on the database, however when I include this script, it prevents the page from refreshing, displays the success message, and fades in 'myDiv' but then no data appears in the database.
Any pointers in the right direction would be very much appreciated. Pulling my hair out over this one.
HTML
<form action='xxx.php' id='myForm' method='post'>
<p>Your content</p>
<input type='text' name='content' id='content'/>
<input type='submit' id='subbutton' name='subbutton' value='Submit' />
</form>
<div id='message'></div>
JavaScript
<script>
$(document).ready(function(){
$("#subbutton").click(function(e){
e.preventDefault();
var content = $("#content").attr('value');
$.ajax({
type: "POST",
url: "xxx.php",
data: "content="+content,
success: function(html){
$(".myDiv").fadeTo(500, 1);
},
beforeSend:function(){
$("#message").html("<span style='color:green ! important'>Sending request.</br></br>");
}
});
});
});
</script>
A couple of small changes should get you up and running. First, get the value of the input with .val():
var content = $("#content").val();
You mention that you're checking to see if the submit button isset() but you never send its value to the PHP function. To do that you also need to get its value:
var submit = $('#subbutton').val();
Then, in your AJAX function specify the data correctly:
$.ajax({
type: "POST",
url: "xxx.php",
data: {content:content, subbutton: submit}
...
quotes are not needed on the data attribute names.
On the PHP side you then check for the submit button like this -
if('submit' == $_POST['subbutton']) {
// remainder of your code here
Content will be available in $_POST['content'].
Change the data atribute to
data:{
content:$("#content").val()
}
Also add the atribute error to the ajax with
error:function(e){
console.log(e);
}
And try returning a var dump to $_POST in your php file.
And the most important add to the ajax the dataType atribute according to what You send :
dataType: "text" //text if You try with the var dump o json , whatever.
Another solution would be like :
$.ajax({
type: "POST",
url: "xxxwebpage..ifyouknowhatimean",
data: $("#idForm").serialize(), // serializes the form's elements.
dataType:"text" or "json" // According to what you return in php
success: function(data)
{
console.log(data); // show response from the php script.
}
});
Set the data type like this in your Ajax request: data: { content: content }
I think it isnt a correct JSON format.

Categories

Resources