JS code not running - php

I have downloaded a note taking app (PHP/css+jquery) and I wanted to hide the div that contains the note pad. I don't know why, but what I write in the js file doesn't affect the site.
This is the js file. Everything works fine, but when I wrote the second line it didn't hide the div at all.
$(function(){
$('#pad').hide();
var note = $('#note');
var saveTimer,
lineHeight = parseInt(note.css('line-height')),
minHeight = parseInt(note.css('min-height')),
lastHeight = minHeight,
newHeight = 0,
newLines = 0;
var countLinesRegex = new RegExp('/n', 'g');
note.on('input', function(e){
clearTimeout(saveTimer);
saveTimer = setTimeout(ajaxSaveNote, 2000);
newLines = note.val().match(countLinesRegex);
if(!newLines) {
newLines = [];
}
newHeight = Math.max((newLines.length + 1)*lineHeight, minHeight);
if(newHeight != lastHeight){
note.height(newHeight);
lastHeight = newHeight;
}
}).trigger('input');
function ajaxSaveNote(){
$.post('index.php', { 'note' : note.val() });
}
});
Here is the PHP:
<?php
$note_name = 'note.txt';
$uniqueNotePerIP = false;
if($uniqueNotePerIP){
// Use the user's IP as the name of the note.
// This is useful when you have many people
// using the app simultaneously.
if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
$note_name = 'notes/'.md5($_SERVER['HTTP_X_FORWARDED_FOR']).'.txt';
}
else{
$note_name = 'notes/'.md5($_SERVER['REMOTE_ADDR']).'.txt';
}
}
if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
// This is an AJAX request
if(isset($_POST['note'])){
// Write the file to disk
file_put_contents($note_name, $_POST['note']);
echo '{"saved":1}';
}
exit;
}
$note_content = '
Write your note here.
It will be saved with AJAX.';
if( file_exists($note_name) ){
$note_content = htmlspecialchars( file_get_contents($note_name) );
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Devoirs Communs</title>
<!-- Our stylesheet -->
<link rel="stylesheet" href="assets/css/styles.css" />
<!-- A custom google handwriting font -->
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Courgette" />
<script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<input type="text">
<input type="button">
<div id="pad">
<h2>Note</h2>
<textarea id="note"><?php echo $note_content ?></textarea>
</div>
<footer>
</footer>
<!-- JavaScript includes. -->
<script src="assets/js/script.js"></script>
</body>
</html>

Your REGEXP is wrong.
You need to change this line:
var countLinesRegex = new RegExp('\\n', 'g');
But this is not the only problem. Follow it:
1 - You start hidding the #pad element, and I couldn't see in your code where do you show it again:
$('#pad').hide();
2 - You can't get line height this way. It will return undefined if there's no line-height attribute. Same for min-height:
parseInt(note.css('line-height'))
your should use some plugin to get this behavior the way you want.
3 - And suppose item 2 returned the line-height rightly, it would return something like "10px", or worst, "1.2em". And when you tried to do some math with it, you will get an error or maybe strip unit measures from it.

Related

How to use FLOT chart examples on web server?

I'm having a problem with my web server on raspberry pi. I have these two files( among others) : view_action.php and graph.html.
One of the function of the firs file is to to redirect the user to the file graph.html.
The graph.html is a copy of the realtime example of Flot chart. The files that i have to include on the code: jquery.js, jquery.flot.js and excanvas.min.js are on the same folder as the files above. So, the only thing changed on the graph.html is the path to these 3 files.
Here the graph.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Examples: Real-time updates</title>
<link href="../examples.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="jquery.js"></script>
<script language="javascript" type="text/javascript" src="jquery.flot.js"></script>
<script type="text/javascript">
$(function() {
// We use an inline data source in the example, usually data would
// be fetched from a server
var data = [],
totalPoints = 300;
function getRandomData() {
if (data.length > 0)
data = data.slice(1);
// Do a random walk
while (data.length < totalPoints) {
var prev = data.length > 0 ? data[data.length - 1] : 50,
y = prev + Math.random() * 10 - 5;
if (y < 0) {
y = 0;
} else if (y > 100) {
y = 100;
}
data.push(y);
}
// Zip the generated y values with the x values
var res = [];
for (var i = 0; i < data.length; ++i) {
res.push([i, data[i]])
}
return res;
}
// Set up the control widget
var updateInterval = 30;
$("#updateInterval").val(updateInterval).change(function () {
var v = $(this).val();
if (v && !isNaN(+v)) {
updateInterval = +v;
if (updateInterval < 1) {
updateInterval = 1;
} else if (updateInterval > 2000) {
updateInterval = 2000;
}
$(this).val("" + updateInterval);
}
});
var plot = $.plot("#placeholder", [ getRandomData() ], {
series: {
shadowSize: 0 // Drawing is faster without shadows
},
yaxis: {
min: 0,
max: 100
},
xaxis: {
show: false
}
});
function update() {
plot.setData([getRandomData()]);
// Since the axes don't change, we don't need to call plot.setupGrid()
plot.draw();
setTimeout(update, updateInterval);
}
update();
// Add the Flot version string to the footer
$("#footer").prepend("Flot " + $.plot.version + " – ");
});
</script>
</head>
<body>
<div id="header">
<h2>Real-time updates</h2>
</div>
<div id="content">
<div class="demo-container">
<div id="placeholder" class="demo-placeholder"></div>
</div>
<p>You can update a chart periodically to get a real-time effect by using a timer to insert the new data in the plot and redraw it.</p>
<p>Time between updates: <input id="updateInterval" type="text" value="" style="text-align: right; width:5em"> milliseconds</p>
</div>
<div id="footer">
Copyright © 2007 - 2014 IOLA and Ole Laursen
</div>
When the view_action.php redirect to graph.html it only appear the title and the info of the body. No graph. I think my webserver it isnt running javascript codes. What is the problem?
Thanks,
Ricardo
You need to specify a width and height for the placeholder div element (see the readme). In the original example this is done in the example.css. Check if the path to the CSS file is correct in your code (you have href="../examples.css").
Changing
<div id="placeholder" class="demo-placeholder"></div>
to
<div id="placeholder" class="demo-placeholder" style="width: 800px; height: 450px;"></div>
or similar should fix that issue if you don't want to use the CSS file.

How can I print result in consecutive textarea?

I am again here for same question again.
Now my old problem is solved. I have two files index.html and code.js
1) index.html
<html>
<head>
<title> perl </title>
<link rel="stylesheet" href="http://code.guru99.com/css/1140.css" type="text/css" media="screen" />
<link rel="stylesheet" href="http://code.guru99.com/css/styles.css" type="text/css" media="screen" />
<script src="http://code.guru99.com/php/lib/codemirror.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">></script>
<link rel="stylesheet" href="http://code.guru99.com/Sanjay/lib/codemirror.css" type="text/css" media="screen" />
<script src="code.js"></script>
<script type="text/javascript" src="http://code.guru99.com/perl/perl.js"></script>
<style>
.CodeMirror {
border: 1px solid #eee;
height: auto;
width : 600px;
}
.CodeMirror-scroll {
height: auto;
overflow-y: hidden;
overflow-x: auto;
}
</style>
</head>
<body>
Integer : whole numbers e.g. -3, 0, 69. The maximum value of an integer is platform-dependent. On a 32 bit machine, its usually around 2 billion. 64 bit machines usually have larger values. The constant PHP_INT_MAX is used to determine the maximum value.
<pre class="codeguru">say 'hi';</pre>
Let us now look at how PHP determines the data type depending on the attributes of the supplied data.
<pre class="codeguru">say 'hello';</pre>
Floating point numbers
<pre class="codeguru">say 'you r amazing';</pre>
Character strings
<pre class="codeguru">say 'i am fine';</pre>
</div>
<form class="hidden code-box" method="GET" name="sample">
<div dir="ltr"><textarea class="php" name="codeguru"></textarea></div>
<input type="button" value="Run" />
</br></br>
Output:</br></br>
<textarea id="print-result" disabled="true" cols="77"></textarea></br>
</form></div>
</body>
</html>
and code.js contain following code
$(document).ready(function()
{
$('pre.codeguru').each(function()
{
var pre = this;
var form = $('form[name=sample]').clone();
$(form).removeAttr('name');
$(form).removeClass('hidden');
$($(form).find('textarea')[0]).val($(pre).text());
var id = $(pre).attr('id');
$(form).find('div textarea[name=code]').first().attr('id', id);
$(pre).replaceWith(form);
});
var n = 0;
$('input[type=button]').each(function () {
$(this).click(function (x) {
return function () {
execute(x);
};
}(n++))
}
);
window.editors = [];
$('textarea[name=codeguru]').each(function()
{
window.editor = CodeMirror.fromTextArea(this,
{
lineNumbers: true,
matchBrackets: true,
mode: "application/x-httpd-perl",
tabMode: "shift"
});
editors.push(editor);
});
});
function execute(idx) {
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value+=p5str(List__[i])
}
return true;
};
p5pkg["main"]["v_^O"] = "browser";
p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";
var source = editors[idx].getValue();
alert(source);
var pos = 0;
var ast;
var match;
document.getElementById('print-result').value = "";
try {
var start = new Date().getTime();
var js_source = p5pkg["Perlito5"].compile_p5_to_js([source]);
var end = new Date().getTime();
var time = end - start;
// run
start = new Date().getTime();
eval(js_source);
end = new Date().getTime();
time = end - start;
}
catch(err) {
//document.getElementById('log-result').value += "Error:\n";
}
}
When I run this code its works fine give me output also. But my problem is that the output prints in one textarea only. I want to print the output in consecutive textarea.
This code in code.js prints the output.
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value += p5str(List__[i])
}
}
So what I have to do for print my output in consecutive textarea.Please please help me.
using same id for different elements in a page can create problems..
make the text area like this..
<textarea id="print-result" class='print-result' disabled="true" cols="77></textarea>
Modified code in code.js that prints the output is
p5pkg.CORE.print = function(List__) {
var i,concat='';
for (i = 0; i < List__.length; i++) {
concat=$(".print-result").eq(idx).val();
$(".print-result").eq(idx).val(concat+p5str(List__[i]));
}
return true;
}
Add name attribute to your textarea like
<textarea id="print-result" disabled="true" name="code" cols="77"></textarea>
in place of
<textarea id="print-result" disabled="true" cols="77"></textarea>
Updated
In your code I can't see a textarea having name="code", and you are using it.
Is it codeguru?

PHP "Error: parsererror" trying to use search API with result list

Hello stackoverflow,
I am trying to make a search function to search events on a Search API.
The API can be viewed here: http://build.uitdatabank.be/api/events/search?key=AEBA59E1-F80E-4EE2-AE7E-CEDD6A589CA9&q=opera this is the output XML if you search on the word "opera".
I'm still quite a noob at PHP so i"m having a hard time. I used this tutorial/example as help:http://designm.ag/tutorials/deviantart-api-instant-search-app-using-ajax-php/
So I built my code and I ended up getting the error "Error: parsererror" every time I type in a keyword in the text area. Can anyone help me fix this please?
Here is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>Culture Reminder</title>
<!-- Stylesheets -->
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/style.css">
<!-- Scripts -->
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<!-- <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script> -->
<script type="text/javascript" src="uitdatabase.js"></script>
<!-- HTML5 Shiv -->
    <!--[if lt IE 9]>
            <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
</head>
<body>
<header>
<h1>Search events</h1>
</header><!-- /header -->
<div id="container">
<div id="searchform">
<h2>Search for culture</h2>
<input id="s" name="s" placeholder="Type in keyword(s)" size="30" type="text" />
</div><!-- /searchform -->
<center id="loader"><img src="images/loader.gif" alt="loading..."></center>
<div id="content">
</div><!-- /content -->
</div><!-- /container -->
<div id="footer">
<div id="nav">
<img src="images/searchbutton.gif" />
<img src="images/mylistbutton.gif" />
<img src="images/settingsbutton.gif" />
</div>
</div><!-- /footer -->
</body>
</html>
Here is the Javascript file:
$(document).ready(function(){
var s = $("#s");
var wrap = $("#content");
var delay = 1500;
var keycode;
var timer;
$(s).keydown(function(e){
// clear old page content and reset timer
$(wrap).empty();
clearTimeout(timer);
});
$(s).keyup(function(){
$("#loader").css("display", "block");
timer = setTimeout(startSearch, delay); // end timeout() function
}); // end keyup() event function
function startSearch() {
$.ajax({
type: 'POST',
url: 'ajax.php',
data: "q="+$(s).val(),
success: function(data){
// hide the loader and blur focus away from input
$("#loader").css("display", "none");
$(s).blur();
var code = "<span class=\"results\">Total Results: "+data['total']+"</span>";
$.each(data, function(i, item) {
if(typeof(data[i].title) !== 'undefined') { // check if data is undefined before setting more variables
code = code + '<div class="listing clearfix"><header><h3>'+data[i].title+'</h3><span class="userdata"><span class="date">'+data[i].calendarsummary+'</span>'+'<span class="location">' + data[i].location+'</span>'+'<span class="description">'+ data[i].shortdescription+'</span></span></header></div>';
code = code + '<img src="'+data[i].thumbnail+'" class="thumbnail">';
}
});
$(wrap).html(code);
},
error: function(xhr, type, exception) {
$("#loader").css("display", "none");
$(wrap).html("Error: " + type);
}
}); // end ajax call
}
}); // end ready() function
And here is my ajax.php code:
<?php
header('Content-Type: application/json');
$query = urlencode(stripslashes($_POST['q']));
$keywords = $query;
$xmlurl = "http://http://build.uitdatabank.be/api/events/search?key=AEBA59E1-F80E-4EE2-AE7E-CEDD6A589CA9&q=".$keywords;
$xmlrss = file_get_contents($xmlurl);
$xmlrss = preg_replace('#&(?=[a-z_0-9]+=)#', '&', $xmlrss);
$object = simplexml_load_string($xmlrss);
// setup return array
$return = array();
$i = 0;
// get total number of results, max 60
$total = count($object->list->item);
$return["total"] = $total;
foreach($object->list->item as $item) {
$title = (string) $item->title;
$date = (string) $item->calendarsummary; //url
$loc = (string) $item->location; // authorname
$desc = (string) $item->shortdescription;//authorpic
$thumburl = (string) $item->thumbnail;//authorpic
// configure array data for each item
$return[$i]["title"] = $title;
$return[$i]["calendarsummary"] = $date;
$return[$i]["location"] = $loc;
$return[$i]["shortdescription"] = $desc;
$return[$i]["thumbnail"] = $thumburl;
$i++;
}
$json = json_encode($return);
die($json);
?>
If anyone could help me I would be so grateful. This is a project for school and I'm still learning basic PHP.
Try this code
<?php
header('Content-Type: application/json');
if(isset($_POST['q']))
{
$query = urlencode(stripslashes($_POST['q']));
$keywords = $query;
$xmlurl = "http://build.uitdatabank.be/api/events/search?key=AEBA59E1-F80E-4EE2-AE7E-CEDD6A589CA9&q=".$keywords;
$xmlrss = file_get_contents($xmlurl);
$xmlrss = preg_replace('#&(?=[a-z_0-9]+=)#', '&', $xmlrss);
$object = simplexml_load_string($xmlrss);
// setup return array
$return = array();
$i = 0;
if(isset($object->list->item))
{
// get total number of results, max 60
$total = count($object->list->item);
$return["total"] = $total;
if($total>0)
{
foreach($object->list->item as $item) {
$title = (string) $item->title;
$date = (string) $item->calendarsummary; //url
$loc = (string) $item->location; // authorname
$desc = (string) $item->shortdescription;//authorpic
$thumburl = (string) $item->thumbnail;//authorpic
// configure array data for each item
$return[$i]["title"] = $title;
$return[$i]["calendarsummary"] = $date;
$return[$i]["location"] = $loc;
$return[$i]["shortdescription"] = $desc;
$return[$i]["thumbnail"] = $thumburl;
$i++;
}
$json = json_encode($return);
die($json);
}else{
//count is empty
}
}else{
//object is not ready
}
}else{
//no post data found
}

jquery dynamic data not getting displayed

index.html
<html>
<head>
<script type="text/javascript" src = "jquery-1.10.1.js"></script>
<script type="text/javascript" language = "javascript">
function swapContent(cv)
{
$_("#myDiv").html("Put animated .gif here").show();
var url= "myphpscript.php";
$_post(url,{contentVar:cv},function(data){
$_("#myDiv").html(data).show();
});
}
</script>
</head>
<body>
Content1 •
Content2 •
Content3 •
<div id = "myDiv"> My Default Content 1</div>
</body>
</html>
myphpscript.php
<html>
<body>
<?php
$_contentVar = $_POST['contentVar'];
if($_contentVar == 'Con1')
{
echo ' My Defaut Content';
}
else if($contentVar == 'Con2')
{
echo ' My Defaut Content 2';
}
else if($contentVar == 'Con3')
{
echo ' My Defaut Content 3';
}
?>
</body>
</html>
I am trying to display some dynamic content when the onmousedown event is done. I haven't done the animation yet, but just I wanted to get the required divs to be changed on choosing the different links but some how it doesn't seem to work.The jQuery file has been correctly loaded.
COndition wrong
$_contentVar = $_POST['contentVar'];
if( $_contentVar == 'Con1') //here you are using $contentVa not $_contentVar
I'm not sure why you have used _ in $_("#myDiv").. I think your javascript code should be
function swapContent(cv)
{
$("#myDiv").html("Put animated .gif here").show();
var url= "myphpscript.php";
$.post(url,{contentVar:cv},function(data){
$("#myDiv").html(data).show();
});
}
and also another problem I see is with how you call the function it should be javascript:swapContent('Con1') not javascript.swapContent('Con1'). You have put '.' instead of ':'
so the links should be
Content1 •
Content2 •
Content3 •
You should also change the variable name in PHP script, which I hope you already knew

YUI Text Editor is not working in my Mozilla

I am experiencing this problem for few hours now and really not sure how to solve this. However its work fine in IE but it is not working in mozilla.
Here is my code:
<!-- Skin CSS file -->
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.7.0/build/assets/skins/sam/skin.css">
<!-- Utility Dependencies -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/element/element-min.js"></script>
<!-- Needed for Menus, Buttons and Overlays used in the Toolbar -->
<script src="http://yui.yahooapis.com/2.7.0/build/container/container_core-min.js"></script>
<script src="http://yui.yahooapis.com/2.7.0/build/menu/menu-min.js"></script>
<script src="http://yui.yahooapis.com/2.7.0/build/button/button-min.js"></script>
<!-- Source file for Rich Text Editor-->
<script src="http://yui.yahooapis.com/2.7.0/build/editor/editor-min.js"></script>
<script>
var myEditor = new YAHOO.widget.Editor('msgpost', {
height: '100px',
width: '522px',
dompath: true, //Turns on the bar at the bottom
animate: true //Animates the opening, closing and moving of Editor windows
});
myEditor.render();
//Inside an event handler after the Editor is rendered
YAHOO.util.Event.on('save', 'click', function() {
//Put the HTML back into the text area
myEditor.saveHTML();
//The var html will now have the contents of the textarea
var html = myEditor.get('msgpost').value;
});
YAHOO.util.Event.on('edit', 'click', function() {
//Put the HTML back into the text area
myEditor.saveHTML();
//The var html will now have the contents of the textarea
var html = myEditor.get('msgpost').value;
});
</script>
<form id="form2" name="form2" method="post" action="processgreeting.php">
<div class="span-22 gtype" >
<div class="span-5"><label>Message:</label></div>
<div class="span-17 last"><textarea name="msgpost" id="msgpost" cols="50" rows="40"> </textarea> <br>
</div>
<input type="submit" name="save" value="Post Greeting" id="postgreeting"/>
</form>
processgreeting.php
if(isset($_POST['save']))
{
$body = trim($_POST['msgpost']);
$valid = 1;
$publish_date = strtotime($publish);
if ($publish >= $today)
{
$valid = 0;
$insert_greeting = "INSERT INTO greeting (type,decs,name,message,date,user,publish) VALUES ('$type','$desc','$name','$body','$today',$user,'$publish')";
$register_greeting = mysql_query($insert_greeting)or die(mysql_error());
$lastnum = mysql_insert_id();
$_SESSION["greetingno"] = $lastnum;
if($valid == 0)
{
echo '<strong>Greeting Type: </strong>'.$type.'<br><strong>Description: </strong>'.$desc.'<br><strong>Name: </strong>'.$name.'<br><strong>Message: </strong>'.$body.'<strong><br>Publish Date: </strong>'.$publish;
}
//echo $valid;
}
else{ //echo "<span style='color:#FF0000'>Publish date is invalid</span>" ;
echo $valid;
} //}
}
Please can anyone help me what iam doing wrong..
Thanks in advance.
i've just tried on my mac with firefox and everything seems to work. What's exactly your problem ?

Categories