single Ajax Post request not working in IE - javascript

I have some code that uses jquery to create dialogs from some hidden forms in my html:
$("#editdeletediv").load().dialog(
{ //Set options for the dialog here
title: 'Edit/Delete log',
modal: true,
autoResize:true,
maxWidth: 600,
minWidth: 500,
buttons: {
Delete: function(){
$('#confirmdelete').load().dialog(
{ //Set options for the dialog here
title: 'Confirm deletion',
modal: true,
autoResize:true,
maxWidth: 300,
minWidth: 250,
buttons: {
Yes: function(){
$.ajax({
url: 'removelog',
type: "POST",
data: { id: calEvent.id},
dataType: "json",
success:function(response){
window.location.href = response;
}
});
},
No: function(){
$(this).dialog('close');
}
}
});
},
Save: function(){
var input = $("<input>")
.attr("type", "hidden")
.attr("name", "id").val(calEvent.id);
$('#editdeleteform').append($(input));
var formdata = new FormData($("#editdeleteform")[0]);
$.ajax({
url: 'updatelog',
type: 'POST',
data: formdata,
async: false,
success: function (response) {
window.location.href = response;
},
cache: false,
contentType: false,
processData: false
});
}
}
});
This all works in chrome and firefox, but in IE it's a different matter.
The ajax post to 'updatelog' doesn't seem to work in IE but the post to 'removelog' does.
Does anyone know what might be the issue here, I think it might be the,
var formdata = new FormData($("#editdeleteform")[0]);
but I need that formdata variable as the fields I'm passing to the post might be different in the future (I might dynamically create more html elements), so I need a way to get everything from that form without hard coding it into my javascript
EDIT: figured out how to get a console open in internet explorer and now I know for sure it's the FormData where the problem is arising:
SCRIPT5009: 'FormData' is undefined
Does anyone know of an alternative that works in chrome, firefox and IE or does anyone know how I can work around this problem for IE?
EDIT: I decided it's more trouble than it's worth, this is for an intranet site solution so spending too much time on this would be a waste (I can just require my users to use specific browsers/versions if they want full functionality)
So I just did this:
if(typeof FormData !== 'undefined'){
var formdata = new FormData($("#editdeleteform")[0]);
}
else{
var formdata = {
'id' : calEvent.id,
'editdate' : $("#editdate").val(),
'editcomment' : $("#editcomment").val(),
'editworkhours' : $("#editworkhours").val(),
'editdoctorsnote' : ''
};
}

FormData isn't compatibile with ie 7-9 see: https://developer.mozilla.org/en-US/docs/Web/API/FormData

var formdata = $("#editdeleteform").serialize()
Try this to send form data to updatelog. This may helps you.

I decided it's more trouble than it's worth, this is for an intranet site solution so spending too much time on this would be a waste (I can just require my users to use specific browsers/versions if they want full functionality)
So I just did this:
if(typeof FormData !== 'undefined'){
var formdata = new FormData($("#editdeleteform")[0]);
}
else{
var formdata = {
'id' : calEvent.id,
'editdate' : $("#editdate").val(),
'editcomment' : $("#editcomment").val(),
'editworkhours' : $("#editworkhours").val(),
'editdoctorsnote' : ''
};
}

Related

CkEditor conflict with jquery form

I am using CKEditor and trying to submit my form with jquery but I have a conflict
Jquery
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
console.log(new FormData(this))
$('.loading-container').show();
$.ajax({
url: "store-course-teacher",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$('.loading-container').hide()
if(data.status == 'done')
{
$('#form').hide();
$('#add-section').show();
$('#course-title').html($('#title').val());
$('.course-id').val(data.course_id)
}
}
});
}));
});
and from my controller I dumped the result and all text area with ckeditor is NULL
I am trying to be clear as possible but that's all I got
I believe with ckeditor, you have to get the HTML from the text editor like this:
var data = CKEDITOR.instances.editor1.getData();
So before calling your ajax, perhaps set data to a hidden input in your form so that your new FormData(this) remains intact?
var data = CKEDITOR.instances.editor1.getData();
$('#MyHiddenInput').val(data);
More info here
best way to send ckEditor with the from was updating the ckEditor instanes
for (instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
}
I found the solution here

FormData not appending the data

I am just scratching my head, and do not understand, what happens here. This code has worked both in production and in my developer environment.
Here is the reference, I do exactly the same.
var fileToUpload = $('#productsFile').prop('files')[0];
var formData = new FormData();
formData.append('file', fileToUpload);
formData.append('action', 'csvUpload');
formData.append('siteId', $('#siteId').val());
console.log($('#siteId').val());
console.log(fileToUpload);
console.log(formData);
The output in the console:
10
File { name: "H00447.PriceList.csv", lastModified: 1464960003935, lastModifiedDate: Date 2016-06-03T13:20:03.935Z, size: 14859917, type: "application/vnd.ms-excel" }
FormData { }
Object has created, the values are fine, so what could be the problem here? Tested with Firefox Developer Edition.
EDIT
Here is the code to send the data to the ajax:
$.ajax({
url: ajaxUrl, // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post'
}).done(function (msg) {
if (parseInt(msg) !== 0) {
alert(msg);
} else {
location.reload();
}
}).fail(function (msg) {
alert('Error: ' + msg.statusText);
});
In the ajax.php I just var_dump($_REQUEST); and shows me an empty array.
EDIT2
I tried it on another localhost environment, I've just added some random keys and values, and everything was fine, even in FF and Chrome.
So I came back to this issue, and just commented out the fileToUpload section.
The other two value was in the $_POST. If I add the file, the $_POST will be empty.
Something wrong with the file.
EDIT3
No I just tested it with a small file, what is about 3-4Kb, and everything is fine. My production file is 14Mb, I think that will be the problem.
SOLUTION
This whole thing because of the filesize. I incrased the post limit, and max file size in php.ini and viola. Things are works. Thank you for your help.
Try this to log keys and values:
formData.forEach(function (value, key) {
console.log(key, value);
});
The data is send but you need to use POST not GET:
var formData = new FormData();
formData.append('action', 'csvUpload');
var xhr = new XMLHttpRequest();
xhr.open("POST", "ajax.php", true);
xhr.send(formData);

What is wrong with this piece of code

This piece of code of a form submission is working perfectly in Google chrome meanwhile in Firefox it does not. Can somebody tell me what is wrong with my code?
$(document).ready(function(e){
/*sending post data to php script */
$("form[id='postForm']").submit(function(e){
e.preventDefault();
var text = $('#postText').val();
var formData = new FormData($(this)[0]);
formData.append('postText', text );
$.ajax({
url: "home.php?module=facebook&action=post-news&method=script",
type: "POST",
data: formData,
cache: false,
processData: false,
contentType: false,
context: this,
success: function (msg) {
window.location.reload();
}
});
e.preventDefault();
});
$('input:file').on('change', function () {
var formData = new FormData($(this)[0]);
//Append files infos
jQuery.each($(this)[0].files, function(i, file) {
formData.append('imageToPost[' + i + ']', file);
});
});
});
Quickly checked console:
TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
The problem is here:
$('input:file').on('change', function () {
var formData = new FormData($(this)[0]); <--- HERE
this is not a form, but input element. Not sure what you wanted to achieve here, but probably serialize your form. For this you need to do:
var form = $("#postForm")[0];
var formData = new FormData(form);
And then append your file.
Hope this helps.

JQuery FormData in IE - changing to JQuery Form plugin

I have a form which has a lot of inputs including two file upload fields. I had everything working with FormData but I have since come to realise that
this does not work in IE8 or IE9 (and I need it too). As such, I am probably going to switch and use the JQuery Form plugin instead.
I wont show the html form because it is a lot of code, but its just a simple form with a lot of fields really. What I do first is some validation using the JQuery Validate plugin. As you can see below, all the FormData stuff is done in the submitHandler.
$(function () {
var validator = $("#my-form").validate({
errorContainer: "#validation-results",
errorLabelContainer: "#validation-results",
errorElement: "li",
groups: {
fileGroup: "fileOne fileTwo"
},
rules: {
//All the appropriate rules
},
messages: {
//All the appropriate messages
},
submitHandler: function (form) {
formData = new FormData(),
params = $(form).serializeArray(),
fileOne = $(form).find('[name="fileOne"]')[0].files,
fileTwo = $(form).find('[name="fileTwo"]')[0].files;
if(fileOne.length != 0) {
$.each(fileOne, function(i, file) {
formData.append('fileOne-' + i, file);
});
}
if(fileTwo.length != 0) {
$.each(fileTwo, function(i, file) {
formData.append('fileTwo-' + i, file);
});
}
$.each(params, function(i, val) {
formData.append(val.name, val.value);
});
$.ajax({
type: "POST",
url: "php/process.php",
dataType: "json",
data: formData,
mimeType: "multipart/form-data",
contentType: false,
processData: false
}).done(function (response) {
});
return false;
}
});
});
My main question is how can I integrate the JQuery Form Plugin with the JQuery Validate code above? I presume I use the submitHandler above, but is it just a case of adding the following
to replicate what I currently have in my submitHandler?
$("#my-form").ajaxSubmit();
return false;
Any advice on how to combine the two would be great. My main aim is to get this working properly in IE.
Many thanks

Json response as tooltip value lookup for a jquery sparklines graph

I'm trying to use a json response as the tooltipValueLookups parameter in a sparklines graph, without success. The tooltip just keeps showing 0:5 and 1:8 instead of Mulder:5 and Scully:8
It works perfectly if I just declare the variable agents with the exactly same json:
var agents = {"names":{"0":"Mulder", "1":"Scully"}}
But evrything goes south when I try to do it with the server response, as intended. Could anyone tell me please, what am I doing wrong?
var agents = $.ajax({
url : "/ajaxAgents",
type : "get",
dataType: 'json'
});
Response: {"names":{"0":"Mulder", "1":"Scully"}}
$("#mini-chart").sparkline([5,8], {
type: 'bar',
height: '30px',
barWidth: 6,
barSpacing: 2,
barColor: '#0aa699',
tooltipFormat: '<span style="color: {{color}}">●</span> {{offset:offset}}: {{value}}',
tooltipValueLookups:{offset:agents.names},
negBarColor: '#0aa699'});
Thanks in advance.
EDIT
After a lot of coffee and swearing, I finally got it to work. Not a very elegant solution, I must admit.
First, I had to change the server-side php function to return a string, rather than json.
Then in the ajax call:
var response = $.ajax({
url : "/ajaxAgents",
type : "get",
dataType: 'text',
global : false,
async : false,
success : function(data){return data;}
}).responseText;
Then, parse the response and filter it:
var agents = $.parseJSON(response);
var filteredNames = $.map(agents.names, function(el) {
return el;
});
And finally, the sparklines function:
$("#mini-chart").sparkline(agentsData, {
type: 'bar',
height: '30px',
barWidth: 6,
barSpacing: 2,
barColor: '#0aa699',
tooltipFormat: '<span style="color: {{color}}">●</span> {{offset:offset}}: {{value}}',
tooltipValueLookups:{offset:filteredNames},
negBarColor: '#0aa699'});
#Hüseyin: Thanks for your assistance, it was very helpful.
Filter json with $.grep
var filteredNames = $.map(agents.names, function(el, i) {
return el;
});
And use in your function like;
tooltipValueLookups:{offset: filteredNames}
You can see demo here: jsfiddle
Note: If you are returning string from server, you need to use;
var agents = jQuery.parseJSON(response);

Categories

Resources