CkEditor conflict with jquery form - javascript

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

Related

How to get FormData object and submit the form data by ajax use asp.net mvc

I would like to get a form object and submit the data to server with a button click in Asp.net MVC.
This is my HTML code:
<form method="post" form-sync="ajax">
#Html.Hidden("InvtId", item.InvtId)
</form>
This is my JS code:
$(document).on("click", "[form-sync='ajax']", function() {
var formdata = new FormData($(this).closest("form")),
url = $(this).data("url");
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(response) {
alert(response.message);
return false;
},
});
});
This is my MVC code:
var data = Request["InvtId"];
The problem is the data variable is empty
Any help would be greatly appreciated, thanks.
Your form-sync attribute is non standard so your HTML is invalid. You should make that a data attribute.
You need to hook to the submit event of the form, not click.
The FormData constructor expects a DOMElement, not a jQuery object as you are currently passing to it. You can just give the this reference as that is the DOMElement.
The form has no data-url attribute. I assume you want the action property instead, which will default to the current page as you haven't provided one explicitly.
The return statement in your success handler is redundant.
You need to stop the standard form submission (as you're submitting via AJAX instead) by calling preventDefault() on the passed submit event.
Here's a complete example with all the above fixes:
<form method="post" data-form-sync="ajax">
#Html.Hidden("InvtId", item.InvtId)
</form>
$(document).on('submit', '[data-form-sync="ajax"]', function(e) {
e.preventDefault();
$.ajax({
url: this.action,
type: 'post',
data: new FormData(this),
processData: false,
contentType: false,
success: function (result) {
alert(result.message);
},
});
})
The problem is that you are passing in a jQuery element and NOT a DOM element.
For the FormData to actually return what you expect, you need to pass in a DOM element to its constructor.
Here, try this instead:
var formdata = new FormData($(this).closest("form")[0]);
Another problem is that the form has no data-url attribute.
Use the action property instead, it will return the url of the current page if you have not given a url yourself.
Here, use this instead:
var url = this.action; // or $(this).prop('action');
HTML
< button type="button" class="btn btn-primary"
onclick="saveData()">Save</button>
JS Code
Inside of function saveData()
var formData = new FormData();
get values with serializeArray
var formulario = $("#miFormulario").serializeArray();
if there are extra data or files
formulario.push({ "name": fileName, "value": file });
add information to formData
formulario.forEach((d) => {
formData.append(d.name, d.value); });
ajax request
$.ajax({
timeout: 0,
url: "/InfoController/savingInfo",
method: "post",
data: formData,
contentType: false,
processData: false,
success: function (result) { //do something }
});
Controller
[HttpPost] public JsonResult savingInfo() {
if (Request.Files.Count > 0)
{ ... }
var data = Request.Form;
var valor1 = data["dato1"];
return Json(true);
}

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

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

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.

Clearing a form field after using append to ajax

I am using an ajax function to append a comment to a a list of existing comments. I have the append to working, but after I append the comment is still in the text field. I am trying to figure out how to clear the text field after the append to. Any pointers on how to go about this would be greatly appreciated.
$('.new_question_comment').on('submit', function(event) {
event.preventDefault();
$form = $(event.currentTarget);
$.ajax({
type: "POST",
url: $form.attr('action'),
data: $form.serialize(),
dataType: "json",
success: function(data) {
$form.siblings().first().append("<h6>"+ "-" + data.body + "</h6><br>")
}
});
});
In your success callback function add the following after you append the data:
$form.each (function() { this.reset(); });
This will reset the form values back to their default.
jsFiddle example
You could also use the native JavaScript form reset function:
$form[0].reset();
If the specific text field has an ID, say "text", clear it directly:
document.getElementById('text').value='';
You can clear the entire form too:
document.getElementById('form').reset();

PHP $_POST not working with jquery

i am using this jquery code:
<script type="text/javascript">
$(document).ready(function () {
$("#message").hide();
$("#please_wait_box").hide();
$("#editcustomer").submit(function (e) {
$("#message").hide();
$("#please_wait_box").show();
e.preventDefault();
dataString = $("#editcustomer").serialize();
$.ajax({
type: "POST",
url: "editcustomer_go.php",
cache: false,
data: dataString,
success: function (res) {
$("#please_wait_box").hide();
$("#message").html(res);
$('#message').fadeIn('slow');
if (res.indexOf("success") != -1) {
window.location.href = res.substr(8);
}
}
});
});
});
</script>
to submit forms without changing the page.
then the editcustomer_go.php echoed results display in:
<div id="message" class="messagebox"></div>
<div id="please_wait_box" class="messagebox">Please Wait...</div>
i am using tinymce for text editors - its working okay but when the data is posted in the PHP, its not seeing the changed data in the tinymce text editor - it has to be plain text.
how can i get round this?
To grab the data from TinyMCE you need to use their getContent() function.
So in your case it'd be
// Grab a reference to the editor
var ed = tinyMCE.get('tinymceeditorname');
// Get it's content
var editordata= ed.getContent();
... and then just pass editordata along with the rest of the form as the AJAX call data.

Categories

Resources