Hey guys i got a problem with my DnD solution.
It works well as long as i dont write something into my textarea. That means if the page is loading data from MySQL into the Area it works, if i try to put write something in it by my self it doesnt.
Does someone know how i can fix this? so that i can write into my Area and still drop something in there?
Below the important part of the Script if you need more to see why it is not working, let me know.
Got the Code for it from:
http://www.dhtmlgoodies.com/index.html?whichScript=drag-drop-custom
Generating dragabele Image preview:
$dir = "../../images";
$handle=opendir ($dir);
while (($file = readdir ($handle)) !== false) {
if ( filetype( $dir.'/'.$file) == "file"
AND ((substr( $file, -4) == ".jpg")
|| (substr( $file, -4) == ".png")
|| (substr( $file, -4) == ".gif"))){
echo " <div id='".$file."' style='float: left; width:120px; height:125px; border-width:1px; border-style:solid; border-color:black;'>
<img src=".$dir."/".$file." width=110 style='height: 110px;'>
$file
</div>";
echo " <script type='text/javascript'>
dragDropObj.addSource('".$file."',true);
</script>";
}
}
closedir($handle);
Now im dropping them into a textarea with the following Javascript:
<script type="text/javascript">
function dropImg1(idOfDraggedItem,targetId,x,y){
var html = document.getElementById('text_kurz').innerHTML;
if(html.length>0)html = html + ' ';
html = html + '<img src="/images/' + idOfDraggedItem+'">';
document.getElementById('text_kurz').innerHTML = html;
}
function dropImg2(idOfDraggedItem,targetId,x,y){
var html = document.getElementById('text_lang').innerHTML;
if(html.length>0)html = html + ' ';
html = html + '<img src="/images/' + idOfDraggedItem+'">';
document.getElementById('text_lang').innerHTML = html;
}
function dropImg3(idOfDraggedItem,targetId,x,y){
var html = document.getElementById('nachwort').innerHTML;
if(html.length>0)html = html + ' ';
html = html + '<img src="/images/' + idOfDraggedItem+'">';
document.getElementById('nachwort').innerHTML = html;
}
var dragDropObj = new DHTMLgoodies_dragDrop();
</script>
OK Guys ive got the solution... its that simple that i didnt even thought about that...
its just:
.innerHTML
to
.value
Thanks anyway ;)
Hope i could help out someone having the same problem
Related
I'm working on a tagging part on a site similar to Facebook. The idea is that whenever someone types # in the post area, a drop down menu appears containing all of his friends. He then picks who he wants to tag and clicks on that person's profile. I have a javascript function which detects when # is pressed, and then calls another js function which then in turn sends an ajax request to a php file for the list. And this part works great.
So when the user clicks on someone from their friend list, I set it up so that an href part containing the friend's username is extracted from the php file as plain text, and then displayed as a text string right after the # character in the post area (I prevented following to the profile after clicking with return: false). So, for example, when someone wants to choose John Smith, he presses #, the list appears, he picks John Smith, clicks on his profile, the list disappears, and then the username appears after #, like this: #john_smith
Now the trouble is that I would want to make john_smith after # into a hyperlink that would lead to John Smith's profile, instead of it being just plain text. And I've been really struggling to find a solution. Any help would be much appreciated.
Thanks a lot! :)
**//php ajax file**
<?php
$userLoggedIn = $_POST['userLoggedIn'];
$userLoggedIn = new User($con, $userLoggedIn);
$rez = array();
$rez = $userLoggedIn->getFriendArray();
if ($rez != ",") {
$no_commas = explode(",", $rez);
foreach ($no_commas as $key => $value) {
$friend = mysqli_query($con, "SELECT first_name, last_name, username, profile_pic FROM users WHERE username='$value'");
$row = mysqli_fetch_assoc($friend);
echo "<div class='displayTag'>
<a href=" . $row['username'] . " id='grabLink'>
<div>
<img src='" . $row['profile_pic'] . "'>
</div>
<div>
" . $row['first_name'] . " " . $row['last_name'] . "
<p style='margin: 0;'></p>
<p id='grey'></p>
</div>
</a>
</div>";
}
}
else {
echo "<br><p id='ynf'>You have no friends. Please add someone</p>";
}
**//js functions**
function userTag(user) { // for ajax
$.post("includes/handlers/ajax_user_tag.php", {userLoggedIn:user},
function(data){
$('.tag_results').html(data);
});
}
function textTag() { // for extracting href and placing # and username anywhere in the post area
$('.displayTag a').click(function(a){
var x = $(this).attr('href');
var y = $(this).prop('href');
var $txt = jQuery("#post_text");
var caretPos = $txt[0].selectionStart;
var textAreaTxt = $txt.val();
$txt.val(textAreaTxt.substring(0, caretPos) + x + textAreaTxt.substring(caretPos) );
$('.tag_results').html("");
return false;
});
}
**//js code**
$("#post_text").keydown(function (e) { // listens for #
if(e.which == 50)
userTag('<?php echo $userLoggedIn; ?>');
if(e.which != 50)
$('.tag_results').html("");
});
$('.tag_results').hover(function(e) { //calls textTag function on hover
textTag();
});
**//Empty div populated by ajax results**
<div class="tag_results">
</div>
EDIT:
I found out what the problem was, purely by accident. In the file with the php classes, strip_tags was used for all posts. So what I wanted to do was practically impossible with that turned on. Now it's working as it should. Thanks everyone for help! :)
I don't believe that your click event is capturing the click, because your php is dynamically creating the list element. Also your function, textTag() doesn't actually apply the event until that function is run, so it could be creating issues. Change your JS to -
$(document).on('click', '.displayTag a', function() {
var href = $(this).attr('href');
//other code applying href to new anchor tag in proper format
});
First I would change a little bit the PHP response in order to make it easier to get the firend's full name.
**//php ajax file**
<?php
$userLoggedIn = $_POST['userLoggedIn'];
$userLoggedIn = new User($con, $userLoggedIn);
$rez = array();
$rez = $userLoggedIn->getFriendArray();
if ($rez != ",") {
$no_commas = explode(",", $rez);
foreach ($no_commas as $key => $value) {
$friend = mysqli_query($con, "SELECT first_name, last_name, username, profile_pic FROM users WHERE username='$value'");
$row = mysqli_fetch_assoc($friend);
echo "<div class='displayTag'>
<a href=" . $row['username'] . " id='grabLink'>
<div>
<img src='" . $row['profile_pic'] . "'>
</div>
<div class='fullname'>
" . $row['first_name'] . " " . $row['last_name'] . "
<p style='margin: 0;'></p>
<p id='grey'></p>
</div>
</a>
</div>";
}
}
else {
echo "<br><p id='ynf'>You have no friends. Please add someone</p>";
}
Then I would modify the JS function
function textTag() { // for extracting href and placing # and username anywhere in the post area
$('.displayTag a').click(function(a){
var fullname = $(this).find('.fullname').text();
var x = ''+fullname +'';
var y = $(this).prop('href');
var $txt = jQuery("#post_text");
var caretPos = $txt[0].selectionStart;
var textAreaTxt = $txt.val();
$txt.html(textAreaTxt.substring(0, caretPos) + x + textAreaTxt.substring(caretPos) );
$('.tag_results').html("");
return false;
});
}
I am working on PHP. I have three dynamic dropdown boxes. On the basis of first selected value I change the content of second select box and same case for the third. I have achieved this functionality through javascript. The problem I am having is my code works perfectly on localhost but when I upload the code on the online server the page keeps on reloading. Let me first share my code so that you can have an idea of what I am talking about
javascript
<script>
var valnew = <?php echo $cat3; ?> ;
function reload() {
var val = form.cat.options[form.cat.options.selectedIndex].value;
var text = form.cat.options[form.cat.options.selectedIndex].text;
self.location = 'douglas-college.php?cat=' + val + '&text=' + text
}
function reload3(form) {
var val = form.cat.options[form.cat.options.selectedIndex].value;
val2 = form.subcat.options[form.subcat.options.selectedIndex].value;
self.location = 'douglas-college.php?cat=' + val + '&cat3=' + val2;
}
function reload4(form) {
var val3 = form.subcat3.options[form.subcat3.options.selectedIndex].value;
var text = form.subcat3.options[form.subcat3.options.selectedIndex].text;
self.location = 'course-title.php?inst_id=' + val3 + '&coursecode=' + valnew;
}
</script>
<?php
$query1 = mysql_query("SELECT * FROM course");
echo "<select name='cat' class='input-large form-control' onchange=\"reload(this.form)\">";
if (!isset($_GET['cat'])) {
echo '<option>Select one</option>';
while ($row = mysql_fetch_array($query1)) {
echo '<option value="' . $row['courseID'] . '">' . $row['courseName'] . '</option>';
}
} else {
while ($row = mysql_fetch_array($query1)) {
echo '<option value="' . $row['courseID'] . '">' . $row['courseName'] . '</option>';
}
}
echo "</select>";
?>
I have added only one selectbox php code right now. I can share the whole code upon request. I have checked the page by using only one dropdown but still page keeps on refreshing. Means the page is keep on reloading again and again
The real problem is that in :
http://smithdeveloper.com/test/js/sitefunction.js
$('select').change(function() {
$('option').css('background', 'white');
$('option:selected').css('background', '#ff87c3');
}).change();
U trigger .change() on all select elements.
So thats why onchange events are called immediately after page load.
So every time page loads u call change event and listen to change event and fire reload() function
first ditch the inline onchange="" events inside select tags..
Than remove your script from begining of the file and save this in file that you include in the end of the page, sitefunction.js inside document.ready hook.
Here is mine jsfiddle and I changed your functions a bit..
$('[name=cat]').on('change', function(){
var val1 = form.cat.options[form.cat.options.selectedIndex].value;
var txt1 = form.cat.options[form.cat.options.selectedIndex].text;
self.location = 'http://smithdeveloper.com/test/douglas-college.php?cat=' + val1 + '&text=' + txt1
});
$('[name=subcat]').on('change', function(form) {
var val2 = form.cat.options[form.cat.options.selectedIndex].value;
var txt3= form.subcat.options[form.subcat.options.selectedIndex].value;
self.location = 'http://smithdeveloper.com/test/douglas-college.php?cat=' + val2 + '&cat3=' + txt3;
});
$('[name=subcat3]').on('change', function(form) {
var val3 = form.subcat3.options[form.subcat3.options.selectedIndex].value;
var text = form.subcat3.options[form.subcat3.options.selectedIndex].text;
self.location = 'course-title.php?inst_id=' + val3 + '&coursecode=' + valnew;
});
http://jsfiddle.net/mkdizajn/wLz2g3sw/
hth, cheers, k
I am working on an app for personal dev and have ran into some trouble. Fairly new to php and javascript so help is appreciated.
It's a simple form with an input and sumbit button. Once the user inputs an ISBN number and clicks search, a div should appear below showing a Google Books results containing title, author and description.
The way I am approaching this is to use the contents of var $isbn in my javascript. This could be the complete wrong way to do it, which is why I'm here. Basically I want to use the inputted ISBN number and 'attach' this to the end of the Google Books search (see below);
var url='https://www.googleapis.com/books/v1/volumes?q='[USER ISBN INPUT HERE];
If I manually set the var $isbn to '0276427343' - I do receive book results and see the div contents successfully. Just not when they are posted by the form to var $isbn.
I will show my code as is now;
HTML Form
<form name="form" method="post" action="">
<input name="isbn_search" id="isbn_search" type="text">
<button id="submit" name="submit">search</button>
</form>
PHP
if(isset($_POST['isbn_search'])){
$isbn = $_POST['isbn_search'];
}
JaveScript
$(document).ready(function() {
var isbn = <?php echo $isbn; ?>;
var url='https://www.googleapis.com/books/v1/volumes?q='+isbn;
$('#submit').click(function() {
$.getJSON(url,function(data){
$('.result').empty();
$.each(data.items, function(entryIndex, entry){
var html = '<div class="results well">';
//html += '<h3>' + entry.id + '</h3>';
html += '<h3>' + entry.volumeInfo.title + '</h3>';
html += '<div class="author">' + entry.volumeInfo.authors + '</div>';
html += '<div class="description">' + entry.volumeInfo.description + '</div>';
$('.result').append(html);
});
});
return false;
});
});
Any help and/or suggestions are welcome.
Your problem is because the form never submits (you stop it with your javascript).
However php is unnecessary for this, you can just extract the value with js:
$(document).ready(function() {
$('#submit').click(function(ev) {
ev.preventDefault();
var isbn = $('#isbn_search').val(); //get isbn direct from input, no need for php
var url='https://www.googleapis.com/books/v1/volumes?q='+isbn;
$.getJSON(url,function(data){
$('.result').empty();
$.each(data.items, function(entryIndex, entry){
var html = '<div class="results well">';
//html += '<h3>' + entry.id + '</h3>';
html += '<h3>' + entry.volumeInfo.title + '</h3>';
html += '<div class="author">' + entry.volumeInfo.authors + '</div>';
html += '<div class="description">' + entry.volumeInfo.description + '</div>';
$('.result').append(html);
});
});
});
});
I think in this case you don't need to use PHP.
but simply try this :
<div>
<input id="isbn_search" type="text">
<button onclick="do_search();" id="submit" name="submit">search</button>
</div>
<div class="result"></div>
<script>
function dosearch(){
var isbn = document.getElementById('isbn_search').value; //$('#isbn_search').val(); : if you like jquery :D
var url='https://www.googleapis.com/books/v1/volumes?q='+isbn;
$.getJSON(url,function(data){
$('.result').empty();
$.each(data.items, function(entryIndex, entry){
var html = '<div class="results well">';
//html += '<h3>' + entry.id + '</h3>';
html += '<h3>' + entry.volumeInfo.title + '</h3>';
html += '<div class="author">' + entry.volumeInfo.authors + '</div>';
html += '<div class="description">' + entry.volumeInfo.description + '</div>';
$('.result').append(html);
});
//here we send this query to database (thanks to AJAX):
//=====================================================
$.ajax({
type: 'POST',
url: './db_insert.php',
data: {'isbn' : isbn },
});
});
}
</script>
if you want to save the search in a database,
we create a php file : db_insert.php
<?php
// first : init access to data base :
//====================================
$user="root"; //user of database
$pass=""; //password of database
$db="test"; //name of database
$host = "localhost"; //host name
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO('mysql:host='.$host.';dbname='.$db, $user, $pass, $pdo_options);
$bdd->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$bdd->query("SET NAMES 'utf8'");
//second : insert in a table named "all_search" in this case :
===============================================================
$req = $bdd->prepare('INSERT INTO all_search(isbn, date_in) VALUES(:isbn, :date_in)');
$req->execute(array(
'isbn' => $_POST['isbn'],
'date_in' => date('Y-m-d H:i:s')
));
//emm... I think thats all, Enjoy :D
?>
You should try to understand the basic concepts of javascript and php before you implement them like this.
It looks like what you want to achieve is sending an ISBN provided by a client to the server.
The client runs Javascript (interpreted by the browser) - the server runs php(interpreted by the server when requested)
A basic classical concept:
split your HTML CSS JAVASCRIPT (HTML5) to your client and let it do all client stuff
get your PHP to do all the server stuff.
You can send information to your PHP server script in different ways now - via ajax or with the submitting the form with a defined action attribute
I hope this helps - you dont need help with the code first of all - spend some (2-3) hours understanding the concepts - then come back and try to get your code right :)
I hope this helps
it's because you are trying to get ISBN entered by user into $_POST. Where your JS is based on button click. So you can't get isbn field value by this way.
Change your JS to below.
var isbn = $('#isbn_search').val();
PHP code is not needed.
if($_POST....
I'm not sure if I understand you correct but you can return the ISBN number from PHP with json and then use it in your JavaScript.
<?php
$isbn = $_POST['isbn'];
json_encode($isbn);
?>
Trying to create a nice dynamic selection process. There are two parts to the selection process: Choose category, then choose name. The form process works just fine. I then want to display an image based on the name chosen. I can't seem to figure it out, here's the code:
<form action="file.php" method="post">
<select id="first-choice" name="cardset">
<?php foreach ($data as $row): ?>
<option><?=$row["name"]?></option>
<?php endforeach ?>
</select>
<select id="second-choice" name="card">
<option>Please choose from above</option>
</select>
<img src="" name="image-swap">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language=JavaScript >
$(document).ready(function() {
$("#first-choice").change(function() {
$.get("getter.php", { choice: $(this).val() }, function(data) {
$("#second-choice").html(data);
});
});
});
$(document).ready(function() {
$("#card").change(function() {
var first = $("first-choice");
var sec = $(this).val();
$("#image-swap").html(src ? "<img src='/pics/" + first + sec + "'>" : "");
});
});
</script>
I am trying to pull the image from pics/"first"/"sec".jpg
Hard to tell without seeing the HTML, but . . .
var first = $("first-choice");
. . . is missing the .val() at the end. If you change it to this, it should get you much closer to what you are looking for:
var first = $("first-choice").val();
At the moment, you are trying to append the jQuery reference to the HTML option to a string value (sec).
UPDATE
Was looking a little further and found some other issues . . .
1) You are using an HTML img element, but you've given it a name attribute value of "image-swap":
<img src="" name="image-swap">
. . . and are trying to reference it with a jQuery "id" selector:
$("#image-swap")
In order for that selector to work, you must change the name attribute to and id attribute, like this:
<img src="" id="image-swap">
2) You appear to be attempting to update the src attribute of the img tag, but you don't have that quite right in your code:
$("#image-swap").html(src ? "<img src='/pics/" + first + sec + "'>" : "");
There are a couple of issues here:
src does not exist as a variable, but you appear to be checking for its existence as one
you want to update the src attribute of the img, but you are using the .html() method, which sets/gets the HTML content of a tag, not its attributes
To do what you appear to be wanting to do, you probably need to use this code:
$("#image-swap").attr("src", (first !== "" && + sec !== "") ? "pics/" + first + "/" + sec + ".jpg" : "");
That will update the src attribute with the image location, if neither of the selections has an empty value, or with "", if one of them does.
I figured out $("first-choice").val() and Try this,
$(document).ready(function(){
$("#first-choice").change(function() {
$.get("getter.php", { choice: $(this).val() }, function(data) {
$("#second-choice").html(data);
});
});
$("#card").change(function() {
var first = $("first-choice").val();
var sec = $(this).val();
$("#image-swap").html(src ? "<img src='/pics/" + first + sec + "'>" : "");
});
});
Two things:
You only need 1 document ready wrap:
$(document).ready(function(){
$("#first-choice").change(function() {
$.get("getter.php", { choice: $(this).val() }, function(data) {
$("#second-choice").html(data);
});
});
$("#card").change(function() {
var first = $("first-choice");
var sec = $(this).val();
$("#image-swap").html(src ? "<img src='/pics/" + first + sec + "'>" : "");
});
});
The second, non of your options have values, which is why it isn't passing.
<select id="first-choice" name="cardset">
<?php foreach ($data as $row): ?>
<option value="<?=$row["name"]?>"><?=$row["name"]?></option>
<?php endforeach ?>
</select>
Given if the is correct. I've never used = is php to echo, normally I would do <?php echo $row["name"]; ?>.
I've got this code, which add videos (and videos infos) of a YouTube channel ($_POST) on a div of the Html code :
var args= "url="+urlchaine;
xhr_object.open("POST", "traitement.php", true);
xhr_object.onreadystatechange = function() {
if(xhr_object.readyState == 4) {
eval(xhr_object.responseText);
}
return xhr_object.readyState;
}
xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr_object.send(args);
traitement.php :
<?php
if ( isset($_POST["url"]) && !empty($_POST["url"]) )
$urlchaine = $_POST["url"];
else
$urlchaine = null;
$stringresult = str_replace("http://www.youtube.com/user/", "",$urlchaine);
require_once "Zend/Loader.php";
Zend_Loader::loadClass('Zend_Gdata_YouTube');
$yt = new Zend_Gdata_YouTube();
//Get Video info with channel name $stringresult
$videoFeed = $yt->getVideoFeed('http://gdata.youtube.com/feeds/users/...');
if ( $stringresult != null){
echo "var mydiv = document.getElementById('vids');";
echo "var newcontent = document.createElement('div');";
foreach ($videoFeed as $v): $thumbs = $v->getVideoThumbnails();
$videoId = $v->getVideoId();
$thumb = $thumbs[0]['url'];
$videoViewCount = $v->getVideoViewCount();
$videoTitle = $v->getVideoTitle();
echo "newcontent.innerHTML =
'<div class=\"videos\">' +
' <div class=\"img_videos\">' +
' <img class=\"img_video\" width=\"250\" idvideo=\"".$videoId."\" ' +
' src=\"".$thumb."\"/>' +
' </div>' +
' <h3>$videoTitle</h3>' +
' <p>$videoViewCount views</p>' +
'</div>' ;";
echo "mydiv.appendChild(newcontent.firstChild);";
endforeach;
?>
The problem is, when I want to do that, it works perfectly with some channels, whereas an error has existed for others (Uncaught SyntaxError: Unexpected identifier). After several tests, I saw that by removing the display of $ videoTitle, every channels test worked. What is wrong with my code? O.o
$videoTitle seems to contains a simple quote in somes cases, which break your JS code.
Try escaping this quotes with something like this :
str_replace("'", "‚", $videoTitle)