My first cry for help here.
Not sure if my title is properly explicit but it's the only one I can come up with right now. I've been at it for 2 days now and I have read so many different things that I think I am getting completely confused. I'll try to be as precise as possible.
Here's my problem,
First, this is the jQuery code I am basing this on:
$thumbnails.find( 'a' ).each( function() {
pictures.push({
src: $( this ).attr( 'href' ),
title: $( this ).find( 'img' ).attr( 'title' ),
valign: $( this ).find( 'img' ).data( 'valign' )
});
})
You notice the pictures.push in there.
Now, this goes with,
$.vegas( 'slideshow', {
backgrounds: pictures,
delay: 4000,
fade:5000
})( 'overlay' );
Note how the background attribute uses pictures to get the images' names it needs. I'm not sure now how to call pictures. Is it an associative array or is it an object?
Anyhow, I don't want to get the images' filenames from the HTML nodes. I am using PHP to fetch filenames in directories on the server and generate an XML document with those filenames.
Here is the part that generates the XML document in my PHP script, (I only need 5 images for my need)
header("Content-type: text/xml");
echo '<?xml version="1.0"?>';
echo "<img>";
for($i=0;$i<5;$i++){
echo "<src>img/" . $rep_aleatoire[$i] . "/" . $img_aleatoire[$i] . "</src>";
echo "<title>" . $img_aleatoire[$i] . "</title>";
}
echo "</img>";
And this is what thes XML document looks like,
<img>
<src>img/portraits/DSC_0161.jpg</src>
<title>DSC_0161.jpg</title>
<src>img/nature/DSC_0019 copy-tych 3.jpg</src>
<title>DSC_0019 copy-tych 3.jpg</title>
<src>img/portraits/DSC_0157.jpg</src>
<title>DSC_0157.jpg</title>
<src>img/editions/DSC_0053.jpg</src>
<title>DSC_0053.jpg</title>
<src>img/editions/DSC_Ant.jpg</src>
<title>DSC_Ant.jpg</title>
</img>
And here is the JQUERY part I use to get that XML data,
$.get("main.php", function(data){
var rep = new Array;
var file = new Array;
$(data).find("img").each(function(){
$(this).find('src').each(function(i){
rep[i] = $(this).text();
});
$(this).find('title').each(function(i){
file[i] = $(this).text();
});;
for(i=0;i<rep.length;i++){
pictures.push({
src: $(rep[i]),
title: $(file[i])
});
}
});
});
pictures has been initialized out of the scope of this function so it should be available anywhere I need it but it is not. If I try to access it outside that function, it is empty.
Also, when within the scope of that function, all it contains is objects. I don't even know if I'm doing it the proper way. I have tried so many different ways I can't even remember. I just can't get the actual data generated in the XML document.
I sure hope I have been clear enough and you guys understand what I am after.
I simply want to generate the proper format of pictures so it is usable in the $vegas function.
Any help will be greatly appreciated.
First of all. Always declare your variables.
Wrong declaration:
var rep = new Array;
var file = new Array;
Should be either
var rep = new Array();
var file = new Array();
Or even better:
var rep = [];
var file = [];
Declare i, you was using in the last loop.
for(var i=0;i<rep.length;i++){
...
Or even better:
var i;
for(var i=0;i<rep.length;i++){
..
When you done with that you'll notice that you trying to access jquery objects by your array value.
pictures.push({
src: $(rep[i]),
title: $(file[i])
});
And you probably meant:
pictures.push({
src: rep[i],
title: rep[i]
});
Of course, make sure that var pictures available in all scopes, where you are using it.
Related
I am struggling here to find a solution to using
div using contenteditable
PHP
<div class="panel-body">
<div contenteditable="true" style="text-align: justify" id="text_data_1">
<?php echo(html_entity_decode($text_data_from_backend))?>
</div>
</div>
jQuery
var postFormData = {
'agent_id' : $("#text_data_1").val(),
'actionmode' : id
};
var link = 'myfile.php';
$.fn.getajaxresponse(link, postFormData, $.fn.this_callback);
Data is pasted or typed into the div which is contenteditable. The whole html layout fails when end users paste content from websites with tags that are not closed properly.
I am using div contenteditable so that new lines and basic html tags are preserved and can be transacted back and forth to database.
Is there a way to remove html tags that are not closed properly and I believe this is the show stopper in getting this methodology in place. Please note I use jQuery, PHP and MySQL
Thank you for your responses.
It was a bit tricky one and on searching I found a library where jQuery cleaned up without using regex
I attached an editor called Trumbowyg to the div - http://alex-d.github.io/Trumbowyg/
It was quite easy and cool. This one is lightweight and and requires to add the js file to the required page.
On saving via ajax, called a function where JClean [https://code.google.com/archive/p/jquery-clean/] library is used to clean the unclosed tags. Add the Jclean js file to the required page
This is how I did it eventually.
Attaching editor
$.fn.attach_event_div_contenteditable = function(){
var tb_buttons = [
['viewHTML'],
['formatting'],
'btnGrp-semantic',
['superscript', 'subscript'],
['link'],
'btnGrp-justify',
'btnGrp-lists',
['horizontalRule'],
['removeformat'],
['fullscreen']
];
$('#text_data_1').trumbowyg({
removeformatPasted: true,
btns: tb_buttons,
height:"100%",
});
$('#text_data_2').trumbowyg({
removeformatPasted: true,
btns: tb_buttons,
});
$('#text_data_3').trumbowyg({
removeformatPasted: true,
btns: tb_buttons,
});
$('#text_data_4').trumbowyg({
removeformatPasted: true,
btns: tb_buttons,
});
}
Cleaning elements
$.fn.get_latest_value = function(elem){
var tagname = elem.prop("tagName");
var returnvalue = "";
switch(tagname.toUpperCase()){
case "TEXTAREA":
returnvalue = elem.val();break;
case "INPUT":
returnvalue = elem.val(); break;
default:
returnvalue = elem.html();break;
}
returnvalue = returnvalue.replace(/\"/g,'"');
returnvalue = returnvalue.replace(/\'/g,''');
var temp = $("<input value='"+returnvalue+"'/>");
returnvalue = $.htmlClean(temp.val(), { format: true });
return returnvalue;
}
Ajax call
var postFormData = {
'agent_id' : $.fn.get_latest_value($("#text_data_1")),
'actionmode' : id
};
var link = 'myfile.php';
$.fn.getajaxresponse(link, postFormData, $.fn.this_callback);
This is the best I could find as an answer and went ahead. Hope this helps to anyone who wondered how I fixed it.
I have a specific array that php needs to access and write to a file. I also want to be able to call the php to get the array info back. I use JSON.strigify to store the array in a string, but i cant figure out how to send it to a server with php. I have very little php experience and i tried:
<script language="javascript">
var COMMENTS_FOR_DISPLAY = new Array('Have fun with this code: Chris');
// Adds a new comment, name pair to the Array feeding textualizer.
function add_comment() {
// Retrieve values and add them to Array.
var new_comment = $('#kwote').val();
var new_name = $('#name').val();
COMMENTS_FOR_DISPLAY.push(new_comment + ': ' + new_name);
// Reset <input> fields.
$('#kwote').val('');
$('#name').val('');
var arrayAsString = JSON.stringify(COMMENTS_FOR_DISPLAY);
}
$(document).ready(function() {
var txt = $('#txtlzr'); // The container in which to render the list
var options = {
duration: 5, // Time (ms) each blurb will remain on screen
rearrangeDuration: 5, // Time a character takes to reach its position
effect: 'random', // Animation effect the characters use to appear
centered: true // Centers the text relative to its container
}
txt.textualizer(COMMENTS_FOR_DISPLAY); // textualize it!
txt.textualizer('start'); // start
});
</script>
in main.php i put:
<?php
$kwoteString = $_GET["arrayAsString"];
echo $kwoteString;
?>
I used echo to see if i was getting any output,but i wasn't. It could be a very simple fix, maybe im missing a header or something telling my html document to read main.php?? any help would be appreciated!
Use jquery with
$.post(url,params);
there are many tutorials around the web and stack overflow itself.
Here the doc:
http://api.jquery.com/jQuery.post/
you can add a hiddenField and set the string to the hidden field.
php code will read the value from hidden field.
As the title says, I have slickgrid getting/parsing JSON data from PHP, but while I can get it to update to the proper row count, nothing is displayed in a cell unless I edit it first. When I do, the correct data is displayed, but only for cells I have edited. Here is the relevant code:
$(function () {
$.getJSON("./test3.php", function(jsondata) {
$.each(jsondata, function(i, arr) {
var d = (data[i] = {});
$.each(arr, function(key, value) {
d[key] = value;
});
});
grid.updateRowCount();
grid.render();
});
grid = new Slick.Grid("#myGrid", data, columns, options);
//continues function prepping the grid
You might want to go for simpler implementation, there's no need to loop through all your data just dump your "jsondata" directly inside the SlickGrid Object creation.
As long as you have the "data" array into a JSON Object then you're fine. Something like this:
{ "data":[{"id":"84","name" : "Someone" ... ]}
// then pass it to your Slick Object.
grid = new Slick.Grid("#myGrid", jsondata, columns, options);
That's all... Oh and don't forget to have at least have a unique "id" on all rows
You can see example from this web site:
http://joeriks.com/2011/07/03/a-first-look-at-slickgrid-with-read-and-update-in-webmatrix/
I needed to call grid.invalidateRow() on all of the added rows.
I have a while loop which creates a list of anchor tags each with a unique class name counting from 1 to however many items there are. I would like to change a css attriubute on a specific anchor tag and class when it is clicked so lets say the background color is changed. Here is my code
while($row = mysql_fetch_array($results)){
$title = $row['title'];
$i++;
echo "<a class='$i'>$title</a>
}
I would like my jquery to look something like this, it is obviously going to be more complicated than this I am just confused as where to start.
$(document).ready(function() {
$('a .1 .2 .3 .4 and so on').click(function() {
$('a ./*whichever class was clicked*/').css('background':'red');
});
});
Can you give the class a more consistent name? Like myClass_1, myClass_2, etc.
Then you could do:
$(document).ready(function() {
$('a[class^=myClass_]').click(function() { // Assign handler to elements with a
// class that starts with 'myClass_'
$(this).css('background','red'); // Change background of clicked one.
});
});
Here, a "starts with" selector is used to assign the event to all classes that start with myClass.
You could still retrieve the index number if needed.
Within the event handler, $(this) refers to the one that was clicked.
Live Example: http://jsfiddle.net/Jurv3/
Docs for "starts with" selector: http://api.jquery.com/attribute-starts-with-selector/
EDIT: I had a missing ] in the selector. Fixed now.
You can use an iterator over an array like this:
var myclasses = [".1",".2",".3"]; // generated by php
$.each(myclasses, function(index, value) {
$('a '+value).click(function() {
$(this).css('background':'red');
});
});
Note: I think you might be better off using unique ID for each item in your list of anchor tags and have them all share a single class. That's more what classes and IDs are for.
Just give them all the same class, say, myClass. Then:
$('a.myClass').click(function () {
$(this).css('background':'red');
});
This will work as long as you're having the links operate on themselves, or on their parents - as long as the relationship between link and target is the same for each. To operate on the parent, it would be $(this).parent().css(...), and to operate on the next element it would be $(this).next().css(...) and so on.
have you tried something like this?
while($row = mysql_fetch_array($results)){
$title = $row['title'];
$i++;
echo '<a class="anchor_link" id="'.$i.'">'.$title.'</a>';
}
And then for the jQuery:
$(document).ready(function() {
$('a.anchor_link').click(function() {
var thisAnchor = $(this).attr('id');
$(this).css('background':'red');
});
});
The reason for my adding the js var 'thisAnchor' is because I am assuming that you need that $i php variable as the anchor marker? if so you can just take the js var and use it however you need. if you can't use ID because the anchored content is marked by id, use a diferent attr, such as 'title' or 'alt'.
I hope this was helpful.
I want users on my website to be able to "move" div tags once they are 'unlocked' and then for a php script to store the positions in mysql database. So once the user re-logs in the div tags are positioned in the correct place.
I know how to postion div tags in css, and am using php varibles within css to pull the data from the database. I just dont know how to get the position of the div tag in order to store it? Maybe using ajax or something?
any ideas welcome, thanks.
What do you mean by position? Is it "left, right, center..." or the position in pixels?
If it's in pixels, just use the top and bottom css property. If it's a custom position, just do a callback when you change the position.
You can easily get the position using javascript and once you have it you want to save that asynchronously, so yeah ajax is nice. Look up jquery for that one: http://docs.jquery.com/Ajax/jQuery.post
$.post("test.php", { func: "getNameAndTime" },
function(data){
alert(data.name); // John
console.log(data.time); // 2pm
}, "json");
Also, from the way your formulated your question it looks that you don't have a lot experience with ajax. I suggest you look up some documentation online or find a nice book (search SO, there's a bunch of topics about this)
When the position of an element changes, you will want to post the pixel values to a PHP script using AJAX. Here is a brief example using jQuery...
function storeElementPosition(elem) {
var off = $(elem).offset();
$.post("storeElementPosition.php",
{ elem : $(elem).attr("id"), left : off.left, top : off.top },
function(resp) {
alert(resp);
}
);
}
Use jQuery, it'll make life a whole lot easier. ..
HTML:
Save
JavaScript:
$('#savelayout').click(function(){
var postData = {};
$('.xy').each(function(){
var id = $(this).attr('id');
var pos = $(this).position();
if (id && id.length){
postData[$(this).attr('id')] = pos.left.toString() + ',' + pos.top.toString();
}
});
$.post('savelayout.php', postData, function(data, textStatus){
if(textStatus == 'success'){
alert('Positions saved successfully.');
}
});
});
Replace .xy in $('.xy') with the CSS selector that will target all the elements you want saved. Once you do that, if you have two savable elements with with "divid1" and "divid2" id's, the data posted to PHP ($_POST) will look like this:
array(
'divid1' => '123,351',
'divid2' => '512,136'
);
You can then explode each string by the comma and grab each int as the x and y coordinate.