Live search - Ajax, PHP - javascript

I have a little problem with the live search form. Below is what I want:
This is what I want. What I have is:
And Screenshot of my problem.
The general problem of Screenshot 3 when I type something in Keyword? field, when I get the result that the field gets bigger and that is what I don't need. The result field is good, exactly what I need. So problem is, I don't need to get a bigger field Keyword? after some user enters some text into that field. Keyword? field the same size, result div size wider.
Bellow, I will paste my code.
HTML:
<div class="header-search-input-item">
<input type="text" name="search" id="search" autocomplete="off" placeholder="Keywords?" value=""/>
<div class="resultDiv"></div>
<div class="clearfix"></div>
</div>
CSS:
.clearfix { clear:both; }
.sp { clear:both; display:block; margin-bottom:30px; }
.sp a { font-weight:bold; color:#0099FF; }
label { margin-top:20px; margin-bottom:3px; font-weight:bold;}
.searchDiv {
width:130px;
}
.resultDiv {
display:none;
width:auto;
margin-top:40px;
max-height:200px;
overflow:auto;
border:1px solid #0099FF;
padding:5px;
z-index:999;
background-color:#fff;
}
.search {
width: 100%;
float: left;
margin:0;
padding:0;
}
.search .pret {
list-style:none;
clear:both;
width:100%;
height: 60px;
padding:5px 0;
border-bottom: 1px solid #fff;
}
.search .pret:hover, .search .pret:hover > a {
background-color:#0099FF;
color:#fff;
cursor:pointer;
}
.search img {
float:left;
margin:0 5px;
padding:3px;
border:1px solid #ccc;
border-radius:5px;
}
.search a {
text-decoration:none;
color:#666;
display:inline;
}
JS:
$(document).ready(function() {
$("#search").keyup(function() {
var keywords = $(this).val();
if(keywords != "") {
$.ajax({
url: "get_search_result.php",
data: {keywords : keywords},
type: "POST",
success: function(resp) {
if(resp != "") {
$(".resultDiv").html(resp).show();
} else {
$(".resultDiv").html("").hide();
}
}
});
} else {
$(".resultDiv").html("").hide();
}
});
$(document).click(function() {
$("#search").val("");
$(".resultDiv").html("").hide();
});
});
And PHP File:
<?php include("db.php");?>
<?php
if(isset($_POST['keywords'])) {
$keywords_arr = explode(",", mysqli_real_escape_string($con, $_POST['keywords']));
$like = "";
foreach($keywords_arr as $key) {
$key = trim($key);
if($key != "") $like .= " `VehiclesTitle` like '%".$key."%' or";
}
$like = substr($like, 0, -3);
$sql = "select distinct * from `tblvehicles` where ".$like." limit 20";
$res = mysqli_query($con, $sql);
echo "<ul class='search'>";
if(mysqli_num_rows($res) > 0) {
while($row = mysqli_fetch_object($res)) {
if(file_exists("admin/img/vehicleimages/".$row->Vimage1."")) $img = "admin/img/vehicleimages/".$row->Vimage1."";
else $img = "images/post_images/default.jpg";
echo "<li class='pret'><a href=''><img src='".$img."' width='50' height='50' />".$row->VehiclesTitle."</a></li>";
}
} else {
echo "<li class='pret'>No match found!</li>";
}
echo "</ul>";
echo "<div class='clearfix'></div>";
}
?>

Related

Need help in drag and drop uploading

When I select and drag and drop multiple files in the drop files area, it goes to Uploads folder but I see only one item under the drop files area each time when uploading.
I want to show multiple files instead of one file/item under the drop files area when uploading.
How can I do that?
if(file_exists($serverpath)) is not working. I don't know why.
Can you people look into it?
I want the same uploaded file rename from 0 to 1,2,3 when I upload files when files exist(if(file_exists($serverpath))) in Uploads folder.
When I click on a image it shows a image box.
I need the .Crop-Box resizable and draggable.
I am using mozilla firefox and google chrome.
Here is the code:
*{margin:0; padding:0;}
body{background:black;}
#Container{
margin:200px auto;
width:620px;
padding-bottom:20px;
background:#ffffff;
color:black;
border:1px solid gray;
border-radius:5px;
}
#Text{
margin:20px;
color:green;
font-family:verdana;
font-size:12pt;
}
#Drop{
margin:20px auto;
padding:20px;
color:gray;
width:500px;
height:40px;
background:#f1f1f1;
border:1px dotted #ccc;
border-radius:5px;
}
.progressbar{
margin:20px auto;
width:80%;
height:20px;
background:#ddd;
border-radius:5px;
display:none;
}
.progress{
width:0%;
height:20px;
border-radius:5px;
background:linear-gradient(to bottom, lightblue, #2196f3);
}
.progresstext{
float:right;
}
.InsertInto{
margin-top:20px;
}
.image{
margin:20px;
width:15%;
height:20%;
display:none;
}
.FileDiv{
margin-bottom:20px;
}
.filenam{
position:absolute;
margin-top:-57px;
margin-left:140px;
}
#RealFile{
margin:20px;
display:none;
}
#UploadImage{
margin-left:100px;
padding:20px 200px;
background:#2196f3;
color:white;
border:none;
border-radius:5px;
cursor:pointer;
}
button:focus{
outline:none;
}
#Submit{
margin-left:100px;
padding:20px 200px;
background:#219549;
color:white;
border:none;
border-radius:5px;
cursor:pointer;
}
.Crop-Main{
position:relative;
width:600px;
min-width:600px;
height:520px;
margin:100px auto;
padding:20px;
background:#f1f1f1;
color:black;
border:1px solid #ccc;
border-radius:5px;
z-index:1;
display:none;
}
#Close{
background:#2196f3;
color:white;
padding:10px;
font-family:verdana;
font-size:12pt;
cursor:pointer;
border-radius:5px;
margin:20px;
margin-right:0px;
float:right;
user-select:none;
}
.Crop-Container{
position:relative;
width:600px;
margin:80px auto;
min-height:300px;
}
.Crop-Container img{
width:600px;
user-select:none;
}
.Crop-Box{
position:absolute;
width:200px;
height:200px;
top:0;
left:0;
background:rgba(69,69,69,0.6);
border:1px solid white;
z-index:2;
cursor:move;
}
#Save{
position:absolute;
padding:20px 80px;
background:green;
color:white;
border:none;
border-radius:5px;
font-family:verdana;
font-size:12pt;
cursor:pointer;
margin:-70px 200px;
}
.InsertInto img{
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="jquery.min.js"></script>
<body>
<div class="Crop-Main">
<span id="Close">X</span>
<div class="Crop-Container">
<img src=""/>
<div class="Crop-Box"></div>
</div>
<button id="Save" onclick="save()">Save</button>
</div>
<div id="Container">
<div id="Text">Advanced File Uploader</div>
<div id="Drop">Drop files here</div>
<div class="progressbar">
<div class="progress"></div>
<div class="progresstext">0%</div>
</div>
<div class="InsertInto">
</div>
<input type="file" name="realfile" id="RealFile" multiple="true"><br/><br/>
<button id="UploadImage" type="button">Upload</button>
<br/><br/>
<form action="uploads.php" method="POST" id="myForm" enctype="multipart/form-data">
<input type="submit" name="submit" id="Submit" value="Submit">
</form>
</div>
<script>
var obj = document.querySelector("#Drop");
var realf = document.querySelector("#RealFile");
obj.ondragover = function(e){
$(this).css("border-color","green");
return false;
}
obj.ondragleave = function(e){
return false;
$(this).css("border","none");
}
obj.ondrop = function(e){
e.preventDefault();
$(this).css("border-color","#2196f3");
var files = e.dataTransfer.files;
upload(files);
console.log(files);
}
realf.onchange = function(e){
var files = e.currentTarget.files;
upload(files);
console.log(files);
}
function upload(e){
var formdata = new FormData();
var xhttp = new XMLHttpRequest();
var i;
for(i=0; i < e.length; i++){
formdata.append("realfile[]", e[i]);
}
if(xhttp.upload){
xhttp.open("POST", "upload.php", true);
xhttp.upload.addEventListener("progress", function(e){
var parcent = (e.loaded / e.total) * 100;
document.querySelector(".progressbar").style.display = "block";
document.querySelector(".progress").style.width = parcent+"%";
document.querySelector(".progresstext").innerHTML = parcent+"%";
});
xhttp.onreadystatechange = function(){
if(xhttp.readyState == 4 && xhttp.status == 200){
var result;
result = this.responseText;
var newresult = JSON.parse(result);
var i;
document.querySelector(".progressbar").style.display = "none";
var insertinto = document.querySelector(".InsertInto");
var filediv = document.createElement("DIV");
filediv.className = "FileDiv";
insertinto.appendChild(filediv);
var img = document.createElement("IMG");
img.className = "image";
filediv.appendChild(img);
img.setAttribute("src",newresult.url);
img.setAttribute("width","100%");
img.setAttribute("height","100%");
img.style.display = "block";
img.addEventListener("click", function(e){
var cropmain = document.querySelector(".Crop-Main");
cropmain.style.display = "block";
document.querySelector("#Container").style.display = "none";
var imgsrc = $(this).attr("src");
$(".Crop-Container img").attr("src", imgsrc);
});
var close = document.querySelector("#Close");
close.addEventListener("click", function(e){
document.querySelector(".Crop-Main").style.display = "none";
document.querySelector("#Container").style.display = "block";
});
var filenam = document.createElement("DIV");
filenam.className = "filenam";
filenam.innerHTML = newresult.name;
insertinto.appendChild(filenam);
if(newresult != "" && newresult != "Not Ok"){
for(i=0; i<newresult.length; i++){
if(newresult[i].status == true){
}
}
}
console.log(xhttp.responseText);
}
}
xhttp.send(formdata);
}
}
$("#UploadImage").click(function(e){
$("#RealFile").click();
});
$(".InsertInto").on("click", ".InsertInto img", function(){
var img = $(this).attr("src");
$(".Crop-Container").find("img").attr("src", img);
var w = $(".Crop-Container img").width();
var h = $(".Crop-Container img").height();
$(".Crop-Container").width(w);
$(".Crop-Container").height(h);
document.querySelector(".Container").style.display = "none";
document.querySelector(".Crop-Main").style.display = "block";
});
</script>
</body>
</html>
PHP
<?php
$status = array();
$allow = array("image/jpeg", "image/png");
//print "<pre>"
//print_r($_FILES["file"]);
//print "</pre>"
foreach($_FILES["realfile"]["name"] as $pos => $val){
if(!in_array(strtolower($_FILES["realfile"]["type"][$pos]), $allow)){
$status = array(
"name" => $_FILES["realfile"]["name"],
"type" => $_FILES["realfile"]["type"],
"url" => "",
"message" => "Invalid file type",
"status" => false
);
}
else{
$tmpname = $_FILES['realfile']['tmp_name'][$pos];
$filename = $_FILES["realfile"]["name"][$pos];
//$path = "Uploads/".$filename;
$addition = 0;
$serverpath = $_SERVER['DOCUMENT_ROOT']."Uploads/".$filename;
if(file_exists($serverpath)){
while(file_exists($serverpath)){
$addition = $addition + 1;
$info = pathinfo($serverpath);
$directory = $info["dirname"];
$oldname = $info["filename"];
$oldext = $info["extension"];
$serverpath = $directory."/".$oldname.$addition.".".$oldext;
}
$serverpath = "Uploads/".$oldname.$addition.".".$oldext;
}
else{
$serverpath = "Uploads/".$filename;
}
move_uploaded_file($tmpname, $serverpath);
$status = array(
"name" => $_FILES["realfile"]["name"][$pos],
"type" => $_FILES["realfile"]["type"][$pos],
"url" => $serverpath,
"message" => "File Uploaded",
"status" => true
);
}
}
echo json_encode($status);
?>

Onclick javascript function doesn't work on first click

I've wrote a code to hide/show a div by clicking on a "p" element, but at first click nothing happens.
Only from 2nd click the code works as expected.
I've read some similar questions and I've understood that it's probably a style problem.
So I've tried to change style (without really knowing what I was doing) but I wasn't lucky.
I've also another problem: the "p" element sometimes covers an input and I've not understood how to have it on the bottom right of the div but below every other element.
<!DOCTYPE html>
<html>
<head>
<style>
.Class1 {
position:relative;
display: inline-block;
width: 48%;
margin: 3px;
border: 3px solid #CCC;
}
.Class2 {
position:absolute;
bottom:0;
right:0;
border: 1px solid #CCC;
margin:1px;
background: #FFC;
}
.Fields {
clear: both;
border: 1px solid #CCC;
display: inline-block;
margin:3px;
}
.H_p {
border: 1px solid #CCC;
display: inline-block;
}
.Opt {
border: 1px solid #CCC;
display: none;
}
</style>
</head>
<body>
<h2>My test</h2>
<?php
$Divs = array('Div1'=>'Class1',
'Div2'=>'Class1',
'Div3'=>'Class1',
'Div4'=>'Class1',
'Div5'=>'Class1');
$AskToShow=array("Field1"=>"1.1.1", "Field2"=>"1.2.1", "Field3"=>"1.3.1");
foreach ($Divs as $Name=>$Class){
echo '
<div class="'.$Class.'">';
echo $Name.'<br/>';
foreach ($AskToShow as $I_Name=>$Id){
echo '
<label>'.$I_Name.'</label>
<input type="text" id="'.$Id.'" class="Fields"/>';
}
echo '
<p id="Btn_Opt'.$Name.'" class="Class2" >Mostra campi opzionali</p>';
echo '
<div id=Opt'.$Name.' name="Opt'.$Name.'" class="Opt" >';
foreach ($AskToShow as $H_Name=>$Id){
echo'
<p id="H_'.$Id.'" class="H_p">'.$H_Name.'</p>';
}
echo '
</div>';
echo '
</div>';
}
?>
<script>
var MyClass = document.getElementsByClassName("Class2");
var myFunction = function() {
var SenderId = this.id;
var SubId = SenderId.substring(SenderId.indexOf('_')+1)
var SubSH = document.getElementById(SubId);
if (SubSH.style.display == 'none'){
SubSH.style.display = 'inline-block';
}else{
SubSH.style.display = 'none';
}
};
for (var i = 0; i < MyClass.length; i++) {
MyClass[i].addEventListener('click', myFunction, false);
}
</script>
</body>
</html>
The thing is that when you do SubSH.style.display you are checking only inline style so something which is inn <your-tag style='...'/> but you have it in your stylesheet so it is not accessible by this method. try to change your function a bit - for example
var myFunction = function() {
var SenderId = this.id;
var SubId = SenderId.substring(SenderId.indexOf('_')+1)
var SubSH = document.getElementById(SubId);
var style = window.getComputedStyle(SubSH);
if (style.display == 'none'){
SubSH.style.display = 'inline-block';
}else{
SubSH.style.display = 'none';
}
};
by using window.getComputedStyle(SubSH); you are checking style which is aware of all your classes and csses
Please find the working code below
<!DOCTYPE html>
<html>
<head>
<style>
.Class1 {
position:relative;
display: inline-block;
width: 48%;
margin: 3px;
border: 3px solid #CCC;
}
.Class2 {
position:relative;
bottom:0;
right:0;
border: 1px solid #CCC;
margin:1px;
background: #FFC;
display: inline-block;
float:right;
}
.Fields {
clear: both;
border: 1px solid #CCC;
display: inline-block;
margin:3px;
}
.H_p {
border: 1px solid #CCC;
display: inline-block;
}
.Opt {
border: 1px solid #CCC;
display: none;
}
</style>
</head>
<body>
<h2>My test</h2>
<?php
$Divs = array(
'Div1' => 'Class1',
'Div2' => 'Class1',
'Div3' => 'Class1',
'Div4' => 'Class1',
'Div5' => 'Class1'
);
$AskToShow = array(
"Field1" => "1.1.1",
"Field2" => "1.2.1",
"Field3" => "1.3.1"
);
foreach ($Divs as $Name => $Class) {
echo '
<div class="' . $Class . '">';
echo $Name . '<br/>';
foreach ($AskToShow as $I_Name => $Id) {
echo '
<label>' . $I_Name . '</label>
<input type="text" id="' . $Id . '" class="Fields"/>';
}
echo '
<div id=Opt' . $Name . ' name="Opt' . $Name . '" class="Opt" >';
foreach ($AskToShow as $H_Name => $Id) {
echo '
<p id="H_' . $Id . '" class="H_p">' . $H_Name . '</p>';
}
echo '
</div>';
echo '
<div style="clear:both;"></div>';
echo '
<p id="Btn_Opt' . $Name . '" class="Class2" >Mostra campi opzionali</p>';
echo '
</div>';
}
?>
<script>
var MyClass = document.getElementsByClassName("Class2");
var myFunction = function() {
var SenderId = this.id;
var SubId = SenderId.substring(SenderId.indexOf('_')+1)
var SubSH = document.getElementById(SubId);
if (window.getComputedStyle(SubSH, null).display == 'none'){
SubSH.style.display = 'inline-block';
} else {
SubSH.style.display = 'none';
}
};
for (var i = 0; i < MyClass.length; i++) {
MyClass[i].addEventListener('click', myFunction, false);
}
</script>
</body>
</html>

I can't figure out why popup disappears & reappears when there's an error or when it sends

I wrote a popup for signing up with a website. It works fine except for one aspect - when the user fails to provide all the necessary info, the popup will disappear but then reappear with the error message. Likewise, if the user provides all the info and clicks send, the message will send successfully but the popup disappears and then reappears with the success message. When the user clicks close, the popup closes and stays gone like it should.
I've been going over the code and I just can't find out why it disappears and then reappears. I want it to stay there and display either the error message or success message and then to only disappear when the user clicks "close." Here is the following code - HTML, CSS, JS and PHP
Here's the website so you can see it in action.
I appreciate any and all advice! Thanks
HTML
<?php include $_SERVER['DOCUMENT_ROOT']. '/php/signup-popup.php'; ?>
<div id="pop-wrapper">
<!-- Popup Div Starts Here -->
<div id="popupContact">
<!-- Contact Us Form -->
<form action="#" id="form" method="post" name="form">
<h2 id="popup-h2">Join the Civil War Digital Digest</h2>
<hr>
<input id="name" name="name" placeholder="Name" type="text" value="<?php echo htmlspecialchars($_POST['name']);?>">
<input id="email" name="email" placeholder="Email" type="text" value="<?php echo htmlspecialchars($_POST['email']);?>">
<textarea id="msg" name="message" placeholder="Message"><?php echo htmlspecialchars($_POST['message']);?></textarea>
<?php echo "<p id='error-message' class='text-danger'>$errError</p>";?>
<?php echo $result; ?>
<button id="submit" name="submit" type="submit" value="Send">Send</button>
<br>
<button onclick="hide()" id="close">Close</button>
</form>
</div>
<!-- Popup Div Ends Here -->
</div>
Javascript
function show() {
if(sessionStorage.getItem("close") == null){
document.getElementById('pop-wrapper').style.display = "block";
}
else {
document.getElementById('pop-wrapper').style.display = "none";
}
}
function hide(){
sessionStorage.setItem("close", 1);
document.getElementById('pop-wrapper').style.display = "none";
}
window.onload=function(){
setTimeout(function(){
show();
}, 500);
}
PHP
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'Civil War Digital Digest Popup Form';
$to = 'kennethpavia#gmail.com';
$subject = 'Message from CWDD Popup Form ';
$body ="From:\n Name: $name\n E-Mail: $email\n Message:\n $message";
// Check for errors
if (!$_POST['name'] || !$_POST['email'] || !$_POST['message']) {
$errError = 'Some information is missing. Unable to send.';
}
// If there are no errors, send the email
if (!$errError) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Message sent. Thank you for contacting the CWDD.</div>';
} else {
$result='<div class="alert alert-danger">Sorry, there was an error sending your message. Please try again.</div>';
}
}
}
?>
CSS
/* popup header color #394650 */
/*font IM Fell DW Pica */
/*----------------------------------------------
CSS settings for HTML div Exact Center
------------------------------------------------*/
#pop-wrapper {
width:100%;
height:100%;
opacity:.99;
top:0;
left:0;
display:none;
position:fixed;
background-color:#313131;
overflow:auto;
}
div #popupContact {
position:absolute;
left:50%;
top:17%;
margin-left:-202px;
font-family:'IM Fell DW Pica', serif;
}
form {
width: 450px;
height: 680px;
/*max-width:300px;
min-width:250px;*/
padding:10px 50px;
border:2px solid gray;
border-radius:10px;
font-family:raleway;
background-color:#fff;
}
#error-message {
/*margin-top:30px;*/
font-size: 18px !important;
}
#popup-h2 {
background-color:#394650;
padding:20px 35px;
margin:-10px -50px;
text-align:center;
border-radius:10px 10px 0 0;
color: #fff;
}
hr {
margin:10px -50px;
border:0;
border-top:1px solid #ccc;
}
input[type=text] {
width:82%;
padding:10px;
margin-top:30px;
border:1px solid #ccc;
padding-left:40px;
font-size:16px;
font-family: raleway;
}
#name {
background-repeat:no-repeat;
background-position:5px 7px;
}
#email {
background-repeat:no-repeat;
background-position:5px 7px;
}
textarea {
background-repeat:no-repeat;
background-position:5px 7px;
width:82%;
height:95px;
padding:10px;
resize:none;
margin-top:30px;
border:1px solid #ccc;
padding-left:40px;
font-size:16px;
font-family:raleway;
margin-bottom:30px;
}
#submit, #close {
text-decoration:none;
width:100%;
text-align:center;
display:block;
background-color:#394650;
color:#fff;
border:1px solid #fff;
padding:10px 0;
font-size:20px;
cursor:pointer;
border-radius:5px;
}
span {
color:red;
font-weight:700;
}
button {
width:10%;
height:45px;
border-radius:3px;
background-color:#cd853f;
color:#fff;
font-family:'IM Fell DW Pica', serif;
font-size:18px;
cursor:pointer;
}
your form's submit request basically reloads the page therefor firing up the window.onload function again

Explore generic value like WebKit console

I am developing a customed tool to test a javascript library.
I'm using Chrome.
I need to explore a generic object, programmaticaly, like WebKit console, when I write "window" and press enter.
How can I implement that inspector?
Or, how can I invoce that object inspector and insert generated HtmlElement to DOM?
In waiting I develop the Explore method.
jQuery required.
This is the JavaScript code:
window.Debugger = {};
window.Debugger.Explore = function (value) {
var fReturn = jQuery("<div class=\"DbgExp\" />");
if (value === null) {
fReturn.addClass("aNull").text("null");
} else {
switch (typeof value) {
case "undefined":
fReturn.addClass("aNull").text("undefined");
break;
case "string":
fReturn.addClass("aStr").text("\"" + value + "\"");
break;
case "number":
fReturn.addClass("aVal").text(value);
break;
case "boolean":
fReturn.addClass("aVal").text(value ? "true" : "false");
break;
case "function":
case "object":
var str1 = "" + value;
if (str1.length > 40) str1 = str1.substr(0, 37) + "...";
var objName = jQuery("<div class=\"name\" />").text(str1);
fReturn.addClass("aObj").append(objName);
objName.click(function (ev, data) {
if (fReturn.hasClass("aOn")) return fReturn.removeClass("aOn");
fReturn.addClass("aOn");
if (fReturn.data("isFill")) return;
var ul = jQuery("<ul />").appendTo(fReturn);
var num = 0;
for (var k in value) {
jQuery("<li />")
.appendTo(ul)
.append(
jQuery("<div class=\"lbl\" />").text(k)
, Debugger.Explore(value[k])
);
num++;
}
if (num == 0) {
jQuery("<li><div class=\"lbl\">- no properties -</div></li>").appendTo(ul);
}
fReturn.data("isFill", true);
});
break;
}
}
return fReturn;
};
And this is the CSS:
.DbgExp { display:inline-block; background-color:white; color:black; font-family:monospace; font-size:10pt; }
.DbgExp.aNull { background-color:white; font-size:10pt; color:#a9a9a9; }
.DbgExp.aStr { background-color:white; font-size:10pt; color:#a62222; }
.DbgExp.aVal { background-color:white; font-size:10pt; }
.DbgExp.aObj { background-color:white; font-size:10pt; border:dotted 1px cornflowerblue; margin-left:20px; }
.DbgExp.aObj:before { display:inline-block; content:"+"; background-color:#d8eaff; border:solid 1px #0966b4; width:16px; line-height:16px; font-family:monospace; font-size:14px; font-weight:bold; text-align:center; }
.DbgExp.aObj .name { display:inline; font-family:monospace; min-width:40px; margin-left:5px; color:#0966b4; background-color:#d8eaff; border:solid 1px #0966b4; font-size:9pt; font-family:helvetica; padding:1px 4px; cursor:pointer; }
.DbgExp.aObj.aOn:before { content:"-"; }
.DbgExp.aObj ul { display:none; }
.DbgExp.aObj.aOn > ul { display:block; }
.DbgExp.aObj ul li { }
.DbgExp.aObj ul li .lbl { display:inline-block; font-family:helvetica; min-width:80px; font-size:10pt; color:#777; vertical-align:top; }
.DbgExp.aObj ul li .DbgExp { margin-left:10px; }
A html fragment to show how to use:
...
<div id="DebugOutput">
</div>
<script type="text/javascript">
jQuery(document)
.ready(function () {
jQuery("#DebugOutput")
.append(
Debugger.Explore(new Date())
, Debugger.Explore(window)
);
});
</script>

javascript not setting innerHTML

I'm working on a website for a client and I am using ajax to get the contents of a file, html specifically, and then I am trying to insert that html into a div so that i can display the content. i know that i am getting the contents of the file because i have alerts set to display the request's readyState, status, and responseText, and it is showing the contents of the file in the alert. however when i attmept to insert it into the div using this line: document.getElementsByClassName('content').innerHTML = response; nothing happens. can anyone help me figure this out?
CODE:
JAVASCRIPT:
<script language="javascript" type="text/javascript">
var request = new ajaxRequest();
var fileLoc;
var response;
function getData(fileName){
fileLoc = encodeURI("assets/"+fileName+".html")
alert(fileLoc);
request.onreadystatechange = processData;
request.open("GET",fileLoc, false);
request.send();
alert(request.readyState);
alert(response);
alert(request.status);
document.getElementsByClassName('content').innerHTML = response;
}
function processData(){
response = request.responseText;
/*if (request.readyState==4){
if (request.status==200){
try{
document.getElementsByClassName('content').innerHTML = response;
} catch(e){
alert("Error: " +e.description);
}
}
else{
alert("An error has occured making the request");
}
}*/
}
function home() {
getData("home");
}
function about() {
getData('about');
}
function proof() {
getData('contact');
}
function contact() {
getData('proof');
}
function ajaxRequest(){
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]
if (window.XMLHttpRequest)
return new XMLHttpRequest();
else if (window.ActiveXObject){
for (var i=0; i<activexmodes.length; i++){
try{
return new ActiveXObject(activexmodes[i]);
}
catch(e){
alert(e.description);
}
}
}
else
return false
}
HTML:
<body>
<div class="container">
<div class="logo"> <span id="link-home" class="noglow" onclick="javascript: home();" onmouseover="this.className='glow'" onmouseout="this.className='noglow'">Home</span><!-- end link-home -->
<span id="link-about"class="noglow" onclick="javascript: about();" onmouseover="this.className='glow'" onmouseout="this.className='noglow'">About</span><!-- end link-about -->
<span id="link-proof" class="noglow" onclick="javascript: proof();" onmouseover="this.className='glow'" onmouseout="this.className='noglow'">Proof of Concept</span><!-- end link-proof -->
<span id="link-contact" class="noglow" onclick="javascript: contact();" onmouseover="this.className='glow'" onmouseout="this.className='noglow'">Contact</span><!-- end link-contact -->
<div id="home-flower" onclick="javascript: home();" onmouseover="javascript: document.getElementById('link-home').className='glow'" onmouseout="javascript: document.getElementById('link-home').className='noglow'"></div><!-- end home-flower -->
<div id="about-flower" onclick="javascript: about();" onmouseover="javascript: document.getElementById('link-about').className='glow'" onmouseout="javascript: document.getElementById('link-about').className='noglow'"></div><!-- end about-flower -->
<div id="proof-flower" onclick="javascript: proof();" onmouseover="javascript: document.getElementById('link-proof').className='glow'" onmouseout="javascript: document.getElementById('link-proof').className='noglow'"></div><!-- end proof-flower -->
<div id="contact-flower" onclick="javascript: contact();" onmouseover="javascript: document.getElementById('link-contact').className='glow'" onmouseout="javascript: document.getElementById('link-contact').className='noglow'"></div><!-- end other-flower -->
</div><!-- end logo-->
<div class="content"></div><!-- end content -->
</div><!-- end container -->
<div class="footer"></div><!-- end footer -->
CSS:
#charset "UTF-8";
/* CSS Document */
* {
margin:auto;
}
html, body {
height: 100%;
}
.container {
position:relative;
min-height: 100%;
width:800px;
}
.logo{
position:relative;
width:100%;
height:210px;
top:0px;
left:0px;
background:url(images/logo.png);
}
.content {
position:relative;
top:0px;
left:0px;
padding-top:20px;
padding-bottom: 75px !important;
}
.footer {
position:relative;
height: 75px;
margin-top:-75px;
background-color:#06F;
bottom:0px;
left:0px;
}
.large{
font-size:36px;
}
.fltright {
position:relative;
float:right;
top:0px;
left:0px;
width:auto;
height:auto;
}
.fltleft {
position:relative;
float:left;
top:0px;
left:0px;
width:auto;
height:auto;
}
span.glow {
text-shadow: 0px 0px 10px #87CFBF, 0px 0px 10px #87CFBF, 0px 0px 10px #87CFBF;
color:#999;
text-align:center;
}
span.noglow {
color:#999;
text-align:center;
}
#home{
position:absolute;
width:100%;
height:100%;
top:0px;
left:0px;
visibility:visible;
line-height:20px;
}
#about{
position:absolute;
width:100%;
height:100%;
top:0px;
left:0px;
visibility:visible;
}
#proof{
position:absolute;
width:100%;
height:100%;
top:0px;
left:0px;
visibility:visible;
}
#contact{
position:absolute;
width:100%;
height:100%;
top:0px;
left:0px;
visibility:visible;
}
#link-home{
position:absolute;
width:75px;
height:30px;
top:110px;
left:419px;
}
#link-about{
position:absolute;
width:75px;
height:30px;
top:110px;
left:515px;
}
#link-proof{
position:absolute;
width:75px;
height:30px;
top:100px;
left:609px;
}
#link-contact{
position:absolute;
width:75px;
height:30px;
top:110px;
left:708px;
}
#home-flower{
position:absolute;
width:30px;
height:30px;
top:131px;
left:442px;
background:url(images/home-flower.png);
}
#about-flower{
position:absolute;
width:30px;
height:30px;
top:135px;
left:540px;
background:url(images/about-flower.png);
}
#proof-flower{
position:absolute;
width:30px;
height:30px;
top:131px;
left:635px;
background:url(images/proof-flower.png);
}
#contact-flower{
position:absolute;
width:30px;
height:30px;
top:135px;
left:733px;
background:url(images/contact-flower.png);
}
document.getElementByClassName is returning an array. You cannot set the innerHtml of an array you need to loop through the array and set each individual elements inner html;
Working example: http://jsfiddle.net/CYZUL/
function processData(){
response = request.responseText;
/*if (request.readyState==4){
if (request.status==200){
try{
var elements = document.getElementsByClassName('content');
for(var x=0; x < elements.length; x++)
{
elements[x].innerHTML = response;
}
} catch(e){
alert("Error: " +e.description);
}
}
else{
alert("An error has occured making the request");
}
}*/
}
function getData(fileName){
fileLoc = encodeURI("assets/"+fileName+".html")
alert(fileLoc);
request.onreadystatechange = processData;
request.open("GET",fileLoc, false);
request.send();
alert(request.readyState);
alert(response);
alert(request.status);
var elements = document.getElementsByClassName('content');
for(var x=0; x < elements.length; x++)
{
elements[x].innerHTML = response;
}
}
Why not using the jQuery's $.load(); function and save your self a lot of pain and time

Categories

Resources