php truncating field issue - javascript

Iam truncating a large field in php. Its all working fine except that iam getting an error on the following line. Iam truncating more than 25 characters with a more hyperlink. When i click the more link, a javascript alert triggers with the actual data.
$length_limit = 25; //limit to this number of characters
$actual_length = strlen($value); //count characters in the $value
$original_text = $value;
$truncated_text = substr($value,0,$length_limit);
if($actual_length <= $length_limit){
$value = $original_text;
} else {
$value = $truncated_text." ... <a onclick='alert(\"'.$original_text.'\")'>more</a>";
Iam getting the error from the last line $value=.... May be some quoatation mark problem. Can someone pls help me with the same.

try this
echo $value = $truncated_text." ... <a onclick=\"alert('".$original_text."')\">more</a>";

You can do it like below (anyone of them):-
echo $value = $truncated_text.' ... <a onclick=\'alert("'.$original_text.'")\'>more</a>';
Or
echo $value = $truncated_text." ... <a onclick=\"alert('".$original_text."')\">more</a>";
Pop-Up Window code:-
<style>
#edit_price_background_overlay {
background: rgba(0, 0, 0, 1) none repeat scroll 0 0;
bottom: 0;
display: none;
overflow-y: auto;
position: fixed;
top: 0;
width: 100%;
z-index: 999999;
}
#mainnew_window {
color: white;
float: left;
margin: 20px;
padding: 100px;
text-align: center;
}
</style>
<div id="edit_price_background_overlay">
<div id="mainnew_window">
</div>
</div>
<?php
$value = 'dhgffdhgfhfhfhghgfhgfhgfhfghfghgfhgfhgfhgfgfhgfhgfhgfhgfhfgrtdyretrertertretgfdvfgvdfgdfbdfgdfbgfnbgbgfhnhhethfgbgfdnggrehgteggbfdvgfdfgergfdgfdrfgrdfgert4gtrhnfgbfdbvcvcbvcbbvcbhrgdghgyfgbfdbgfvfdbtgf';
$length_limit = 25; //limit to this number of characters
$actual_length = strlen($value); //count characters in the $value
$original_text = $value;
$truncated_text = substr($value,0,$length_limit);
if($actual_length <= $length_limit){
echo $value = $original_text;
} else {
echo $value = $truncated_text." ... <a onclick=\"showdata('".$original_text."','mainnew_window','edit_price_background_overlay')\">more</a>";
}
?>
<script>
function showdata(mytext,innerdiv,outerdiv){
var elem = document.getElementById(innerdiv);
var elem2 = document.getElementById(outerdiv);
console.log(elem);
if(typeof elem !== 'undefined' && elem !== null) {
document.getElementById(innerdiv).innerHTML = mytext;
document.getElementById(outerdiv).style.display = 'block';
}
}
</script>
Note:- put this whole code in php file as it is and check.

Related

Infinite Scroll won't load more posts on scroll down when included in another file with HTML tags on top of it

I have an Infinite Scroll that loads more data (from DB) upon scrolling to the bottom,
However, when I try to include that file in another .PHP file and write any HTML tag at its top, it won't load more posts.
On console, I get an error as
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Object.success (test.php:126)
at i (jquery-3.2.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.2.1.min.js:2)
at A (jquery-3.2.1.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-3.2.1.min.js:4)`
My code goes as :
getData.php
<?php
require_once('db.php');
if (! function_exists('getData')) {
/**
* #param int $offset
* #param int $limit
* #return array|null
*/
function getData($offset, $limit, $conn) {
$offset = (int)$offset;
$limit = (int)$limit;
$sqlQuery = "SELECT * FROM tbl_posts ORDER BY id DESC LIMIT $limit OFFSET $offset";
$result = mysqli_query($conn, $sqlQuery);
$rows = [];
while ($row = mysqli_fetch_assoc($result)) {
$cleanRow = [];
foreach ($row as $column => $value) {
$cleanRow[$column] = htmlentities($value);
}
$rows[]= $cleanRow;
}
return $rows;
}
}
Index.php
<?php
require_once ('getData.php');
$offset = (int)($_GET['offset'] ?? 0);
$dataOnly = (int)($_GET['dataOnly'] ?? 0);
$limit = 7;
$rows = getData($offset, $limit, $conn);
$offset+= $limit;
$data = [
'rows' => $rows,
'offset' => $offset,
];
$data = json_encode($data);
// if this is an ajax call, stop here and just spit out our json
if ($dataOnly) {
echo $data;
exit;
}
// otherwise, render the page
$sqlQuery = "SELECT * FROM tbl_posts";
$result = mysqli_query($conn, $sqlQuery);
$total_count = mysqli_num_rows($result);
?>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<style type="text/css">
body {
font-family: Arial;
background: #e9ebee;
font-size: 0.9em;
}
.post-wall {
background: #FFF;
border: #e0dfdf 1px solid;
padding: 20px;
border-radius: 5px;
margin: 0 auto;
width: 500px;
}
.post-item {
padding: 10px;
border: #f3f3f3 1px solid;
border-radius: 5px;
margin-bottom: 30px;
}
.post-title {
color: #4faae6;
}
.ajax-loader {
display: block;
text-align: center;
}
.ajax-loader img {
width: 50px;
vertical-align: middle;
}
</style>
<div class="post-wall">
<div id="post-list">
<input type="hidden" name="total_count" id="total_count" value="<?= $total_count ?>" />
<input type="hidden" name="offset" id="offset" value="<?= $offset ?>" />
</div>
<div class="ajax-loader text-center">
<img src="LoaderIcon.gif"> Loading more posts...
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
// load the initial rows on page load
let initialData = <?= $data ?? '' ?>;
if (initialData) {
if (initialData.rows) {
addrows(initialData.rows);
$('.ajax-loader').hide();
}
}
windowOnScroll();
});
function windowOnScroll() {
$(window).on("scroll", function(e) {
if ($(window).scrollTop() + 1 >= $(document).height() - $(window).height()) {
if ($(".post-item").length < $("#total_count").val()) {
let offset = $('#offset').val();
getMoreData(offset)
}
}
});
}
function getMoreData(offset) {
$('.ajax-loader').show();
$(window).off("scroll");
let pageUrl = window.location.href.split('?')[0];
$.ajax({
url: pageUrl + '?dataOnly=1&offset=' + offset,
type: "get",
success: function (response) {
response = JSON.parse(response);
if (response.rows) {
addrows(response.rows);
if (response.offset) {
$('#offset').val(response.offset);
}
$('.ajax-loader').hide();
}
windowOnScroll();
}
});
}
function addrows(rows) {
let postList = $("#post-list");
$.each(rows, function (i, row) {
let rowHtml = '<div class="post-item" id="'+row.id+'"><p class="post-title">'+row.title+'</p><p>'+row.content+'</p></div>';
postList.append(rowHtml);
});
}
</script>
Now please note that the above code works completely fine, as infinite scroll does exactly what it needs to be.
But when I place it inside another file like
test.php
<div>
<?php include("index.php"); ?>
</div>
the first few posts (7) load and along with the loader.gif at the bottom. That's all.
Any help is greatly appreciated.
After basic understanding on what the error is trying to say, I finally figured out this as
ERROR:
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Object.success (test.php:126)
at i (jquery-3.2.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.2.1.min.js:2)
at A (jquery-3.2.1.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-3.2.1.min.js:4)
JSON should start with a valid JSON value – an object, array, string, number, or false/true/null. This response started with a < (hence the “Unexpected token <”).
That unexpected token, <, is a strong clue that the response was HTML instead of JSON.
The root cause is that the server returned HTML or some other non-JSON string.
So what I did was, just simply cut the JSON code into the top of the test.php leaving everything as it is.
index.php
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<style type="text/css">
body {
font-family: Arial;
background: #e9ebee;
font-size: 0.9em;
}
.post-wall {
background: #FFF;
border: #e0dfdf 1px solid;
padding: 20px;
border-radius: 5px;
margin: 0 auto;
width: 500px;
}
.post-item {
padding: 10px;
border: #f3f3f3 1px solid;
border-radius: 5px;
margin-bottom: 30px;
}
.post-title {
color: #4faae6;
}
.ajax-loader {
display: block;
text-align: center;
}
.ajax-loader img {
width: 50px;
vertical-align: middle;
}
</style>
<div class="post-wall">
<div id="post-list">
<input type="hidden" name="total_count" id="total_count" value="<?= $total_count ?>" />
<input type="hidden" name="offset" id="offset" value="<?= $offset ?>" />
</div>
<div class="ajax-loader text-center">
<img src="LoaderIcon.gif"> Loading more posts...
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
// load the initial rows on page load
let initialData = <?= $data ?? '' ?>;
if (initialData) {
if (initialData.rows) {
addrows(initialData.rows);
$('.ajax-loader').hide();
}
}
windowOnScroll();
});
function windowOnScroll() {
$(window).on("scroll", function(e) {
if ($(window).scrollTop() + 1 >= $(document).height() - $(window).height()) {
if ($(".post-item").length < $("#total_count").val()) {
let offset = $('#offset').val();
getMoreData(offset)
}
}
});
}
function getMoreData(offset) {
$('.ajax-loader').show();
$(window).off("scroll");
let pageUrl = window.location.href.split('?')[0];
$.ajax({
url: pageUrl + '?dataOnly=1&offset=' + offset,
type: "get",
success: function (response) {
response = JSON.parse(response);
if (response.rows) {
addrows(response.rows);
if (response.offset) {
$('#offset').val(response.offset);
}
$('.ajax-loader').hide();
}
windowOnScroll();
}
});
}
function addrows(rows) {
let postList = $("#post-list");
$.each(rows, function (i, row) {
let rowHtml = '<div class="post-item" id="'+row.id+'"><p class="post-title">'+row.title+'</p><p>'+row.content+'</p></div>';
postList.append(rowHtml);
});
}
</script>
test.php
<?php
require_once ('getData.php');
$offset = (int)($_GET['offset'] ?? 0);
$dataOnly = (int)($_GET['dataOnly'] ?? 0);
$limit = 7;
$rows = getData($offset, $limit, $conn);
$offset+= $limit;
$data = [
'rows' => $rows,
'offset' => $offset,
];
$data = json_encode($data);
// if this is an ajax call, stop here and just spit out our json
if ($dataOnly) {
echo $data;
exit;
}
// otherwise, render the page
$sqlQuery = "SELECT * FROM tbl_posts";
$result = mysqli_query($conn, $sqlQuery);
$total_count = mysqli_num_rows($result);
?>
<div class="some">
<?PHP include("index.php"); ?>
</div>
And Voila. It works perfectly fine.
Thanks to #WesleySmith & #AngelDeykov for the time they spared on this.

How to submit HTML form data in Modal Box using PHP ajax?

I want to add state name in my state mysql table in database using PHP and Ajax but the modal box is not submitting the information. I posted all my code for single button submission in model box and are as follows:
My directory structure is:
test.html
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<link rel="stylesheet" type="text/css" href="./model.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js">
</script>
</head>
<body>
<button id="add_state">Add State</button>
<div>
<?php
include('server/connection.php');
$sqlSelect="SELECT * FROM tbl_state_info ORDER By StateName ASC";
$result = $conn -> query ($sqlSelect);
$result = $conn -> query ($sqlSelect);
echo "<select name='StateName'>";
echo "<option>select</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value=$row[StateName]> $row[StateName] </option>";
}
echo "</select>";
?>
</div>
<div id="add_state_model" class="add_state_model">
<div class="add_state_model_content">
<span class="state_model_close">×</span>
<form id="state_submit_form" method="post" action="">
<label>Enter State:</label>
<input type="text" name="state">
<input type="submit" name="state_submit">
</form>
<div class="message_box" style="margin-left: 60px;"></div>
</div>
</div>
<script src="./model.js"></script>
</body>
</html>
and for backend i am using javascript and PHP
model.js
var add_state_model = document.getElementById('add_state_model');
var add_state_button = document.getElementById('add_state');
var add_state_span = document.getElementsByClassName('state_model_close')[0];
add_state_button.onclick = function(){
add_state_model.style.display = "block";
}
add_state_span.onclick = function(){
add_state_model.style.display = "none";
}
window.onclick = function(event) {
if (event.target == add_state_model) {
add_state_model.style.display = "none";
}
}
$(document).ready(function(){
var delay = 1000;
$('[name="state_submit"]').click(function(e){
e.preventDefault();
var state = $('#state_submit_form').find('[name="state"]').val();
if(state === ''){
$('.message_box').html(
'<p><span style="color:red;">Please enter state name!</span></p>'
);
$('[name="state"]').focus();
return false;
}
console.log(state);
$.ajax({
type: "POST",
url: "server/addstate.php",
data: {"state":state},
beforeSend: function() {
$('.message_box').html(
'<img src="./tenor.gif" width="40" height="40"/>'
);
},
success: function(data)
{
setTimeout(function() {
$('.message_box').html(data);
}, 1000);
}
});
});
});
And also there is server page addstate.php
<?php
if ( ($_POST['state']!="") ){
$state = $_POST['state'];
include('connection.php');
/* check connection */
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
//insert query for registration
$insertSql = "INSERT INTO `tbl_state_info`(`StateName`) VALUES ('$state')";
if ($conn->query($insertSql) === TRUE) {
echo "<span style='color:green;'>
<p>State added to dropdown</p>
</span>";
}else{
printf("Error: %s\n", $conn->error);
}
}
?>
and connection.php file
<?php
// set the timezone first
if(function_exists('date_default_timezone_set')) {
date_default_timezone_set("Asia/Kolkata");
}
$conn = new mysqli('localhost', 'root', '');
//check connection
if($conn->connect_error){
die("Connection Failed".$conn->connect_error);
}
//connect database
mysqli_select_db($conn, 'crm');
?>
and the css file model.css, it is used for Model Box pop up
.add_state_model {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content/Box */
.add_state_model_content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 30%; /* Could be more or less, depending on screen size */
}
/* The Close Button */
.state_model_close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.state_model_close:hover,
.state_model_close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
I am getting this below error:
Make me correct if I am not wrong
You can visit this URL this will help you to solve your problem How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?
Or try to change URL path
I have tried on my end it's working for me
url: "http://localhost/CRM/server/addstate.php",
to
url: "server/addstate.php"
If any help feel free to ask me
in your ajax request
data object accept only json object and you have passed query string
try this code
$.ajax({
type: "POST",
url: "http://localhost/CRM/server/addstate.php",
data: {"state":state},
beforeSend: function() {
$('.message_box').html(
'<img src="tenor.gif" width="40" height="40"/>'
);
},
success: function(data)
{
setTimeout(function() {
$('.message_box').html(data);
}, 1000);
}
});
and second thing settimeout accept delay in miliseconds which i have specified 1 second

How to stop <li> elements from overlapping? [duplicate]

This question already has answers here:
Is there ever any reason to use padding-top and padding-bottom for inline elements?
(1 answer)
Padding for Inline Elements
(3 answers)
Closed 4 years ago.
This is my code
ul li{
display:inline;
}
li {
padding: 10px;
border: 1px solid brown;
margin-right: 5px;
position: relative;
background-color: Bisque ;
}
<div class="fr_station">
<span id="route">
<?php
// print_r($route);
$pLine = 0;
$cLine = 0;
echo "<ul>";
foreach ($route as $value) {
$result = mysqli_query($conn,'select station,line,stnCode from stn_name where stnCode='.$value.' LIMIT 1') or die(mysqli_error());
$res = mysqli_fetch_array($result);
echo "<li>".$res['station']."</li>";
//echo str_repeat(" ", 3);
if (!isset($previous)) {
$previous = $source;
$present = $source;
} else {
$current = $value;
$d_result = mysqli_query($conn,'SELECT * FROM alt_station_data WHERE stnCode ='.$previous.' AND nei='.$current.' LIMIT 1');
$d_res = mysqli_fetch_array($d_result);
$tot_dist += $d_res['dis'];
$previous = $value;
echo "</tr>";
$floored = floor($tot_dist);
}
}
echo "</ul>";
echo "</span>";
echo "<br>";
echo "</div>";
When I am printing the elements then the elements from 2nd line is overlapping with the ones on the first line and so on at the end of the line it is printing half content on one line and remaining content on next line.
Try this:
li {
display: inline-block;
}
By using inline each li behaves like a word so doesn’t have it’s own ‘box’. inline-block lets them sit side-by-side but gives each one it’s own ‘box’.
If you need even more control then start looking at flex-box: https://css-tricks.com/snippets/css/a-guide-to-flexbox/ and https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout but don’t forget you will need flex-wrap: wrap
On a side note, with your example it would be easier if you just provide the outputted HTML without the php code as that’s not required. :)

Checking if searched item exists in database - PHP won't output anything but will still add item to the database

I'm learning PHP and am looking to solve my PHP, JS and SQL issue.
If necessary, to ensure you understand exactly what the issue is, you may need you to set up the HTML, CSS, PHP and JS to work with your SQL database. I ask of your time only if you have it.
As you can probably tell, I have a search bar. The user types their interest into the search bar and it adds that interest to the database. If their interest exists in the database (as in someone else has the same interest) it uses an if statement to say so. However, for some reason it will not do anything if an interest is found (not even that test alert). It will however insert something into the database (in this case the number of other existing interests) which is very strange. I have inserted comments in the PHP file to explain what is happening and where the issue is.
Here is the PHP, JS, CSS and HTML respectively:
<?php
error_reporting(E_ALL ^ E_NOTICE);//TO REMOVE THE ANNOYING KEYWORD ERRORS
function connect() {
return new PDO('mysql:host=localhost;dbname=mysite', 'username', 'pw', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
//GET THE USERS IP
if(!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else{
$ip=$_SERVER['REMOTE_ADDR'];
}
$pdo = connect();
//OUTPUT THE SEARCHBAR SUGGESTIONS (OBTAIN SUGGESTIONS FROM DATABASE)
$testing = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM interests WHERE interestName LIKE (:testing) ORDER BY id ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':testing', $testing, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
$interestName = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['interestName']);
$interestlist = '<li onclick="set_item(\''.str_replace("'", "\'", $rs['interestName']).'\')">'.$interestName.'</li>';
if (strlen($_POST['keyword']) > 0){
echo $interestlist; //THIS IS THE SUGGESTION BAR OUTPUT WITH THE SUGGESTIONS
}
}
//EVERYTHING ABOVE THIS WORKS.. THIS IS THE ISSUE HOWEVER:
if(isset($_POST['counter'])=="counter"){
//INSERT THE INTEREST INTO THE DATABASE, WITH THE USER'S IP.
$interestid=$_POST['interestinput'];
$insertion = "INSERT INTO users (ipaddress, interest)
VALUES ('$ip', '$interestid')";
$pdo->query($insertion);
//INSERTION WORKS. NOW I WANT TO CHECK IF INTEREST EXISTS. IF IT DOES EXIST, PRINT 'Users exist!':
$item ="SELECT * FROM `users` WHERE interest LIKE '$interestid'";
$result = $pdo->query($item)->fetchAll();
$counted = count($result); //COUNT NUMBER OF RESULTS, THEN INSERT IT AS A TEST.
$insertion = "INSERT INTO users (ipaddress, interest)
VALUES ('$ip', '$counted')";
if (count($result) > 1) {
$pdo->query($insertion); //TEST IF IT WORKS -- THIS INSERTS THE TOTAL NUMBER OF SAME INTERESTS. IT WORKS!
//BUT..
echo ("Users exist!"); //THIS DOES NOTHING? <--------- THE ISSUE
echo "<script> alert('Test'); </script>"; //THIS ALSO DOES NOTHING (as a test)
}
}
?>
//THIS FUNCTION IS CALLED WHEN THE USER HITS ENTER:
function enterPressed(e, field) {
if (e.keyCode == 13) {
var tb = document.getElementById("searchbox");
if (field.value.length > 0) {
document.getElementById('searching').style.display='block';
document.getElementById('searchdisappear').style.display='none';
$.ajax({
type: 'POST',
url: './php/phprefresh.php',
data: {interestinput: field.value, counter: "counter"},
});
}
}
}
//THIS FUNCTION GIVES INTEREST SUGGESTIONS (PULLED FROM THE DATABASE):
function autocomplet() {
var workchecker = 0
var min_length = 1;
var keyword = $('#searchbox').val();
if (keyword.length == min_length) {
$.ajax({
url: './php/phprefresh.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#interest_list_id').show();
$('#interest_list_id').html(data);
}
});
} else {
$('#interest_list_id').hide();
}
}
//THIS FUNCTION SETS THE SUGGESTION INTO THE SEARCH BOX WHEN CLICKED
function set_item(item) {
$('#searchbox').val(item);
$('#interest_list_id').hide();
}
/*Input*/
input.interestsearch {
margin: auto;
margin-top: 30px;
width: 540px;
height: 30px;
font-size: 22px;
display: block;
padding: 2px 2px 2px 8px;
outline: none;
}
.input_container {
padding: auto;
margin: auto;
margin-top: -10px;
width: 520px;
display: block;
outline: none;
font-size: 20px;
}
.input_container ul {
list-style: none;
border-radius: 15px;
padding: 5px;
color: black;
}
.input_container ul li:hover {
border: 1px solid black;
border-radius: 15px;
cursor: pointer;
width: 500px
}
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Testsite</title>
<link rel="stylesheet" type="text/css" href="./css/main.css">
<script src ="./js/search.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body">
<!-- SEARCH BAR -->
<div id="searchdisappear" style="display:block;">
<center><h1> INTEREST SEARCH </h1></center>
<input class="interestsearch" id="searchbox" maxlength="200" type="text" title="Search for an interest" onkeyup="autocomplet();" autocomplete="off" onkeypress="enterPressed(event, searchbox);" placeholder="Search for an interest.."/>
<div class="input_container">
<ul id="interest_list_id"></ul>
</div>
</div>
<!-- CONNECTING PEOPLE WITH SAME INTEREST-->
<div id="searching" style="display:none;">
<center> <p>Finding people..</p></center>
</div>
</html>
Do not hesitate to ask any questions about the code. I am happy to answer anything!
I really appreciate anyone's time. It has been driving me crazy for far too long.
Add a
<div id="response"></div>
to your HTML which will display the result then add a success: argument in the enterPressed function. ie.
function enterPressed(e, field) {
if (e.keyCode == 13) {
var tb = document.getElementById("searchbox");
if (field.value.length > 0) {
document.getElementById('searching').style.display='block';
document.getElementById('searchdisappear').style.display='none';
$.ajax({
type: 'POST',
url: './php/phprefresh.php',
data: {interestinput: field.value, counter: "counter"},
success: function() {
$("#response").html("<p>User Exists</p>");
}
});
}
}
}
If you want to display echo text (in HTML form) from phprefresh.php change the success: to
success: function(data) {
$("#response").html(data);
}

How to replace document.write with document.getElementById('ElementID').innerHTML [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Just to let you know I am not a programmer. I try to understand some code and change it where I can using trial and error.
I have the following piece of code from a Joomla module where I need to change in the function: function pausescroller the document.write function that is used to document.getElementById('ElementID').innerHTML and I don't know how. I am posting the code of the function function pausescroller where I tried implementing the above w/o luck. Nothing displays on front end:
function pausescroller(content, divId, divClass, delay){
this.content=content //message array content
this.tickerid=divId //ID of ticker div to display information
this.delay=delay //Delay between msg change, in miliseconds.
this.mouseoverBol=0 //Boolean to indicate whether mouse is currently over scroller (and pause it if it is)
this.hiddendivpointer=1 //index of message array for hidden div
document.getElementById('divId').innerHTML = "<div id="'+divId+'" class="'+divClass+'" style="position: relative; overflow: hidden"><div class="innerDiv" style="position: absolute; width: 100%" id="'+divId+'1">'+content[0]+'</div><div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" id="'+divId+'2">'+content[1]+'</div></div>";
//document.write('<div id="'+divId+'" class="'+divClass+'" style="position: relative; overflow: hidden"><div class="innerDiv" style="position: absolute; width: 100%" id="'+divId+'1">'+content[0]+'</div><div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" id="'+divId+'2">'+content[1]+'</div></div>')
var scrollerinstance=this
if (window.addEventListener) //run onload in DOM2 browsers
window.addEventListener("load", function(){scrollerinstance.initialize()}, false)
else if (window.attachEvent) //run onload in IE5.5+
window.attachEvent("onload", function(){scrollerinstance.initialize()})
else if (document.getElementById) //if legacy DOM browsers, just start scroller after 0.5 sec
setTimeout(function(){scrollerinstance.initialize()}, 500)
}
HERE IS THE CODE OF THE WHOLE JavaScript part:
<script type="text/javascript">
<!--
var pausecontent=new Array();
var cnti = 0;
<?php
for($im=0; $im<count($testi_RSMSC); $im++) {
$dateExp_RSMSC = explode('-', $testi_RSMSC[$im]['date']);
$timestamp_RSMSC = mktime(12,0,0,$dateExp_RSMSC[1],$dateExp_RSMSC[2],$dateExp_RSMSC[0]);
$dateConfig_RSMSC = JFactory::getConfig();
$siteLang_RSMSC = $dateConfig_RSMSC->get('config.language');
setlocale(LC_ALL, $siteLang_RSMSC);
$dateView_RSMSC = strftime("%d %B %Y", $timestamp_RSMSC);
$testi_RSMSC[$im]['comment'] = preg_replace('/\s\s+/', ' ', trim($testi_RSMSC[$im]['comment']));
$testi_text = '';
if($char_RSMSC > 0) {
$testi_text .= substr($testi_RSMSC[$im]['comment'], 0, ($char_RSMSC-3)).'...';
} else {
$testi_text .= $testi_RSMSC[$im]['comment'];
}
####
$RStesti_pic_file = '';
if($imgDispRSMSC == '1') {
if(file_exists(JPATH_ROOT.DS.'images'.DS.'com_rsmonials'.DS.$testi_RSMSC[$im]['id'].'.gif')) {
$RStesti_pic_file = '<img src="'.JURI::root().'images/com_rsmonials/'.$testi_RSMSC[$im]['id'].'.gif" style="max-width:'.$imgMwRSMSC.'px; max-height:'.$imgMhRSMSC.'px; border:'.$imgBorderRSMSC.';" />';
} else if(file_exists(JPATH_ROOT.DS.'images'.DS.'com_rsmonials'.DS.$testi_RSMSC[$im]['id'].'.png')) {
$RStesti_pic_file = '<img src="'.JURI::root().'images/com_rsmonials/'.$testi_RSMSC[$im]['id'].'.png" style="max-width:'.$imgMwRSMSC.'px; max-height:'.$imgMhRSMSC.'px; border:'.$imgBorderRSMSC.';" />';
} else if(file_exists(JPATH_ROOT.DS.'images'.DS.'com_rsmonials'.DS.$testi_RSMSC[$im]['id'].'.jpg')) {
$RStesti_pic_file = '<img src="'.JURI::root().'images/com_rsmonials/'.$testi_RSMSC[$im]['id'].'.jpg" style="max-width:'.$imgMwRSMSC.'px; max-height:'.$imgMhRSMSC.'px; border:'.$imgBorderRSMSC.';" />';
} else if(file_exists(JPATH_ROOT.DS.'images'.DS.'com_rsmonials'.DS.$testi_RSMSC[$im]['id'].'.jpeg')) {
$RStesti_pic_file = '<img src="'.JURI::root().'images/com_rsmonials/'.$testi_RSMSC[$im]['id'].'.jpeg" style="max-width:'.$imgMwRSMSC.'px; max-height:'.$imgMhRSMSC.'px; border:'.$imgBorderRSMSC.';" />';
} else {
$RStesti_pic_file = $RS_noimg;
}
if($imgAlignRSMSC == '1') {
$RStesti_pic_file = '<div style="margin-bottom:5px; text-align:left;">'.$RStesti_pic_file.'</div>';
} else if($imgAlignRSMSC == '2') {
$RStesti_pic_file = '<div style="margin-bottom:5px; text-align:right;">'.$RStesti_pic_file.'</div>';
} else if($imgAlignRSMSC == '3') {
$RStesti_pic_file = '<span style="float:left; margin-right:5px;">'.$RStesti_pic_file.'</span>';
} else if($imgAlignRSMSC == '4') {
$RStesti_pic_file = '<span style="float:right; margin-left:5px;">'.$RStesti_pic_file.'</span>';
} else {
$RStesti_pic_file = '<div style="margin-bottom:5px; text-align:center;">'.$RStesti_pic_file.'</div>';
}
}
####
$RSMSC_disp_context = '<div style="text-align:'.$alignRSMSC.';">'.$RStesti_pic_file.addslashes($testi_text).'</div><br /><em><strong>'.addslashes($testi_RSMSC[$im]['fname']).' '.addslashes($testi_RSMSC[$im]['lname']).'</strong>';
if($displayaboutRSMSC == '1') {
if(($testi_RSMSC[$im]['about'] != '') || ($testi_RSMSC[$im]['location'] != '')) {
$RSMSC_disp_context .= ', Ηλικία: <small>';
$RS_isa = 0;
if($testi_RSMSC[$im]['about'] != '') {
$RSMSC_disp_context .= addslashes($testi_RSMSC[$im]['about']);
$RS_isa = 1;
}
if($testi_RSMSC[$im]['location'] != '') {
if($RS_isa == '1') {
$RSMSC_disp_context .= ', ';
}
$RSMSC_disp_context .= addslashes($testi_RSMSC[$im]['location']);
}
$RSMSC_disp_context .= '</small>';
}
}
if(($displayurlRSMSC == '1') && ($testi_RSMSC[$im]['website'] != '')) {
$RSMSC_disp_context .= '<br /><small>'.$testi_RSMSC[$im]['website'].'</small>';
}
if($displaydateRSMSC == '1') {
$RSMSC_disp_context .= '<br /><small>'.$dateView_RSMSC.'</small>';
}
$RSMSC_disp_context .= '</em>';
?>
pausecontent[cnti++]='<?php echo $RSMSC_disp_context; ?>';
<?php
}
?>
function pausescroller(content, divId, divClass, delay){
this.content=content //message array content
this.tickerid=divId //ID of ticker div to display information
this.delay=delay //Delay between msg change, in miliseconds.
this.mouseoverBol=0 //Boolean to indicate whether mouse is currently over scroller (and pause it if it is)
this.hiddendivpointer=1 //index of message array for hidden div
document.getElementById(divId).innerHTML = '<div class="innerDiv" style="position: absolute; width: 100%" id="' + divId + '1">' + content[0] + '</div><div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" id="' + divId + '2">' + content[1] + '</div>';
//document.write('<div id="'+divId+'" class="'+divClass+'" style="position: relative; overflow: hidden"><div class="innerDiv" style="position: absolute; width: 100%" id="'+divId+'1">'+content[0]+'</div><div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" id="'+divId+'2">'+content[1]+'</div></div>')
var scrollerinstance=this
if (window.addEventListener) //run onload in DOM2 browsers
window.addEventListener("load", function(){scrollerinstance.initialize()}, false)
else if (window.attachEvent) //run onload in IE5.5+
window.attachEvent("onload", function(){scrollerinstance.initialize()})
else if (document.getElementById) //if legacy DOM browsers, just start scroller after 0.5 sec
setTimeout(function(){scrollerinstance.initialize()}, 500)
}
/* initialize()- Initialize scroller method. -Get div objects, set initial positions, start up down animation */
pausescroller.prototype.initialize=function(){
this.tickerdiv=document.getElementById(this.tickerid)
this.visiblediv=document.getElementById(this.tickerid+"1")
this.hiddendiv=document.getElementById(this.tickerid+"2")
this.visibledivtop=parseInt(pausescroller.getCSSpadding(this.tickerdiv))
//set width of inner DIVs to outer DIV's width minus padding (padding assumed to be top padding x 2)
this.visiblediv.style.width=this.hiddendiv.style.width=this.tickerdiv.offsetWidth-(this.visibledivtop*2)+"px"
this.getinline(this.visiblediv, this.hiddendiv)
this.hiddendiv.style.visibility="visible"
var scrollerinstance=this
document.getElementById(this.tickerid).onmouseover=function(){scrollerinstance.mouseoverBol=1}
document.getElementById(this.tickerid).onmouseout=function(){scrollerinstance.mouseoverBol=0}
if (window.attachEvent) //Clean up loose references in IE
window.attachEvent("onunload", function(){scrollerinstance.tickerdiv.onmouseover=scrollerinstance.tickerdiv.onmouseout=null})
setTimeout(function(){scrollerinstance.animateup()}, this.delay)
}
/* animateup()- Move the two inner divs of the scroller up and in sync */
pausescroller.prototype.animateup=function(){
var scrollerinstance=this
if (parseInt(this.hiddendiv.style.top)>(this.visibledivtop+5)){
this.visiblediv.style.top=parseInt(this.visiblediv.style.top)-5+"px"
this.hiddendiv.style.top=parseInt(this.hiddendiv.style.top)-5+"px"
setTimeout(function(){scrollerinstance.animateup()}, 50)
}
else{
this.getinline(this.hiddendiv, this.visiblediv)
this.swapdivs()
setTimeout(function(){scrollerinstance.setmessage()}, this.delay)
}
}
/* swapdivs()- Swap between which is the visible and which is the hidden div */
pausescroller.prototype.swapdivs=function(){
var tempcontainer=this.visiblediv
this.visiblediv=this.hiddendiv
this.hiddendiv=tempcontainer
}
pausescroller.prototype.getinline=function(div1, div2){
div1.style.top=this.visibledivtop+"px"
div2.style.top=Math.max(div1.parentNode.offsetHeight, div1.offsetHeight)+"px"
}
/* setmessage()- Populate the hidden div with the next message before it's visible */
pausescroller.prototype.setmessage=function(){
var scrollerinstance=this
if (this.mouseoverBol==1) //if mouse is currently over scoller, do nothing (pause it)
setTimeout(function(){scrollerinstance.setmessage()}, 100)
else{
var i=this.hiddendivpointer
var ceiling=this.content.length
this.hiddendivpointer=(i+1>ceiling-1)? 0 : i+1
this.hiddendiv.innerHTML=this.content[this.hiddendivpointer]
this.animateup()
}
}
pausescroller.getCSSpadding=function(tickerobj){ //get CSS padding value, if any
if (tickerobj.currentStyle)
return tickerobj.currentStyle["paddingTop"]
else if (window.getComputedStyle) //if DOM2
return window.getComputedStyle(tickerobj, "").getPropertyValue("padding-top")
else
return 0
}
//new pausescroller(name_of_message_array, CSS_ID, CSS_classname, pause_in_miliseconds)
new pausescroller(pausecontent, "rsmsc_scroller", "rsmsc_scroller_class", <?php echo $delay_RSMSC; ?>);
//-->
</script>
Change this line:
document.getElementById('divId').innerHTML = "<div id="'+divId+'" class="'+divClass+'" style="position: relative; overflow: hidden"><div class="innerDiv" style="position: absolute; width: 100%" id="'+divId+'1">'+content[0]+'</div><div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" id="'+divId+'2">'+content[1]+'</div></div>";
to this:
document.getElementById(divId).innerHTML = '<div class="innerDiv" style="position: absolute; width: 100%" id="' + divId + '1">' + content[0] + '</div><div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" id="' + divId + '2">' + content[1] + '</div>';
(The very first, and very last double quote, should be single quotes, and do not put quotes around the var name divid when calling document.getElementById(divId).innerHTML)
-EDIT- But actually the element you are looking for is not there yet, place the parent div into the html first '<div id="myDiv" class="divClass" style="position: relative; overflow: hidden"></div> then if var divId = 'myDiv'; call the function with:
pausescroller(content, divId, divClass, delay);
The value you set innerHTML to needs to be a complete string - adding ' to each side will fix it:
document.getElementById('divId').innerHTML = '"<div id="'+divId+'" class="'+divClass+'" style="position: relative; overflow: hidden"><div class="innerDiv" style="position: absolute; width: 100%" id="'+divId+'1">'+content[0]+'</div><div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" id="'+divId+'2">'+content[1]+'</div></div>";'

Categories

Resources