I am working on an application that involves getting the entire page content from a page using javascript and dumping the html to the database.On the page I have various components that will be parsed and stored using a ajax request.I do it like this.
function saveContent(){
var $getContent = $('#mainWrap').clone();
$getContent.find('.textBox, .pictureBox').removeAttr('id');
var saveContent = $getContent.wrap('<div></div>').html();
var getBodyStyle=$('body').attr('style');
var auto="auto";
$.ajax({
url:"save.php",
type:"POST",
dataType:"text",
data:"txtComp="+saveContent+"&auto="+auto+"&pageId="+pageId+"&webId="+webId+"&userId="+userId+"&bodyStyle="+getBodyStyle,
success:function(data){
var options = {"text":data,"layout":"topCenter","type":"success","animateOpen": {"opacity": "show"}};
setTimeout(function(){noty(options)}, 1000);
//$('#draftMsg').html(data).fadeIn(500);
}
});
}
Now I have social media components like facebook,twitter.When I try to save the facebook component it is not save entirely as it contains some parameters that are present in the script with '&'.
<div style="z-index: 1001; height: 560px; width: 413px; top: -20px; left: 121.5px;" id="com-IADDFSGNHLU7WNR3WM2KC3I8DA2DOIC6" class="facebookBox contentBox boxStyle">
<div class="blankDiv"></div>
<iframe class="facebookBoxObject" allowtransparency="true" style="border: medium none; overflow: hidden; height: 560px; width: 413px;" src="https://www.facebook.com/plugins/likebox.php?api_key=117096311791424&locale=en_US&height=560&header=true&show_faces=true&stream=true&width=413&href=http://www.facebook.com/cbil360" frameborder="0" scrolling="no">
</iframe>
</div>
The above is the content I want to store to the database and I get it when I say console.log but in the database it stores only the below content
<div style="z-index: 1001; height: 388px; width: 283px; top: -20px; left: 120.5px;" id="com-IADDFSGNHLU7WNR3WM2KC3I8DA2DOIC6" class="facebookBox contentBox boxStyle">
<div class="blankDiv"></div><iframe class="facebookBoxObject" allowtransparency="true" style="border: medium none; overflow: hidden; height: 388px; width: 283px;" src="https://www.facebook.com/plugins/likebox.php?api_key=117096311791424
It breaks after the api_key parameter as it has & after that.I am not asure as I don't get any error for this.Tried to debug but,not to a conclusion yet.
Please correct where am I going wrong.
Update: The query I am using is
$query = "insert into tbl_revision (userId,revisionContent,webId,pageId,status,saveType,dateAdded) values ('".$_SESSION['UserId']."','$revisionContent','$webId','$pageId','$status','$saveType','$toDate')"
I really doubt that the problem is happening before the data reaches your backend. It's happening on the front end because you are including a & as a normal character in your query string which causes some confusion. What I recommend is either you URL encode your saveContent variable (URL encode not HTML encode).
encodeURIComponent(saveContent) //that will replace the & with it's corresponding url encoding
There is also another workaround, you could submit the ajax request fields using the json form provided by jquery $.ajax. An example of that would be
$.ajax({
url:"save.php",
type:"POST",
dataType:"text",
data:{txtComp: saveContent, auto: auto }, //etc
success:function(data){
var options = {"text":data,"layout":"topCenter","type":"success","animateOpen": {"opacity": "show"}};
setTimeout(function(){noty(options)}, 1000);
//$('#draftMsg').html(data).fadeIn(500);
}
});
I also recommend that you have a look on that question to know the difference betweeen URL Encoding and HTML Encoding
Difference between Url Encode and HTML encode
Have you tried to encoded the input string and decoded the output string with htmlentities and html_entity_decode?
Related
With ajax I am bringing content to upload my website with information. What the page does is load everything normally first, then execute the corresponding ajax, but when loading the ajax and placing the appropriate information, this information does not apply the styles of the web page. Here is an example of how my code would be:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<!-- Styles that you do not recognize -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="content" class="div-short"></div>
<script src="js/jquery.js"></script>
<script>
$.ajax({
type: 'POST',
url: "http://localhost:8000/api/pag/5",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
// Dynamic information
$('#id').html(data);
}
});
</script>
</body>
</html>
If someone has some kind of solution or how it can be done, it is very useful for me. Thank you
Example Snippet
In the example below...
assume that const data is being returned from your ajax call
ignore everything except the jQuery, since it's all just to show that styles come through-- the point is to focus on how the HTML is generated
I'm aware I didn't use your exact code and IDs to create this snippet. That doesn't matter-- what matters is the educational takeaway you can get from seeing the data flowing.
const data = '[{"species": "dog", "breed": "Husky", "name": "Kenna"},{"species": "cat", "breed": "Siamese", "name": "Jeff"},{"species": "dog", "breed": "Doberman", "name": "Bella"}]';
let parsed_data = jQuery.parseJSON(data);
var html = "";
$.each(parsed_data, function(key, value) {
html += '<div class="card"><h3>' + value.name + '</h3><p>Species: ' + value.species + '</p><p>Breed: ' + value.breed + '</p></div>';
});
$("#container").html(html);
.card {
margin: 20px;
padding: 20px;
background-color: #EEE;
font-family: "Arial", sans-serif;
cursor: default;
}
.card > h3 {
color: blue;
cursor: pointer;
}
.card > h3:hover {
text-decoration: underline;
}
.card > p {
color: #555;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container"></div>
Explanation
Notice how the first thing I did with the data was run jQuery.parseJSON() on it. This takes the result from a string representation to a javascript object.
I then loop through the javascript object with $.each. I access the variables with the funcParam.keyName format (e.g. the first access value.name).
I finally included the generated HTML in a variable, and then used .html() to add it to my container after the $.each (which is faster than using .append() on each iteration of the loop).
See below where the HTML generation code would be placed:
$.ajax({
type: 'POST',
url: "http://localhost:8000/api/pag/5",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
// run your HTML generation code (like my Snippet example) HERE
}
});
If you deal with changes in DOM (via AJAX), you need to understand, that addClass() or something like toggleClass() will work only for currently present objects. All newly appended or loaded items will not be styled, unless they are chіldren of parents which have CSS for children. Loading external CSS sometimes is a hassle.
Good practice in my case came to use variables in CSS.
Examples of usage: you need to change skin of website/webapp, make a nightmode/daymode or just to style loaded elements correctly.
As example, let's take initial color of text and background in variables:
/* CSS for day mode */
:root {
--textcolor: #333;
--bgcolor: #fff;
}
JS allows you to change the variables in CSS (along with saving that information), here is handy JS snippet from Ciaran O'Kelly for manipulating with CSS variables:
/**
* Gets and sets css vars
* get a css var:
* cv('bgcolor') // Returns #ccc
* set a css var:
* cv('bgcolor','#f00') // Sets and returns #f00
*/
function cv(n,v) {
if(n[0]!='-') n = '--'+n //allow passing with or without --
if(v) document.documentElement.style.setProperty(n,v)
return getComputedStyle(document.documentElement).getPropertyValue(n);
}
And finally, user function to change UI. Styles will be aplicable to all present and yet not loaded elements in DOM:
function change_skin() {
if($("#sk").text() == 'Night') {
// Night mode skin
cv('bgcolor','#666')
cv('textcolor','#eee')
// Change label
$("#sk").text('Day')
} else {
// Day mode
cv('bgcolor','#fff')
cv('textcolor','#333')
// Change label
$("#sk").text('Night')
}
}
i think you need to format your data in html... example
$('#id').append("<span class='yourclass'>"+ data.name +"</span>");
that way you make thediv with all the data and styles you need and then append it to your div #id
after get response add simple html with class for example
$('#id').append('<p class="test">test</p>');
and in the head add the following line
<style>
.test { font-size: 50px; }
</style>
if your "p" get the given style that's means your problem with "data" variable
So I have someone who wanted a special class title to use so they could be able to change the padding of a div. I quickly created a class called .columnpadding so they could do this. Later I was asked to make a few more classes so they could change the padding across multiple pages. Instead of having to duplicate the css class over and over and change the padding for each, is there a way I could have the variable changed via the class title.
For example.
If the class title is .columnpadding-100
Is there a way to have a class with its padding at 100px?
My website runs on Php and Less. Let me know if the coding would be too complicated. Im hoping its not something too crazy! Thanks!
So let's presume we have the following basic structure:
div {
border: 1px solid black;
height: 10px;
width: 10px;
}
<div class="columnpadding-50"></div>
<div class="columnpadding-30"></div>
<div class="dontchangeme"></div>
<div class="columnpadding-10"></div>
Using only vanilla JS we can easily achieve the desired result:
var divs = document.querySelectorAll("div[class^='columnpadding-']");
for (let i = 0; i < divs.length; i++){
let psize = divs[i].getAttribute('class');
psize = psize.substring(psize.indexOf('-') +1, psize.length);
divs[i].style.padding = psize + 'px';
}
div {
border: 1px solid black;
height: 10px;
width: 10px;
}
<div class="columnpadding-50"></div>
<div class="columnpadding-30"></div>
<div class="dontchangeme"></div>
<div class="columnpadding-10"></div>
Where we first select all divs containg class with value columnpadding- into a NodeList
Then we retrieve a string of the each class attribute, and substring it from the - to receive the size
Last but not least, we apply style.padding to our selected elements in NodeList
And voilà, produces the expected result!
Use JQuery
CSS - not needed, but here for the example
div {
display: inline-block;
}
HTML
<div class="columnpadding-100">This has 100 padding
</div>
<div class="columnpadding-50">This had 50 padding
</div>
javascript / jQuery
$(document).ready(function(){ // wait until the page is completely loaded
$("[class^='columnpadding-']").each(function(){ // get every element that has a class starting with "columnpadding-"
let classNamesString = $(this).attr('class'); // get the string of class nameS from this element
let classNames = classNamesString.split(" "); // create an array of class names
$.each(classNames, function(index, className){ // loop through the class names looking for the one we want
if (className.startsWith("columnpadding-")) { // hey, this is the one we want
let amount = className.substring(14); // get the amount after the hyphen
$("." + className).css("padding", amount + "px"); // set the css for the padding on the element
}
});
});
});
I have found a way to move a picture round in a box made of a tag.
It works perfectly as i want it. The code is as flows:
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#my-image").css({top: 0, left: 0});
var maskWidth = jQuery("#my-mask").width();
var maskHeight = jQuery("#my-mask").height();
var imgPos = jQuery("#my-image").offset();
var imgWidth = jQuery("#my-image").width();
var imgHeight = jQuery("#my-image").height();
var x1 = (imgPos.left + maskWidth) - imgWidth;
var y1 = (imgPos.top + maskHeight) - imgHeight;
var x2 = imgPos.left;
var y2 = imgPos.top;
jQuery("#my-image").draggable({containment: [x1, y1, x2, y2]});
jQuery("#my-image").css({cursor: 'move'});
});
</script>
<div id="my-mask" style="width: 600px; height: 200px; overflow: hidden;">
<img id="my-image" src="stormP.jpg" width="" height=""/>
</div>
Now I want a button that can save the visible part of the picture in a new file.
Can anyone point me in the right direction. I have no clue of how to do that. I'm using PHP, CSS and JQuery.
Alternately I can use CSS to place the hole picture inside the tag with overflow hidden.
In that case I need the coordinates of the upper left corner compared to the picture coordinates. Then I would set the background-position: -300px -330px; as the upper left corners X,Y coordinates relative to the picture like this:
<div style="cursor: pointer; width: 600px; height: 200px; background-image: url(stormP.jpg); background-repeat: no-repeat; background-position: -300px -330px;">
Any of the two will do.
Any help will be greatly appreciated!
You have two ways that you can handle this. In PHP you can do server side editing (You would pass the coordinates to the server and then use something similar to GD in order to crop the image to the set width/height you want), or use the javascript canvas method, which are explained in many tutorials, one of which can be found here.
I have a PHP site I'm working on, and need to allow the user to select data and have different data appear on the next DIV (see attached image). Essentially I'd like a DIV (overflow:auto, so it scrolls) to populate using the SQL SELECT statement, and allow a user to click on a list item. That item creates a new SELECT statement for the div to the right, if that makes sense. Any input on the best way to go about this? New to PHP, not HTML/CSS though.
Zach
I think the best way to achieve this is with jQuery (a JavaScript-Library). I is quite easy to use, and if you got the trick, you can do amazing things with it.
For PHP/MySQL, you could use jQuerys Ajax functionalities (see http://api.jquery.com/jQuery.ajax/). Use the callback to display the loaded data (see below).
Here is a very simple example on how to show another div (in which could be more links to select) with dynamic content. If you combine this with Ajax, you should get what you need.
Include jQuery in within head tag:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
Code for the body:
<!-- First Box: click on link shows up second box -->
<div id="selectOne" style="float: left; margin-right: 10px; border: #666 thin solid; padding: 10px;">
One<br />
Two<br />
Three
</div>
<!-- Second Box: initially hidden with CSS "display: none;" -->
<div id="selectTwo" style="float: left; margin-right: 10px; display: none; border: #666 thin solid; padding: 10px;"></div>
<!-- The JavaScript (jQuery) -->
<script type="text/javascript">
//Do something when the DOM is ready:
$(document).ready(function() {
//When a link in div with id "selectOne" is clicked, do something:
$('#selectOne a').click(function() {
//Fade in second box:
$('#selectTwo').fadeIn(500);
//Get id from clicked link:
var id = $(this).attr('id');
//Depending on the id of the link, do something:
if (id == 'one') {
//Insert html into the second box which was faded in before:
$('#selectTwo').html('One<br />is<br />selected')
} else if (id == 'two') {
$('#selectTwo').html('Two<br />is<br />selected')
} else if (id == 'three') {
$('#selectTwo').html('Three<br />is<br />selected')
}
});
});
</script>
So if you would use jQuerys Ajax-Functionality, you could use something like that (not tested!):
$('#selectOne a').click(function() {
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'getYourData.php',
data: 'thisIsSentToPHPFile='+id,
success: function(msg){
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#selectTwo').html(msg)
$('#selectTwo').fadeIn(500);
}
});
});
The getYourData.php could be:
$id = $_POST['id'];
$query = mysql_query('SELECT * FROM table WHERE id='.$id);
$result = mysql_fetch_assoc($query);
//Now echo the results - they will be in the callback variable:
echo $result['tablefield1'].', '.$result['tablefield2'];
Give it some tries, tweak it a little bit and you should get it working.
The most straightforward way to do this is probably to make the right portion an iframe.
Then each item in the middle list could be a link like so:
Company 2
In displaySubItems.php you would then use the $_GET['company'] value in your select statement to populate the table.
Alternatively you could make use of AJAX methods to populate the table on the right though I'm personally not that familiar with AJAX so I can't tell you more about that. Also I suspect iframes are more widely supported.
EDIT: changed some parts based on one of your comments
I am using an ajax function to receive data. Based on that data, if results are not found I receive a string "No matches found" with some html formatting. If there are results, data is formatted into a table and a "Div" section underneath this section is hidden.
Now the issue I am having is, when I find no results, i do not want this "Div" table to disappear.But to check if there are no results, I would have to compare the whole string received by the searchCustomer.php (which is very large).
Is there an easier way of doing this?
My ajax call:
$('#search').click(function(e){
$.ajax({
type : 'GET',
url : 'searchCustomer.php',
dataType :'html',
data:{
lastName : $('#search_LN').val(),
firstName : $('#search_FN').val(),
phone : $('#search_PN').val()
},
success : function(data){
if (data.error == true){
alert("there was an error in the post layer");
} else {
$('#searchResults').html(data);
if (data.text == '<br><font color='red'>No matches found</font>'){
}else{
var ele = document.getElementById("NewCustomerDiv");
ele.style.display = "none";
}
}
}
});
return false;
});
Running fire-bug,
The actual data received from searchCustomer.php is:
<style type="text/css">
a.resultBookButton {
color: black;
padding: 1px;
border: 2px outset lightgrey;
background: #008800;
/* Mozilla: */
background: -moz-linear-gradient(top, lightgrey, #FFFFFF);
/* Chrome, Safari:*/
background: -webkit-gradient(linear,
left top, left bottom, from(lightgrey), to(#FFFFFF));
text-decoration: none;
}
a:active {
border-style: inset;
}
</style>
<br><font color='red'>No matches found</font>
I just want to check for "No matches found" or if there is a better way of finding no results.
Yes, return JSON instead. You can structure the response to be:
{
count: 0,
content: "your html here"
}
You can then check the count through data.count. Your server will need to set this based on the number of results found.
You will want to set the dataType property in the ajax call to JSON.
I disagree with Brad, converting to JSON would be a pain because all your HTML which uses quotes all the time would have to have those quotes escaped in order to work in a JSON string, which can present an annoyance at best and accidentally trigger errors for invalid JSON at worst.
The ideal solution is changing what those pages return. Return the full HTML if items found, return "0" or "" if nothing is found, and then check for those returns.
If you can't change what is returned from the AJAX call, perhaps just do an (returnedData.indexOf("
Easy peasy.
EDIT:
$.ajax({
... other setting ...
success : function(data){
(data.indexOf('<table') == -1){
//there was a table in the returned data
} else {
// ...
}
}
});
AJAX responses should contain raw data that is in an easily parse-able format, such as JSON or XML. Upon receiving the response, the AJAX success handler should then parse the response and generate the necessary HTML to display. searchCustomer.php should not be generating the HTML...your success handler should.
If designed in this way, it gives you the flexibility to display the data however you want, so you can re-use this AJAX function anywhere in your website (or even make it publically available for others on the Internet to use).
JSON:
{
results: [
"result1",
"result2"
]
}
XML:
<results>
<result>result1</result>
<result>result2</result>
</results>