I am trying to make an admin page using AJAX so when the client updates information in the CKEDITOR it doesn't have to take him to a new page. Getting data from input fields are easy enough using the .val() function, but because textareas are not updated on the fly, I can't use that same function. Heres as far as I got:
// this replaces all textarea tags into CKEDITORS
<script type="text/javascript">
CKEDITOR.replaceAll();
</script>
//this attempts to grab all data from inputs and textareas
$(function() {
$("#submit").click(function() {
var newsTitle = $("#newsTitle").val();
var editNews = CKEDITOR.instances.editNews.getData();
var contactTitle = $("#contactTitle").val();
var editContact = CKEDITOR.instances.editContact.getData();
var linksTitle = $("#linksTitle").val();
var editLinks = CKEDITOR.instances.editLinks.getData();
$.ajax({
type: "POST",
url: "update.php",
data: 'newsTitle='+newsTitle+'&editNews='+editNews+'&contactTitle='+contactTitle+'&editContact='+editContact+'&linksTitle='+linksTitle+'&editLinks='+editLinks,
cache: false,
success: function(){
updated();
}
});
return false;
});
});
the getData() function seemed like it would work because I tested it with alerts and it was grabbing the data from the editors, but once I would try and update, it wouldn't work...
any ideas?
This code replaces the textarea:
<script type="text/javascript">
CKEDITOR.replace( 'TEXTAREA_ID', {
extraPlugins : 'autogrow',
removePlugins : 'resize',
entities : false
});
</script>
In the JS file this is the code and I am using Jquery Validator Plugin:
$(document).ready(function(){
jQuery.validator.messages.required = "";
$("#FormID").validate({
submitHandler: function(){
var ContentFromEditor = CKEDITOR.instances.TEXTAREA_ID.getData();
var dataString = $("#FormID").serialize();
dataString += '&ContentFromEditor='+ContentFromEditor;
$.ajax({
type: "POST",
url: "Yourfile.php",
data: dataString,
cache: false,
success: function(html){
YOU WORK WITH THE RETURN HERE
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.responseText);
}
});
return false;
}
});
});
This is the line that most of the time creates the error:
CKEDITOR.instances.TEXTAREA_ID.getData();
After the instances always comes the ID of the textarea.
I have my own config.js that you can get from the ckeditor website or from the examples.
Tage a look at the CKEditor function/adaptor for jQuery
http://docs.cksource.com/CKEditor_3.x/Developers_Guide/jQuery_Adapter
Because setting and retrieving the editor data is a common operation, the jQuery Adapter also provides the dedicated val() method:
// Get the editor data.
var data = $( 'textarea.editor' ).val();
// Set the editor data.
$( 'textarea.editor' ).val( 'my new content' );
With this code, my problems were solved.
I updated the field running ckeditor to be seen in serialize.
$('#form').find('.class').each(function(index) {
$(this).val(CKEDITOR.instances[$(this).attr('id')].getData());
});
Related
I have one html page which contains a jquery function.
<script>
function loadCustomers() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getCustomers',
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td><a href="clientSiteInfo.html?client=">'+id+'</td><td>'+value+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadCustomers;
</script>
I have linked another html page for each row. When each rows populated, the id values has to be passed to the clientSiteInfo.html page.
In the clientSiteInfo.html page i have another jquery function similar to above.
<script>
function loadSites() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getSite?clientName='+${param.client},
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td>'+id+'</td><td>'+value.machine+'</td><td>'+value.state+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadSites;
</script>
in the GET url I try to read client parameter. But it is not passing from my initial page.
What Im doing wrong here? I look for simple solution
jQuery doesn't have a native way to read the url parameters. However, javascript works just fine:
function getParameterByName(name) {
const match = RegExp(`[?&]${name}=([^&]*)`).exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' ') );
}
In your code you would just call it as getParameterByName('client')
Everytime a page loads I need to load text into the CK Editor using JQuery, in order to get data from CK Editor I use
var editor_data = CKEDITOR.instances['editor1'].getData();
now is there a similar function I could use to put the data back into the editor?
I'm using ajax to set the data like this
$.ajax({
type: "POST",
url: "/inc/ajax/basic.php?menu_id="+menu_id+"&info=3",
success: function(msg){
CKEDITOR.instances['editor1'].setData(msg);
}
});
What am I doing wrong
Try this:
CKEDITOR.instances['editor1'].setData(html)
Where 'html' is a string containing content to edit.
Because its not an array then
just replace the instance like this
CKEDITOR.instances.editor1.setData(html)
var editor = CKEDITOR.instances.help_ldesc;
editor.setData('');
$.ajax({
url: urlstr, // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data:{action:"ex_form"}, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache:false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
//alert(data);
var data1=data.split("~`");
$('#help_id').val(data1[0]);
$('#help_title').val(data1[1]);
$('#help_sdesc').val(data1[2]);
editor.setData(''+data1[3]);
var edata = editor.getData();
alert(edata);
}
});
Use this code its works for me and (help_ldesc) is my textarea name.
you should use data, and method for sending query string like this:
$(document).ready(function()
{
var querystring="menu_id="+menu_id+"&info=3";
$.ajax({
method: "POST",
url: "/inc/ajax/basic.php",
data:querystring,
success: function(msg)
{
CKEDITOR.instances['editor1'].setData(msg);
}
});
});
var jqxhr = $.get( "file.php", function(data) {
CKEDITOR.instances.idOftextAreaName.setData( data );
alert( "success" );
})
.done(function() {
//alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
// alert( "finished" );
});
CKEDITOR.instances['<%=ckEditor.ClientID%>'].setData(value);
From my experience using inside a function sometimes doesn't work properly. I'll suggest to use in:
$(document).ready(function () {
...
// instance, using default configuration.
CKEDITOR.replace('editor1');
//set data
CKEDITOR.instances['editor1'].setData(data);
...
});
The title is quite self-explanatory: I need to read a HTML file through jQuery and store its contents into a string variable.
I tried using .load and $.get, but they wouldn't do what I needed.
This is the code I've tried so far, based on the comments below, but they didn't populate my template variable at all:
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template);
AND:
var template = "";
var fileUrl = "includes/twig/image_box.twig";
jQuery.get(fileUrl).then(function(text, status, xhr){
var html = String(text);
template.concat(html);
// console.log(html); // WORKS!
});
console.log(template); // Does not work
It's weird why this isn't working. Weird for me at least. This is how I'd populate a variable in PHP so I've carried the same logic to JS. Maybe there is an alternative way?
P.S:V I've also tried all alternative ways, like concatenating with += and assigning inside the callback function to template with =, but nothing worked.
Thanks to the ones who are trying to help me!
Maybe you should try a AJAX request with $.ajax()
Check the jQuery API here
$.ajax({
url: 'yourHTMLfile.html',
type: 'get',
async: false,
success: function(html) {
console.log(html); // here you'll store the html in a string if you want
}
});
DEMO
EDIT: Added a demo!
I reread your question and I noticed you're calling the console log right above the ajax request but you forgot the ajax is asynchronous that means the page will do a request and only will set the template value when the response return with success(if it returns). So the console.log(template) don't appears because it may be not loaded yet.
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
console.log(template); // the change!
}
});
or
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
async: false,
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template); // the change!
You can try this:
//as you see I have used this very page's url to test and you should replace it
var fileUrl = "/questions/20400076/reading-a-file-into-a-string-in-jquery-js";
jQuery.get(fileUrl).then(function(text, status, xhr){
//text argument is what you want
});
and if it won't work try if your browser can open the file. if it could you'd better try ajax method in jQuery if not you might have some problems regarding permissions or somethings like that in you application server.
I have this in my head section.
<script type="text/javascript" src="post.js"></script>
I want this post.js to be also be implemented to the newly created elements.My another js file which is named as main.js have a code that get data from another php file and prepend it in a div with id display.Previous Loaded Div works great with the post.js file but as new elements are prepended, it does not work for new ones. Here is my main.js code which get data from php file and prepend it:
var auto_refresh8 = setInterval(function() {
var id = "id="+$(".ally:first").attr("id");
$.ajax({
type: "POST",
url: "get_post.php",
data: id,
cache: false,
success:function(html){
$('#display').prepend(html);
}
});
},2000);
this jquery ajax request get data from get_post.php file and prepend it to the div display. but the code in post.js doesn't work with this.The data returned by jquery ajax request contains a div with class comm which have to submitted when keypress function acts.
following is the code of post.js :
$(document).ready( function() {
$(".comm").keypress(function(e) {
if(e.which == 13) {
var id = $(this).attr("id");
var data = 'id=' + id;
var post = $(this).val();
var data1 = 'comment='+post;
var wholedata = data+'&'+data1;
$(this).blur();
$.ajax({
type: "POST",
url: "c_insert.php",
data: wholedata,
cache: false,
success:function(html){
$('.class_all'+id).append(html);
}
});
return false;
}
});
});
Use a delegate to handle the event in post.js file instead. See the jQuery documentation for more information.
Something like this should do it:
$('#display').on('keypress', '.comm', function (e) {
if(e.which == 13) {
// Do code on event
}
});
Note that the "on" function should only be used if you are using jQuery version 1.7 or later. Previous versions uses the function "delegate".
edit Changed $(document).on(...) to $('#display').on(...) since all '.comm'-elements are children of '#display'.
I have a few forms on my single page and I'm submitting them by this method:
$(function() {
$(".button").click(function() {
var upform = $(this).closest('.upform');
var txt = $(this).prev(".tekst").val();
var dataString = 'tekst='+ txtr;
$.ajax({
type: "POST",
url: "http://url-to-submit.com/upload/baza",
data: dataString,
success: function() {
upform.html("<div class='message'></div>");
$('.message').html("<h2>FORM SUBMITTED</h2>")
.append("<p>THANKS!!</p>")
.hide()
.fadeIn(1500, function() {
$('.message').append("<img src='http://my-images.com/i/check.png' />");
});
}
});
return false;
});
});
As you can see, after submit a form, message div appears instead of submitted form.
It works perfectly, when I submit only one form - then it changes to my message div, but when I submit second, and next and next - every time ALL of my already submitted form's messages refreshing.
It looks bad. I want to operate only on actually submitting form. How to fix it?
Well you're setting the message of every .message div by using $('.message').html(). Try this:
upform.find('.message').html(...)
Hard to tell without seeing how your HTML looks but i'm guessing it's this bit,
$('.message')
Should be something like,
$('.message', upForm).
First you have to find out the message div (upform.find('.message')) and than add any html to it. i think your code should be
$(function() {
$(".button").click(function() {
var upform = $(this).closest('.upform');
var txt = $(this).prev(".tekst").val();
var dataString = 'tekst='+ txtr;
$.ajax({
type: "POST",
url: "http://url-to-submit.com/upload/baza",
data: dataString,
success: function() {
upform.html("<div class='message'></div>");
upform.find('.message').html("<h2>FORM SUBMITTED</h2>")
.append("<p>THANKS!!</p>")
.hide()
.fadeIn(1500, function() {
upform.find('.message').append("<img src='http://my-images.com/i/check.png' />");
});
}
});
return false;
});
});
Another way without editing more in your current code just add few lines.
var msgbox = $("<div class='message'></div>");
upform.html(msgbox);
msgbox.html("<h2>FORM SUBMITTED</h2>")
.append("<p>THANKS!!</p>")
.hide()
.fadeIn(1500, function() {
$(this).append("<img src='http://my-images.com/i/check.png' />");
});