TinyMCE not being added to element on AJAX call - javascript

I'm having some issues applying TinyMCE onto the textarea element.
I have a page with a list of passengers. When you click a passsenger, AJAX is called and it displays info for the passenger, one field which happens to be a textarea element. My problem is that the first passenger (any passenger) you click on loads TinyMCE, but from here on out, it's just a normal textarea with no TinyMCE applied. I don't know what's happening. Here is the following code I have:
j$ = jQuery.noConflict();
j$(document).ready(function(e) {
tinyMCE.init({
mode : "textareas",
theme : "advanced",
theme_advanced_buttons1 : "bold, italic, underline, | ,bullist, numlist, | ,outdent, indent, | ,link, unlink, |, code",
relative_urls : false,
remove_script_host : false,
});
j$('.names strong').click(function(e) {
//Find passenger ID
var customer_ID = j$(this).closest('.passenger_Container').find("input[name='customer_ID']").val();
//Find placement of returned data
var insert_Data = j$(this).closest('.passenger_Container').find('.package');
j$.ajax({
type: "POST",
url: "/include/passenger_Detail.php",
data: { customer_ID_Data : customer_ID },
success: function(data) {
//get returned data and add into appropriate place
insert_Data.html(data);
var oldEditor = tinyMCE.get('notes');
if (oldEditor != undefined) {
tinymce.remove(oldEditor);
}
tinyMCE.execCommand('mceAddControl', false, 'notes');
//re-initialise WYSIWYG editor. Notes is the ID to re-initialize
/*tinymce.execCommand('mceRemoveControl',true,'notes');
tinymce.execCommand('mceAddControl',true,'notes');*/
}
});
});
});
<!-- content is displayed using PHP while loop -->
<div class="passenger_Container bottom-buffer">
<div class="names row">
<div class="col-xs-1 text-center">
<!-- Display checkbox -->
</div>
<div class="col-xs-4 col-sm-3">
<strong><?php echo $row['f_Name'].' '.$row['l_Name']; ?></strong> </div>
<div class="col-xs-3 hidden-xs">
<!-- display child names -->
</div>
<div class="col-xs-3">
<!-- Display order status -->
</div>
<div class="col-xs-1 col-sm-2">
<!-- Display form -->
</div>
</div>
<div class="package custom-well well-sm top-buffer">
<!-- passenger detail goes here. You will find the code in includes/passenger_Detail.php -->
</div>
</div>
<!-- end PHP while loop -->
I have left the examples I have tried to get TinyMCE to work. I have a sneaky suspicion bad coding practice is the culprit. Each of the textareas have an ID of #notes which I think is the cause. But looking at documentation I don't think tinyMCE lets you use classes to target textareas. Unless I have to loop through all textareas. I'm just spitballing here.
Please inform me if more info is required. Thanks again.

I ended up solving the issue but using a unique ID for each of the textarea elements. So instead of each textarea having the ID "notes", it is now "notes_unique customer_ID".
Following is my answer:
j$.ajax({
type: "POST",
url: "/include/passenger_Detail.php",
data: { customer_ID_Data : customer_ID },
success: function(data) {
//console.log("Returned data: "+data);
//get returned data and add into appropriate place
insert_Data.html(data);
notes = insert_Data.find('textarea').attr('id');
var oldEditor = tinyMCE.get('notes_'+customer_ID);
if (oldEditor != undefined) {
tinymce.remove(oldEditor);
}
tinyMCE.execCommand('mceAddControl', false, 'notes_'+customer_ID);
}
});

Related

Drag and sort divs using jQuery and output html code

What i'm doing:
I'm creating a Mailings Generator. This simply is an application, that generates Mailings (An E-mail with some of my products as advertisement) from a Mailing Template.
What i want:
I want to be able to order the divs generated in my Mailing Generator and create a new file with the new order.
Let me show you the concept:
$( "#sortable" ).sortable({
connectWith: ".connectedSortable",
stop: function(event, ui) {
$('.connectedSortable').each(function() {
result = "";
($(this).sortable("toArray"));
$(this).find("div").each(function(){
result += $(this).text() + "<br />";
});
$("."+$(this).attr("id")+".list").html(result);
});
}
});
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<div id="sortable" class="connectedSortable">
<div class="companyLogo">
<!-- logo here...-->
</div>
<div class="productBox1">
Product Name: 1
Price: 10,00
<!-- etc...-->
</div>
<div class="productBox2">
Product Name: 2
Price: 20,00
<!-- etc...-->
</div>
<div class="productBox3">
Product Name: 3
Price: 30,00
<!-- etc...-->
</div>
<div class="productBox4">
Product Name: 4
Price: 40,00
<!-- etc...-->
</div>
<div class="footerInformation">
<!-- Footer Info Here...-->
</div>
</div>
<div class="sortable list"></div>
So here's a quick example of how the mailing could look when generated. (Please run the code snippet)
I want to drag the divs and sort them the way i'd like.
After i sorted them i want to create a NEW file but this time display the divs in the order i sorted the last one.
Question:
When i move the div's, i get the new order as output. What i want is it to output all the html code. This way i want to create a new file with the new order.
If there is any way to do this and you know how, please consider helping me a little. Please correct me in any way possible. it helps me learn!
If i wasn't clear enough, please let me know.
Could you be a little more specific? Send the modified HTML back to the webserver using ajax, how would i do that?
You could for example add a Button. Then when u are done sorting your articles in the list you will click that button. The eventhandler attached to that button will then extract the html that you want to save to a file (htmlToSend) from the $('#sortable') element and send it to a certain server_address.
$( "#sortable" ).sortable({
connectWith: ".connectedSortable",
stop: function(event, ui) {
$('.connectedSortable').each(function() {
result = "";
$(this).sortable("toArray");
$(this).find("div").each(function(){
result += $(this).text() + "<br />";
});
$("."+$(this).attr("id")+".list").html(result);
});
}
});
$('#send').on('click', function() {
const htmlToSend = $('#sortable').html();
alert('SENDING HTML: ' + htmlToSend);
$.ajax({
method: 'POST',
url: '<SERVER_ADDRESS>', //CHANGE SERVER_ADDRESS to the address of the script that will handle the html (save it to file or send it via email)
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({ html: htmlToSend }),
success: function(response) {
//code to execute if saving on server was successful
},
error: function(err){
//code to execute if saving on server failed
}
});
});
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<div id="sortable" class="connectedSortable">
<div class="companyLogo">
<!-- logo here...-->
</div>
<div class="productBox1">
Product Name: 1
Price: 10,00
<!-- etc...-->
</div>
<div class="productBox2">
Product Name: 2
Price: 20,00
<!-- etc...-->
</div>
<div class="productBox3">
Product Name: 3
Price: 30,00
<!-- etc...-->
</div>
<div class="productBox4">
Product Name: 4
Price: 40,00
<!-- etc...-->
</div>
<div class="footerInformation">
<!-- Footer Info Here...-->
</div>
</div>
<input type="button" value="Send to Server" id="send">
On the serverside you will need to receive that data from the post-body of the http-request. For example on a php-server u would use file_get_contents('php://input') to receive that. But that is dependant on your serverside technology that you use. So let me know if u have problems with the serverside implementation.

AJAX response using HTML5 data attribute

I've a working env where I'm using AJAX response to fill in HTML elements.
for example AJAX response has two(or n) objects like this:
0:Object
id: "111"
Name: "abc"
1:Object
id: "112"
Name: "xyz"
Then, There already would be two(or n) divs with user class and HTML5 data-user containing the id in HTML
<div class='user' data-user='111'>
<div class='userId'data-userId='111> </div>
<div class='usernm' data-user='usernm'> </div>
</div>
<div class='user' data-user='112'>
<div class='userId'data-userId='112> </div>
<div class='usernm' data-user='usernm'> </div>
</div>
What I need is put those response values in this divs like this:
<div class='user' data-user='111'>
<div class='userId'data-userId='111> 111 </div>
<div class='usernm' data-user='usernm'> abc </div>
</div>
<div class='user' data-user='112'>
<div class='userId'data-userId='112> 112 </div>
<div class='usernm' data-user='usernm'> xyz </div>
</div>
What I'm currently doing (and is working) is using jQuery find (see below code) but now I'm suggested to put the responses using HTML5 data-.. attribute. I can't get around it, if someone can help up with it..
$.ajax({
type: 'GET',
url: '/url/goes/here',
dataType: "json",
success: function(data) {
$('.user').each(function(key, value){ //i need to remove .user and use data-user here (if possible)
$(value).find('.userid').text(data[key].id); //i need to put values using data attr instead of find
$(value).find('.usernm').text(data[key].name); //i need to put values using data attr instead of find
});
}
});
Data attributes are accessed by:
$(#id).data('userId');
or
$(#id).attr('data-userId');
and to set a value in that data attribute:
$(#id).data('userId', 'value');
or
$(#id).attr('data-userId', 'value');

jQuery modal not show name after close and open

I create my custom modal window where i show image and that image contain comments and owner name. When i click on some image modal is opened and show big image, author name, comments etc... Problem is when i close current modal and opent it again name does not exist. But first time when i open modal name is there but only when i close that window and opent it again name does not exist. Check screenshots.
I try to debug it with firebook console and GET response return real name but that name is not rendered after closing and opening.
To prview image i use this code:
preview: function() {
$('body').on('click', '#open-picture-modal', function (e) {
e.preventDefault();
$("#photo_preview").show();
var $this = $(this);
var guid = $this.data('guid');
var photo_id = $this.data('id');
$.ajax({
method: 'post',
dataType: 'json',
url: baseurl + '/photo/preview',
data: {'photo_id': photo_id},
success: function(data) {
Photo.photo_author_meta(photo_id);
$(".pleft").html('<img class="fileUnitSpacer" src="'+ $this.data('href')+data['photo_name']+'">');
}
});
//window.history.pushState(null, null, pic_url);
// $(".image-source").attr("src", $this.data('href'));
});
},
// Close image preview modal
close: function() {
$("body").on("click", ".close", function(e) {
e.preventDefault();
$('#photo_preview').hide();
$('#photo_preview .pleft').html('empty');
$('#photo_preview .pright').html('empty');
});
},
// Show photo author meta(name, date created, etc..)
photo_author_meta: function(pid){
$.ajax({
method: "post",
dataType: 'json',
url: baseurl + '/photo/photo_details',
data: {'post_id': pid},
success: function(data) {
$("h4.photo-author-full-name").html(data['account_firstname'] +' '+ data['account_lastname']);
}
});
},
And here is modal where i append and set html
<div id="photo_preview" style="display:none">
<div class="photo_wrp">
<span class="pull-right close fa fa-times"> </span>
<div style="clear:both"></div>
<div class="pleft"></div>
<div class="pright">
<div class="photo-author-meta">
<div class="media">
<a href="#" class="media-left">
<img alt="64x64" data-src="holder.js/64x64" class="media-object" style="width: 64px; height: 64px;" src="test.png" data-holder-rendered="true">
</a>
<div class="media-body photo-author-name-box">
<div class="photo-author-name">
<h4 class="media-heading photo-author-full-name"></h4>
</div>
<div class="photo-datetime-box">
<div class="photo-date-posted"> Objavljeno: </div>
</div>
</div>
</div>
</div> </div>
<div style="clear:both"></div>
</div>
</div>
Like u can see on first image i have firstname and lastname in modal.
On second image i open again the some modal but name and surname does not exist. But check firebug console, data exist but not rendered.
Your close method is removing the HTML that renders the meta data.
$('#photo_preview .pright').html('empty');
That line is emptying all the HTML within . So, when photo_author_meta() is called a subsequent time after closing, h4.photo-author-full-name no longer exists.
You have various things:
1 - You are messing with .html() and .empty():
$('#photo_preview .pleft').html(); // or .empty()
2 - As you delete all the content from #photo_preview .pright, when you do:
$("h4.photo-author-full-name").html(data['account_firstname'] +' '+ data['account_lastname']);
This element don't exist. You could create it, or not empty all the div content.
You could change this:
$('#photo_preview .pright').html(); // or .empty()
to
$('h4.photo-author-full-name').html(); // or .empty()
In order to no delete the element, only the content on it.

MVC display partial view on navigation bar click

I want to display the partial view, when I click on navigation bar click. I have a view which contains left side menu. when user click on navigation bar item, appropriate view should display.
I am not getting how can I implement such view?
Manage.cshtml
<div class="row">
<div class="col-xs-12">
<div class="page-header">
<h1>My Account</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-3">
<ul class="nav nav-pills nav-stacked nav-stacked-extended">
<li class="active">
<a id="A3" target="_self" runat="server" href="#Url.Action("Contactinfo", "Account")">Contact Info</a>
</li>
<li class="">
<a id="A4" target="_self" runat="server" href="#Url.Action("changePassword", "Account")">Password</a>
</li>
</ul>
</div>
<div class="col-xs-9 ng-scope" data-ng-view="">
<div class="row row-gap-medium ng-scope">
#Html.Partial("Contactinfo")
</div>
</div>
</div>
In above code, I have created left side menu i.e contactinfo, changepassword etc. when Manage.cshtml load first time I want to display Contactinfo view. When user click on password menu, contactinfo get's changed with changedpassword page. Please check following screen shot.
Here in above image you can see left side menu and appropriate page. What I want when user click on password, view changed to password page. Currently it shows contact info page. How can I do this?
i think you should render partial through JavaScript.
Let's say you have <div id="partialView"></div>
Then you should run Ajax query when user clicked on link.
Something like:
$.ajax({
url: $(this).data('yourUrl'),
type: 'GET',
cache: false,
success: function(result) {
$('#partialView').html(result);
}
});
Took me a little while to figure this out too.
Essentially, you want your Controller action to return a partial view, then use Ajax to load that returned partial view.
JavaScript / Ajax
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: 'POST',
data: { 'viewName': 'password' },
success: function (data) {
$('#partial-container').html(data);
}
});
Controller return type
Public ActionResult GetView(string viewName)
{
return PartialView(viewName, model);
}
Ideally, change your HTML so it's easier to reference the div container where you'd like to load the partial
<div class="col-xs-9 ng-scope" data-ng-view="">
<div class="row row-gap-medium ng-scope">
<div id="partial-container">#Html.Partial("Contactinfo")</div>
</div>
</div>
In your requirement just make partial Views of the links present in your left side bar and when user clicks on a specific option in left side bar then just load a appropriate partial view from ajax call using jquery and just replace html of right side bar with the html coming from ajax call.
Give your left side menues unique id and then :
A Demo :
$(document).ready(function(){
$("#menu1").click(function(e){
e.preventDefault();
$.ajax({
url: "/MyController/getdata",
type: 'GET',
datatype: 'html',
data: { },
success: function (data) {
$("#div1").html('');
$("#div1").html(data);
});
});
});
Controller(MyController) :
[HttpGet]
Public ActionResult getdata(string dropval)
{
//bind model here
return PartialView("mypartialview",model)
}
try This JS for Clickevent
$(document).on('click', '#anCalcBtn', function () {
$('#anCalcDetail').load('/Home/Contactinfo/');
});
If I am not wrong you are trying to do like This

Uncaught TypeError: Cannot read property 'x' of undefined Morris.js

I'm going nuts and I can't figure out what is causing this error.
My Javascript:
<script>
$(document).ready(function() {
var jqxhr = $.getJSON("rest/scriptruns/VeloxMorgana", function() {
//VeloxMorgana.setData('[{"period":"2014-07-15","VeloxMorgana":1},{"period":"2014-07-16","VeloxMorgana":47}]');
});
jqxhr.complete(function() {
if ($('#VeloxMorgana').length) {
var week_data = jqxhr;
var VeloxMorgana = Morris.Line({
element : 'VeloxMorgana',
data : week_data,
xkey : 'period',
ykeys : ['VeloxMorgana'],
labels : ['VeloxMorgana'],
events : ['2014-07-10', '2014-07-17']
});
}
});
});
</script>
My HTML
<!-- Widget ID (each widget will need unique ID)-->
<div class="jarviswidget" id="wid-id-7" data-widget-editbutton="false">
<!-- widget options:
usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false">
data-widget-colorbutton="false"
data-widget-editbutton="false"
data-widget-togglebutton="false"
data-widget-deletebutton="false"
data-widget-fullscreenbutton="false"
data-widget-custombutton="false"
data-widget-collapsed="true"
data-widget-sortable="false"
-->
<header>
<span class="widget-icon"> <i class="fa fa-bar-chart-o"></i> </span>
<h2>Time Graph</h2>
</header>
<!-- widget div-->
<div>
<!-- widget edit box -->
<div class="jarviswidget-editbox">
<!-- This area used as dropdown edit box -->
</div>
<!-- end widget edit box -->
<!-- widget content -->
<div class="widget-body no-padding">
<div id="VeloxMorgana" class="chart no-padding"></div>
</div>
<!-- end widget content -->
</div>
<!-- end widget div -->
</div>
<!-- end widget -->
It loaded when I statically set the data, but when I use JSON it just freaks.
Here is the JSON it loads in when I call it using the ajax json feature and the load data (i've tried just putting it straight into the data from finishing the json request, same result).
[
{
"period":"2014-07-15",
"VeloxMorgana":1
},
{
"period":"2014-07-16",
"VeloxMorgana":47
}
]
The jqxhr is just the promise object for your XHR request, it doesn't actually contain the data that was received.
Since you don't really deal with failure at all, I could recommend just using the success callback straight away:
$.getJSON("rest/scriptruns/VeloxMorgana", function(data) {
if ($('#VeloxMorgana').length) {
Morris.Line({
element : 'VeloxMorgana',
data : data,
xkey : 'period',
ykeys : ['VeloxMorgana'],
labels : ['VeloxMorgana'],
events : ['2014-07-10', '2014-07-17']
});
}
});
Also, the documentation states:
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8.

Categories

Resources