AJAX call inside Ckeditor widget's upcast function - ajax

I would like to use an AJAX call (via jQuery) to change the HTML of a widget during the upcast function of a CKEditor widget. Here is what I have tried:
CKEDITOR.plugins.add('mywidget', {
requires: 'widget',
icons: 'mywidget',
init: function (editor) {
editor.widgets.add('mywidget', {
button: 'My widget',
template: '<p class="mywidget">Initial text.</p>',
allowedContent: 'p(!mywidget)',
upcast: function (element) {
if (element.hasClass('mywidget')) {
element.setHtml('After upcasting.');
$.get('http://example.com')
.done(function (response) {
element.setHtml('Updated text after AJAX.');
});
return true;
}
return false;
},
});
}
});
When the widget is first instantiated, as expected, it says:
"Initial text."
After I click "Source" and then click "Source" again, as expected again, the text has changed to:
"After upcasting"
However, when the AJAX request comes back, the text does not change to "Updated text after AJAX".
Does anyone know how I can get at the element from inside the AJAX callback? If it is too late to access the element from the AJAX callback, is there any way to use the response from the callback to retroactively edit the markup of the already-upcasted widget? Thank you!

$.get() is asynchronous so the .done part is called after the upcasting had already completed. Use $.ajax() instead and set async: false.
The modified widget code:
CKEDITOR.plugins.add('mywidget', {
requires: 'widget',
icons: 'mywidget',
init: function (editor) {
editor.widgets.add('mywidget', {
button: 'My widget',
template: '<p class="mywidget">Initial text.</p>',
allowedContent: 'p(!mywidget)',
upcast: function (element) {
if (element.hasClass('mywidget')) {
element.setHtml('After upcasting.');
$.ajax({
url: 'http://www.example.com',
async: false,
success: function (result) {
element.setHtml('Updated text after AJAX.');
}
});
return true;
}
return false;
},
});
}
});

Related

add code to ajax post form submit

i have the next code
$(document).ready(function () {
$("#productfilter").validate({
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "listproresult_core.php",
data: $("#productfilter").serialize(),
beforeSend: function () {
$("#contentincore").html("<img src='../loading_core/loading animated/loader.gif'class='clock' border='0' />");
},
success: function (result) {
$("#contentincore").html(result);
}
});
}
});
});
and i wish add the next functions inside and that the results of the form, the links are implemented inside the load function results
$('#contentincore a').click(function (e) {
("#contentincore").on("click", "a:not(.minlink)", function (e) {
("#contentincore").load($(this).attr("href"));
e.preventDefault();
});
});
To bind functions to content that is loaded in with ajax, you have to use .on(). Here's a live example: http://jsfiddle.net/GMDah/ (check the console) When pressing the top link, "pressed" will be printed in the console. When the bottom link with class .minlink is pressed, the code in here is not executed.
The code being:
$("#contentincore a:not(.minlink)").on("click", function (e) {
console.log("pressed");
});
Also, don't forget putting the $-sign or jQuery before your brackets, you seem to have missed a few.

Close Jquery dialog based on resulted validation

I am loading a PartialView into a Jquery UI dialog and if something went wrong during the post method I reload the PartialView into the dialog again ( ModelState errors for example ) . At this point my ajax sumbit doesn't work anymore. It justs redirect me and it should not.
What is wrong in my code ? Here is what I have tried :
$('#editdialog').dialog({
autoOpen: false,
width: '900px',
modal: true,
open: function (event, ui) {
$(this).load('Controller action', function (html) {
$('#incarcerationForm').submit(function () {
$.ajax({
url: 'Controller action',
data: $("#myForm").serialize(),
type: "POST",
success: function (data) {
$('#editdialog').html(data);
$.validator.unobtrusive.parse($("#myForm"));
if ($("#myForm").valid()) {
GetDetails(#Model.FormModel.ID);
$('#editdialog').dialog('close');
console.log("myForm was edited successfully");
return false;
}
return false;
},
error: function (data) {
$('#editdialog').html(data);
console.log("error at edit myForm");
return false;
}
});
return false;
});
return false;
});
}
});
And my [HttpPost] Controller action :
public ActionResult Create(Mymodel viewModel)
{
return CheckValidBusiness(() =>
{
viewModel.Save(viewModel.FormModel); return true;
})
.Valid(() => PartialView(viewModel))
.Invalid(() => PartialView(viewModel));
}
Replace:
$('#incarcerationForm').submit(function () {
with:
$(document).on('submit', '#incarcerationForm', function () {
so that you subscribe to the submit event of the form in a lively manner which will be resilient to DOM changes. Take a look at the .on() method for more information.

Unable to serialize a form that contains a tinymce editor for an Ajax call

I'm trying to post a form that contains an instance of tinyMCE editor to an action method using AJAX. My View:
<script src="#Url.Content("~/Scripts/tinymce/tiny_mce.js")" type="text/javascript"></script>
<div>
<fieldset>
#using (Html.BeginForm("SubmitNewTRForm", "LaboratoriesOrdersGrid", FormMethod.Post,
new {enctype = "multipart/form-data", #id = "newTrUploadForm" }))
{
<div style="overflow: hidden;width: 763px; height:312px; border: black solid thin;">
#Html.TextAreaFor(model => model.TestSummary, new {#class="TestSummaryEditor"})
</div>
}
</fieldset>
</div>
In the same view I instantiate the editor:
$(document).ready(function () {
tinyMCE.init({
directionality: "rtl",
width: "760",
height: "300",
language: 'fa',
// General options
mode: "textareas",
theme: "advanced",
plugins: "autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
// Theme options
theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect,|,sub,sup,|,charmap,iespell,advhr,|,print,|,fullscreen",
theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,cleanup,|,insertdate,inserttime,preview,|,forecolor,backcolor,|,insertlayer,moveforward,movebackward,absolute,|,blockquote,pagebreak,|,insertfile,insertimage,|,visualchars,nonbreaking,template",
theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,ltr,rtl,|,cite,abbr,acronym,del,ins,attribs",
theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
theme_advanced_statusbar_location: "bottom",
theme_advanced_resizing: true,
// Skin options
skin: "o2k7",
skin_variant: "silver",
add_form_submit_trigger: false,
// Example content CSS (should be your site CSS)
content_css: "css/example.css",
// Drop lists for link/image/media/template dialogs
template_external_list_url: "js/template_list.js",
external_link_list_url: "js/link_list.js",
external_image_list_url: "js/image_list.js",
media_external_list_url: "js/media_list.js",
// Replace values for the template plugin
template_replace_values: {
username: "Some User",
staffid: "991234"
}
});
});
ANd my AJAX call:
$("form").live('submit', function (e) {
tinyMCE.triggerSave(true, true);
e.preventDefault();
var form = $("#newTrUploadForm");
if (form.valid()) {
$.ajax({
url: '#Url.Action("SubmitNewTRForm")',
data: form.serialize(),
type: 'POST',
error: function (xhr, textStatus, exceptionThrown) {
$("#errorDIV").html(xhr.responseText);
},
success: function (data) {
if (data.success) {
}
else {
}
}
});
}
});
And my AJAX call always returns an error whenever the tinyMCE editor is on the form, removing tinyMCE solves the problem, but why is this happening? I know this issue has been addresses on SO a couple of times already but I've tried all the proposed solutions and none seem to work for me, plus those solutions are somewhat outdated. During serialization in my AJAX call, i get this error:
[MissingMethodException: No parameterless constructor defined for this object.]
Any ideas?
The error I posted and the tinyMCE problem happen to be totally unrelated. The tinyMCE problem was fixed by saving the contents after preventing the default action of the button click, basically changing my AJAX call from:
$("form").live('submit', function (e) {
tinyMCE.triggerSave(true, true);
e.preventDefault();
to:
$("form").live('submit', function (e) {
e.preventDefault();
tinyMCE.triggerSave(true, true);
and the form serialzed properly and the conents of teh editor sent to the action flawlessly.
Totally irrelevant to this question, but that error posted was caused by setting my model property's type as SelectList and the form posting a SelectListItem.
Your error indicates that the model you are trying to bind to in your controller action needs a constructor like
public yourModel
{
public yourModel()
{
//your logic here
}
}
It also doesn't look like you have a 'form' in your view to post back in the first place. I have a feeling that there are multiple errors on top of each other and the paramterless constructor is just the first one.

Displaying a message in a dialog box using AJAX, jQuery, and CakePHP

I have a form, and when users submit this form, it should pass the data along to a function using AJAX. Then, the result of that is displayed to the user in a dialog box. I'm using CakePHP (1.3) and jQuery to try and accomplish this but I feel like I'm running into the ground.
The form will eventually be used for uploading images with tags, but for now I just want to see a message pop up in the box..
The form:
<?php
echo $this->Form->create('Image', array('type' => 'file', 'controller' => 'images',
'action' => 'upload', 'method' => 'post'));
echo $this->Form->input('Wallpaper', array('type' => 'file'));
echo $this->Form->input('Tags');
echo $this->Form->end('Upload!');
?>
The AJAX:
$(document).ready(function() {
$("#ImageUploadForm").submit(function() {
$.ajax({
type: "POST", url: "/images/upload/",
data: $(this).serialize(),
async: false,
success: function(html){
$("#dialog-modal").dialog({
$("#dialog-modal").append("<p>"+html+"</p>");
height: 140,
modal: true,
buttons: {
Ok: function() {
$(this).dialog('close');
}
}
})
}
});
return false;
});
});
NOTE: if I put $("#dialog-modal").dialog({ height: 140, modal: true }); OUTSIDE of the $.ajax but inside the $("#ImageUploadForm").submit(function() { and comment out the $.ajax stuff, I WILL see a dialog box pop up and then I have to click it for it to go away. After this, it will not forward to the location /images/upload/
The method that AJAX calls:
public function upload()
{
$this->autoRender = false;
if ($this->RequestHandler->isAjax())
{
echo 'Hi!';
exit();
}
}
$this->RequestHandler->isAjax() seems to do either absolutely nothing, or it is always returning false. I have never entered an if statement with that as the condition.
Thanks for all the help, if you need more information let me know.
Try this:
$(document).ready(function(){
$.ajax({
type: "POST", url: "/images/upload/",
data: $(this).serialize(),
async: false,
success: function(html){
//First you must append to div:
$("#dialog-modal").append("<p>"+html+"</p>");
$("#dialog-modal").dialog({
height: 140,
modal: true,
buttons: {
Ok: function() {
$(this).dialog('close');
}
}
}); //dialog
}//success
});//ajax
Note the first sentence:
$("#dialog-modal").append("<p>"+html+"</p>");
it can not be a propertie. You must pass an object as a parameter to dialog() function so properties or member of an object looks like:
{
height:140,
buttons:{},
anotherPropertie: 'value'
}
If you call to dialog() function after ajax(), the dialog will be empty because will execute before success() function declared inside ajax().

jQuery - why ajaxForm bypasses the validation procedure?

I have the following code snippet:
$(document).ready(function () {
// bind 'regFormBody' and provide a simple callback function
$('#regFormBody').ajaxForm(function() {
alert("Thank you for your comment!");
});
// validate the #regFormBody form when it is submitted
$("#regFormBody").validate({
submitHandler: function(form) {
alert('form is submitted');
},
rules: {
...
},
messages: {
...
}
});
}
The problem is that after I add the
// bind 'regFormBody' and provide a simple callback function
$('#regFormBody').ajaxForm(function() {
alert("Thank you for your comment!");
});
The form validation doesn't work at all. I always see the message alert('form is submitted') even without entering any information to form.
May you tell me how to solve this problem?
Thank you
You can expand your options object for .ajaxForm(), like this:
$('#regFormBody').ajaxForm({
beforeSubmit: function() {
return $('#regFormBody').valid();
},
success: function() {
alert('Thanks for your comment!');
}
});
This will kick off validation before submitting, and if it's not .valid() it'll stop the submit from happening like you want.

Resources