Saving <div> styles with its content inside a contenteditable div - javascript

The title of this question might be unclear, but thats why I'm trying to explain it right here. I've got a contenteditable div which acts like a textarea for the articles of my blog (adminpanel). Getting the db data to display properly in the contenteditable div is no problem. But when I save the updated article version to my database, it aint saving the div styles ( as example) which are in the contenteditable div.
Example:
<div id="article_content" class="edit_article_content_container_inner" contenteditable="true"><?php echo $db_content ?></div>
outputs:
<div id="article_content" class="edit_article_content_container_inner" contenteditable="true">
<div>Dear visitor,</div>
<div><br /></div>
<div>Thank you for visiting</div>
</div>
When I make changes and decide to save the new version, the db_content column gets updated and looks like:
Dear visitor,Thank you for visiting this page
So the contenteditable div destroys my div styles when saving the new updated article. Is there a way to still store these div styles?
Thank you.
This is the part where I make the ajax call
$("#btn-save-new-article").on('click', function (event) {
var article_id = $('.edit_article_title_container').attr('data-article-id');
var article_title = $("#article_title").text();
var article_content = $("#article_content").text();
event.preventDefault();
$.ajax({
type: "POST",
url: "/includes/db-requests/admin/db-save-edited-article.php",
data: {article_id: article_id, article_title: article_title, article_content: article_content},
success: function(data,textStatus,jqXHR){ finish_editing_article(data,textStatus,jqXHR); }
});
});
function finish_editing_article(data,textStatus,jqXHR) {
//alert (data);
if (data == "article_edited_success") {
//location.reload();
alert(data);
} else {
alert(data);
}
}
As you can see, I'm storing the article_id, article_title and article_content.
Receiving the data to actual store it:
//DIV SUBMITTED DATA
$article_id = safe($mysqli,$_POST['article_id']);
$article_title = safe($mysqli,$_POST['article_title']);
$article_content = $_POST['article_content'];

.text() returns just the text content of an element. .html() returns the content with the HTML intact.
var article_content = $("#article_content").html();

Related

jquery ajax request wrapped in jQuery()'s .text() isn't the same as the div's .text()?

I know this is a very concrete issue but I've struggled with this code for the last 2 hours and I can't find anything on the topic or figure out how to solve it.
I have an issue with a jQuery Ajax Post request. I am trying to make a section on my page where I display the users current level. When a user interacts and does something that increases the level on the site the level should also increase in the DOM/client's browser. Therefore I've added a setinterval that allows the request to run every 5th second. And if the $(response).text() is different from the current div's .text() where i am rendering the current level I want to append this new response from the ajax request.
Maybe the answer is more obvious than I think.... I have added the code below
Ajax page:
$(document).ready(function () {
function getLevel() {
var getLvlData = $.ajax({
url: "AjaxRequests.php",
type: "POST",
data: {type: "4", lvl_r_type: 1}
});
getLvlData.done(function (response, textStatus, jqXHR) {
var innerLevelHTML = $("#LevelContainer");
if (($(response).text()) != ($(innerLevelHTML).text())) {
innerLevelHTML.html("");
innerLevelHTML.append(response);
}
if ($(response).text() == $(innerLevelHTML).text()) {
alert("the same");
}
});
}
var levelChecker = setInterval(function () {
getLevel();
}, 1000);
getLevel();
});
AjaxRequests.php:
if ($_POST["type"] == "4" && isset($_POST["lvl_r_type"])) {
$returnVal = htmlentities($_POST["lvl_r_type"]);
if (!empty($returnVal)) {
if ($returnVal == 1) {
?>
<div id="chartWrapper">
<div>
<canvas id="doughnut-chart"></canvas>
</div>
<div id="chart-center">
<div>
<div><h1>0%</h1></div>
<div><p>GX 0 / 1</p></div>
</div>
<div><p>LVL 0</p></div>
</div>
</div>
<div id="progressList">
<div><p>View tasks</p></div>
</div>
<?php
}
}
}
?>
html page
<div id="LevelContainer"></div>
Try using trim since a white space could be treated as a part of the text.
if (($(response).text().trim()) != ($(innerLevelHTML).text().trim())) {
...
One alternative approach I can think of, off of my head is, to set a hash inside a data attribute say data-hash="" whenever you set the html of that div, and then whenever you have a new ajax response you can generate a hash on the fly and compare that to the existing one and if a change is found just update the html and the hash value for that attribute.
This process minimises the confusion that may be caused due to dom being updated by some script.
Also, Instead of
innerLevelHTML.html("");
innerLevelHTML.append(response);
Why not just just set the html directly as
innerLevelHTML.html(response);

JS: get value of element in ajax updated div

I have a page with a div updated with Ajax request as needed; this div contains an input with dynamic name that I need to get data from. The button and the script that need this data are placed on the main page. When I try to get data with scripts placed in the updated div html itself, it works fine; but same code placed on the main page does not work. How do I find an element by id in Ajax updated div?
Main page:
/* ajax updated div */
<span id="i_descr_{{i.id}}" class="tooltiptext"></span>
/* button */
<div class="trade_move arrow_r" item_id="{{i.id}}" partner_id="{{data.partner_id}}"></div>
<script>
$(".trade_move").click(function() {
var item_id = $(this).attr("item_id");
var partner_id = $(this).attr("partner_id");
var quantity = 1;
var sliderElem = document.getElementById("slider_".concat($(this).attr("item_id")));
if (sliderElem) {
quantity = sliderElem.value;
}
}
</script>
Ajax template, input part:
<input class="slider" type="range" item_id="{{description.id}}" id="slider_{{description.id}}" min="0" max="{{description.slider}}" value="{{description.slider}}" step="1">
If I put the button and the script into the ajax template, they work just fine; is it possible to address the input by its id from main page, loaded before the ajax part?
edit:
I tried adding the button press script to ajax unction that updates the div as by suggestion from Arathi Sreekumar, but it behaves same as before. It also does not work unless you actually load the div with the slider now, meaning it comes from ajax function and not somewhere else. Could I get the syntax wrong or something?
$(".item_description").hover(function(){
var param = $(this).attr("d_id");
$.get('/sud/item_na/', {id: param}, function (data) {
$('#i_descr_'.concat(param)).html(data);
$(".trade_move").click(function() {
var item_id = $(this).attr("item_id");
var quantity = 1;
var sliderElem = document.getElementById("slider_".concat($(this).attr("item_id")));
if (sliderElem) {
quantity = sliderElem.value;
}
$.ajax({
...
});
});
});
edit2: I got it working, not exactly how I wanted it initially, but still.
I did not go into details about the general layout but to make things clear:
1) Layer 1: main page with empty div and a button
2) Layer 2: empty div on main page is populated with ajax html generated by button press. This html is a list of items, each coming with an empty tooltip div, that on hover triggers another ajax query and populates it with item info.
3) Layer 3: Item info window which has the slider control and the button to do something with the item, considering the slider value (and item id naturally).
I put the button and the script attached to it into the last layer 3 template. Here goes the code:
<div align="left">
<input class="slider_value" id="slider_value_{{description.id}}" type="number" value="{{description.slider}}" disabled>
<input class="slider" type="range" item_id="{{description.id}}" id="slider_{{description.id}}" min="0" max="{{description.slider}}" value="{{description.slider}}" step="1">
<div class="trade_move_slider arrow_r" id="trade_move_slider_button_{{description.id}}" item_id="{{description.id}}" partner_id="{{description.partner_id}}" quantity="{{description.slider}}" style="width: 30px;height: 20px;display: inline-block;">
</div>
<script>
$(document).ready(function() {
$(".slider").change(function() {
$("#slider_value_".concat($(this).attr("item_id"))).val($(this).val());
$("#trade_move_slider_button_".concat($(this).attr("item_id"))).attr("quantity", $(this).val());
});
$(".trade_move_slider").click(function() {
$('#output').html('<span class="dot"></span><span class="dot"></span><span class="dot"></span>');
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
var item_id = $(this).attr("item_id");
var partner_id = $(this).attr("partner_id");
var quantity = $(this).attr("quantity");
$.ajax({
type:"POST",
url:"/sud/trade_action/",
data: {
'partner': "container",
'id': partner_id,
'goods_id': item_id,
'csrftoken': csrftoken,
'quantity': quantity
},
success: function(data){
$('#output').html(data);
}
});
});
});
</script>
Note how button attribute "quantity" is updated on slider change. For some reason I could not address the slider directly with $('#slider_'.concat(item_id)).val(); might me the problem that brought me here initially. For general purposes I would still like to know how to address elements of one ajax generated DOM (if I'm putting this correctly) with a script in another ajax generated DOM.
This is the code that updates item info on hover:
$(".item_description").hover(function(){
if ($(this).attr("data") == "empty")
{
$(this).attr("data", "loaded");
var param;
var partner_id = $(this).attr("partner_id");
param = $(this).attr("d_id");
$.get('/sud/item_na/', {id: param, list_type: 'char', 'partner_id': partner_id}, function (data) {
$('#i_descr_'.concat(param)).html(data);
});
}
});
You could add a pseudo-class, js-slider in your input element:
<input class="slider js-slider" type="range"
item_id="{{description.id}}"
id="slider_{{description.id}}"
min="0" max="{{description.slider}}"
value="{{description.slider}}" step="1">
and then you this class in order to grab your element.
$(".trade_move").click(function() {
var item_id = $(this).attr("item_id");
var partner_id = $(this).attr("partner_id");
var quantity = 1;
var sliderElem = $(".js-slider");
if (sliderElem) {
quantity = sliderElem.val();
}
}
In the above code, I think that it is evident that item_id and partner_id are not used. So you can eliminate them. Furthermore, I don't see where you use the quantity.

Javascript populates input, but not span?

I am using Select2 dropdown menu to get data from database threw ajax and json/php.
The option i make will then populate some input fileds for editing the database.
I use (This field get´s populated ok):
<input type="text" class="form-control" name="valt_element_id" id="valt_element_id" placeholder="Objekt ID" />
But on some field i just want to show the data, not to be edited.
I figured to use:
<span id="valt_element_id"></span>
But this span code won´t work!
Why?
JS:
$(document).ready(function(){
var valtObjektElement = $('#valj_objekt_element');
$('#valj_objekt_element').select2({
ajax: {
url: "valj_objekt_element.php",
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
} // Ajax Call
}); // Select2
// Start Change
$(valtObjektElement).change(function() {
var ElementId = $(valtObjektElement).select2('data').id;
var ObjektNummer = $(valtObjektElement).select2('data').text;
$('#valt_element_id').val(ElementId);
$('#valt_objekt_nummer').val(ObjektNummer);
}); //Change
}); //Domument Ready
There is no value attribute for span. You should either use text or html.
Replace
$('#valt_element_id').val(ElementId);
with
$('#valt_element_id').text(ElementId);
Using javascript:
document.getElementById("valt_element_id").innerHTML = ElementId;
Or jQuery:
$('#valt_element_id').html(ElementId);
You mentioned:
But on some field i just want to show the data, not to be edited . Why not use readonly attribute in input rather than replacing it with a span ?

Ajax reload div content on click button

The idea is: i have a main DIV with content mini divs of cars info divided two per row, that i'm getting with a query from DB, i want when pressing that button to make reload of that main content with new content from the DB, is that possible to do ? please advise.
code looks like this:
<div class="SearchBlocks">
<div class="row">
<div class="car_section">INFO</div>
<div class="car_section">INFO</div>
<div class="car_section">INFO</div>
<div class="car_section">INFO</div>
......
</div>
<h2 class="load_more"><a id="more_link" href="#">Load more <i class="icon-custom_arrow"></i></a></h2>
</div>
function reload(url){
$.get(url, function(data){ // $.get will get the content of the page defined in url and will return it in **data** variable
$('#row').append(data);
}
}
$('#more_link').click(function(e){
e.preventDefault();
var url = 'http://example.com/somepage.html';
reload(url); // this calls the reload function
});
You haven't shown the exact code you're using to generate your AJAX request, however the general pattern will be something like this, where the update logic is extracted in to it's own function which is called both on load of the page, and click of the #reload_cars button.
function getData() {
$.ajax({
url: 'yoururl.foo',
success: function(data) {
$('#row .car_section').remove();
$('#row').append(data);
}
});
}
$('#reload_cars').on('click', getData);
getData();
just use
function refreshDiv(){
var container = document.getElementById("divId");
var content = container.innerHTML;
container.innerHTML= content;
}

How to call ajax and output its result inside div and textarea?

I am trying to make load more button. My goal is to call ajax and put the response inside div and textarea.how to place the response inside div and textarea? Currently the response only shows in messagebox but i want to append the result into div.
*Note:*Response is html hyperlinks produced by process.php and i want those hyperlinks placed inside the div
<html>
<head>
<script>
//initialize page number to 1 default
var pagenumber=1;
//pass pagenumber to function to fetch correct page records
function getResult(pagenumber){
alert('me here'+pagenumber);
$.ajax(
{
type: 'GET',
url: './process.php?ID=1234&type=1&moviePath=1234/1212/Love&title=Love&page='+pagenumber,
data: $("#myform").serialize(),
data: {
},
success: function (good)
{
//handle success
alert(good)
},
failure: function (bad)
{
//handle any errors
alert(bad)
}
});
//after every call increment page number value
pagenumber++;
}// end of getResult Function
function addMoreItems()
{
pagenumber++;
getResult(pagenumber);
}
</script>
</head>
<body>
<div id="myDiv"></div>
<div class="MoreButtonSection">
<div class="RedButton">
<span class="LeftEnd"></span>
<span class="Centre">see more</span>
<span class="RightEnd"></span>
</div>
</div>
<br>
<br>
<form id="myform" name="myform" action="./2.php?Id=&title=" method="post">
<td>
<textarea rows="7" cols="15" name="outputtext" style="width: 99%;"></textarea>
</td>
</form>
</html>
You say your result is only showing in the message box, instead of alerting it, simply append. Assuming the below div is what you want to append to:
<div id="myDiv"></div>
You can modify your success function:
success: function (good)
{
//handle success
$("#myDiv").append(good);
},
Also, get rid of that second data: {}, -- it's doing nothing.
There are a number of issues.
There is no indication that you've included jQuery.
You've declared data: twice.
As Dmitry pointed out, you should probably be posting this.
And finally, where are you actually calling getResult()? It doesn't look like it's being called.
In addition, it is worth noting that from jQuery 1.8 and higher, .success() and .failure() are now deprecated and have been replaced with .done() and .fail().
http://api.jquery.com/jQuery.ajax/
I tend to use jQuery in these situations to make life a little easier, and work with the $('#yourDiv').append() function. For instance you can create variables i.e. var mug; and once it is filled with your data append mug to the document through $('#yourDiv').append("<p>"+mug+"</p>);
An example - Ajax Twitter API call that returns tweets to specific lists within a div (page source)
Hope that helps!
I think I get what you are trying to do but that code is a mess. As #David L has stated, you need jQuery. But then you do not need all the code you have written. It can be done in a few simple lines. Please replace the actual element selectors with your correct ones.
function addMoreItems() {
pagenumber++;
// get form values
var params = $('#myform').serializeArray();
// add predefined values
params.push({name: 'ID', value: '1234'});
params.push({name: 'type', value: '1'});
params.push({name: 'moviePath', value: '1234/1212/Love'});
params.push({name: 'title', value: 'Love'});
params.push({name: 'page', value: pagenumber});
// do request and insert response from server in div with id='divresults'
$.get('process.php', params, function(data) {
$('#divResults').append(data);
});
}

Categories

Resources