add google ads in the middle of content page - javascript

I would like to add google ads after the first paragraph on every page on my wiki.
I have a code that checks if a tag is there, if it isn't then the tag is added and this tag calls the code for the google ads.
However, the rest of the text on the page is not showing after the ads.
This is my code: (based on the AdsWhereever extension)
$wgHooks['ParserFirstCallInit'][] = 'AdsSetup'; $wgHooks['EditPage::showEditForm:initial'][] = 'CheckHasTag';
function AdsSetup( &$parser ) {
$parser->setHook( 'ads', 'AdsRender' );
return true;}
function AdsRender($input, $args ) {
$input =""; $url = array(); global $wgOut;
$ad['goo1'] = '<html><br><script type="text/javascript">
google_ad_client = "xxx";
google_ad_width = 728;
google_ad_height = 90;
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br></html>';
$media = $args['media'];
return $ad[$media];
}
// check if content has <goo1> tag
function CheckHasTag($editPage){global $wgOut;
$wgOut->addScript('<script type="text/javascript">
var editTextboxText = document.getElementById("wpTextbox1").value;
var searchFor = "goo1";
var searchResult = editTextboxText.search(searchFor);
if(searchResult == -1){
var a = editTextboxText;
var b = "\n<ads media=goo1>\n";
var findP = "\n";
var p = editTextboxText.search(findP);
var position = p;
document.getElementById("wpTextbox1").value = a.substr(0, position) + b + a.substr(position);
}</script>');
return true;
}

Your code relies on $wgRawHtml being set to true in LocalSettings.php. (This, by the way, is a huge security risk, and should never be used in public wikis.) If you did not set
$wgRawHtml to true, the last output of your tag function will be </html>, that will cause the browser to stop parsing the page, and produce no further output.
Something like this would probably work, without having to use the html-tag:
function AdsRender( $input, $args, $parser, $frame ) {
$output = '<div id="googlead"><script type="text/javascript">
google_ad_client = "xxx";
google_ad_width = 728;
google_ad_height = 90;
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>';
return array( $output, "markerType" => 'nowiki' );
}
Btw, you have a lot of garbage in you example, it's easier to help you if you remove code that is not being used (like $url = array(); global $wgOut; etc)

It was missing a / in the tag which was why the rest of the text wasn't being displayed!
var b = "\n\n"

Related

how to make javascript in to PHP

I have the following javascript code which I need to be executed in a PHP file.
I need to know how should I enter the php tags to this javascript code.
I am new to web programming.
The javascript used here is to export content in the html page to a .csv file.
<!-- Scripts ----------------------------------------------------------- -->
<script type='text/javascript' src='https://code.jquery.com/jquery-
1.11.0.min.js'></script>
<!-- If you want to use jquery 2+: https://code.jquery.com/jquery-2.1.0.min.js -->
<script type='text/javascript'>
$(document).ready(function () {
console.log("HELLO")
function exportTableToCSV($table, filename) {
var $headers = $table.find('tr:has(th)')
,$rows = $table.find('tr:has(td)')
// Temporary delimiter characters unlikely to be typed by
keyboard
// This is to avoid accidentally splitting the actual
contents
,tmpColDelim = String.fromCharCode(11) // vertical tab
character
,tmpRowDelim = String.fromCharCode(0) // null character
// actual delimiter characters for CSV format
,colDelim = '","'
,rowDelim = '"\r\n"';
// Grab text from table into CSV formatted string
var csv = '"';
csv += formatRows($headers.map(grabRow));
csv += rowDelim;
csv += formatRows($rows.map(grabRow)) + '"';
// Data URI
var csvData = 'data:application/csv;charset=utf-8,' +
encodeURIComponent(csv);
// For IE (tested 10+)
if (window.navigator.msSaveOrOpenBlob) {
var blob = new Blob([decodeURIComponent(encodeURI(csv))], {
type: "text/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, filename);
} else {
$(this)
.attr({
'download': filename
,'href': csvData
//,'target' : '_blank' //if you want it to open in a
new window
});
}
//------------------------------------------------------------
// Helper Functions
//------------------------------------------------------------
// Format the output so it has the appropriate delimiters
function formatRows(rows){
return rows.get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim);
}
// Grab and format a row from the table
function grabRow(i,row){
var $row = $(row);
//for some reason $cols = $row.find('td') || $row.find('th')
won't work...
var $cols = $row.find('td');
if(!$cols.length) $cols = $row.find('th');
return $cols.map(grabCol)
.get().join(tmpColDelim);
}
// Grab and format a column from the table
function grabCol(j,col){
var $col = $(col),
$text = $col.text();
return $text.replace('"', '""'); // escape double quotes
}
}
// This must be a hyperlink
$("#export").click(function (event) {
// var outputFile = 'export'
var outputFile = window.prompt("What do you want to name your
output file (Note: This won't have any effect on Safari)") ||
'export';
outputFile = outputFile.replace('.csv','') + '.csv'
// CSV
exportTableToCSV.apply(this, [$('#dvData > table'),
outputFile]);
// IF CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
};
</script>
use this, add ?> before it and <?php after script
<?php
/* your php code */
?>
<script type='text/javascript'>
// your script
</script>
<?php
/* your php code */
?>
Top answer from a previous question
<script type="text/javascript">
var my_var = <?php echo json_encode($my_var); ?>;
</script>
works if you define and use the variable in PHP, and want to pass the variable in the Javascript.
If you are running in a PHP file (which you are) you can also use
function foo()
{
var i = 0 ;
i = <?php echo $my_var; ?>
}

Postpone the ads script execution

With the help of the following php function:
<?php
if (!function_exists('wrapAds')) {
function wrapAds($current_banner_name){
$STRING_EMPTY = "";
$openExprResult = array();
$closeExpreResult = array();
$openExpr = "/(<div[^>]*>)/";
$closeExpr = "/(<\/div>)/";
$banner = tsp_get_banner($current_banner_name);
$result = '<pre data-script-reference>'
.htmlspecialchars($banner)
.'</pre>';
return $result;
}
}
?>
I am rendering the following markup:
<pre data-script-reference="1"><!--- s: middle-box-sidebar -->
<div class="ads middle-box-sidebar"><script type="text/javascript">
var FW_type = "4w";
var FW_code = "18xxxx;95xxx;70xxx;0";
var FW_dimension = "300x250";
var FW_category = "gossip";
</script>
<script src="//optimized-by.4wnetwork.com/simply_loader.js?4wvideo=true" type="text/javascript"></script></div>
<!--- e: middle-box-sidebar --></pre>
Now I am tring to postpone the encoded script execution later with the following script:
<script type="text/javascript">
[].slice.call(document.querySelectorAll('pre[data-script-reference]'))
.forEach(function(item){
var txt = document.createElement("textarea");
txt.innerHTML = item.innerHTML;
var parentNode = item.parentNode;
var p0 = txt.innerText;
// parentNode.removeChild(item);
parentNode.innerHTML += p0;
</script>
seems that decoded script isn't executed at all, what I am doing wrong?
After a trillion of useless code executions, I just noted a curious statement inside a long list of warnings:
"Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.". I googled around this message and I found a nice question.
The only not accepted answer suggest postscribe.js
Asynchronously write javascript, even with document.write.
Remote scripts, especially ads, block the page from doing anything
else while they load. They contribute a large % to load times which
affects your bottom line. Asynchronous ads do not block the page and
can be delivered after core content - Async FTW.
Why is it so hard to deliver ads asynchronously? Because they may
contain calls to document.write, which expects to be handled
synchronously. PostScribe lets you deliver a synchronous ad
asynchronously without modifying the ad code.
So, since I have to manage both ads in the body and in the sidebar, I made a little refactoring, moving the php function in the functions.php:
/**
* redefine and get the legacy ads block from base library by name
* render as encoded plain text inside a *pre* wrapper
*/
function tsp_get_banner($current_banner_name){
$STRING_EMPTY = "";
// https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags
$openExpr = "/(<div[^>]*>)/";
$closeExpr = "/(<\/div>)/";
$openExprResult = $closeExpreResult = array();
$banner = original_tsp_get_banner($current_banner_name);
preg_match($openExpr, $banner, $openExprResult);
$banner = preg_replace($openExpr, $STRING_EMPTY, $banner);
preg_match($closeExpr, $banner, $closeExpreResult);
$banner = preg_replace($closeExpr, $STRING_EMPTY, $banner);
return wrapAdsSnippet($banner, $openExprResult[0], $closeExpreResult[0]);
}
function wrapAdsSnippet($source, $prefix, $postfix){
$result = '<pre data-script-reference style="display:none;">'
.htmlspecialchars($source)
.'</pre>';
if(isset($prefix) && isset($postfix)){
$result = $prefix.$result.$postfix;
}
return $result;
}
then I changed the inclusion of the block:
so that I don't need to change anything.
<?php
echo tsp_get_banner("middle-box-sidebar");
echo renderAds("middle-box-sidebar");
?>
I have just to change the final script to include in the footer.php:
var MyCompanyLab;
(function (MyCompanyLab) {
"use strict";
var Ads;
(function (Ads) {
var Optimization;
(function (Optimization) {
var PostProcessor = (function () {
function PostProcessor() {
}
PostProcessor.postponeAdsExecution = function () {
$("pre[data-script-reference]").each(function (idx, item) {
var parentNode = item.parentNode;
postscribe(parentNode, $('<textarea />').html(item.innerHTML).text(), {
done: function () { },
error: function () { },
releaseAsync: true,
});
parentNode.removeChild(item);
});
};
return PostProcessor;
}());
Optimization.PostProcessor = PostProcessor;
})(Optimization = Ads.Optimization || (Ads.Optimization = {}));
})(Ads = MyCompanyLab.Ads || (MyCompanyLab.Ads = {}));
})(MyCompanyLab|| (MyCompanyLab= {}));
<script type="text/javascript">
...
MyCompanyLab.Ads.Optimization.PostProcessor.postponeAdsExecution();
...
</script>

pass angular scope to jquery

anyone has any case like me ? i have to connect another service to my system. the problem is that service is unsupported on JS front-end (im using angularJS). to show form for service i need to complete jQuery form like this :
<script type="text/javascript">
$(function() {
var data = new Object();
data.req_merchant_code = '1';
data.req_chain_merchant = 'NA';
data.req_payment_channel = '15'; // ‘15’ = credit card
data.req_transaction_id = '<?php echo $invoice ?>';
data.req_currency = '<?php echo $currency ?>';
data.req_amount = '<?php echo $amount ?>';
data.req_words = '<?php echo $words ?>';
data.req_form_type = 'full';
getForm(data);
});
</script>
like you see that PHP variable on there with echo, can anyone help me to pass scope variable to that jQuery. i set that variable like this
$scope.dokuPayment = function(){
topUpFactory.createwordsDoku().then(function(data){
console.log(data.data);
var req = data.data;
$scope.invoice = req.invoice;
$scope.words = req.words;
$scope.currency = req.currency;
$scope.amount = req.amount;
console.log(invoice);
$("#doku-modal").modal('show');
});
}
i try to put that scope to parametes like this
<script type="text/javascript">
console.log("form doku");
$(function() {
var data = new Object();
data.req_merchant_code = '3279';
data.req_chain_merchant = 'NA';
data.req_payment_channel = '15'; // ‘15’ = credit card
data.req_transaction_id = {{invoice}};
data.req_currency = {{currency}};
data.req_amount = {{amount}};
data.req_words = {{words}};
data.req_form_type = 'full';
getForm(data);
});
</script>
but doesn't work.. i try to set upperstroup ("") still doesn't work. anyone can help. . thanks
When using AngularJS, try avoiding using jQuery in that way.
$("#doku-modal").modal('show'); - not a good idea to do that in this framework.
This article may give some guidance: http://www.dwmkerr.com/the-only-angularjs-modal-service-youll-ever-need/
In $scope.dokuPayment you can potentially do the same thing what getForm(data) does as long as it does not manipulate the DOM directly.
As a result, you do not have to pass any data to the view as the entire JS logic should be in your Angular services or controllers.
There is simple hack, not sure if it is good practice or not! You can make use of $window scope.
All you need to do is, make angular variables to global variables using $window.{variable name} and access them from outside using window.{variable name}.
See here:
$scope.dokuPayment = function(){
topUpFactory.createwordsDoku().then(function(data){
console.log(data.data);
var req = data.data;
$window.invoice = req.invoice;
$window.words = req.words;
$window.currency = req.currency;
$window.amount = req.amount;
console.log(invoice);
$("#doku-modal").modal('show');
});
}
Outside AngularJS:
console.log("form doku");
$(function() {
var data = new Object();
data.req_merchant_code = '3279';
data.req_chain_merchant = 'NA';
data.req_payment_channel = '15'; // ‘15’ = credit card
data.req_transaction_id = window.invoice;
data.req_currency = window.currency;
data.req_amount = window.amount;
data.req_words = window.words;
data.req_form_type = 'full';
getForm(data);
});
This worked for me. Hope this helps :)

Set JavaScript file to a variable in PHP

Okay so I'm trying to set a JavaScript document to a variable in PHP?
Essentially I'm setting the WiFi speed I calculate in a Javascript document to a variable,so I can save the variable value in a database with other information as an instance.
The Javascript code is pretty long so I don't know if I should copy the whole code in and set it equal to the variable or if there's a syntax to set it to a variable.
I've seen:
<script type="text/javascript" src="file.js"></script>
Online for calling a Javascript file but not sure how to get that value and store it in a variable.
You could do something like this
$js = file_get_contents( 'http://www.example.com/javacsript.js');
$value = trim( str_replace( array( "document.write('", "');"), '', $js));
echo $value;
Hope this will help you
The JavaScript must be executed in the browser client. The flow would be:
PHP generates HTML (wich includes the JS code)
HTML is sent to the browser
The browser renders the HTML and executes the JS
The browser communicates with the server to tell the result
Depending if the JS is a library or an script the precise steps would differ. But basically inside tags you will have to save the result to a variable and then make an AJAX call (easier with jQuery.ajax() ) to communicate that variable to the server and then the server can do something with it.
I hope that helps puting you on the right track. If you expand the info in your question, I will try to update my answer :)
You have to do this using a POST, possibly to the same PHP script.
<form method='post' id=myform>
<input type=hidden id=js-to-php value=0>
</form>
<script>
jQuery(document).ready(function(){
//calulcate the wifispeed using the long js code
//then save it in the field
$('#js-to-php').val(YOUR_SPEED);
// send the form
$('#myform').submit();
});
</script>
and then in the same script:
if( isset($_POST['js-to-wifi']) && $_POST['js-to-wifi']!='') {
// store your stuff in DB
}
So here is the Java script code:
//Source: http://stackoverflow.com/questions/5529718/how-to-detect-internet-speed-in-javascript
var imageAddr = "http://www.kenrockwell.com/contax/images/g2/examples/31120037-5mb.jpg";
var downloadSize = 4995374; //bytes
window.onload = function() {
var oProgress = document.getElementById("progress");
oProgress.innerHTML = "Loading the image, please wait...";
window.setTimeout(MeasureConnectionSpeed, 1);
};
function MeasureConnectionSpeed() {
var oProgress = document.getElementById("progress");
var startTime, endTime;
var download = new Image();
download.onload = function () {
endTime = (new Date()).getTime();
showResults();
}
download.onerror = function (err, msg) {
oProgress.innerHTML = "Invalid image, or error downloading";
}
startTime = (new Date()).getTime();
var cacheBuster = "?nnn=" + startTime;
download.src = imageAddr + cacheBuster;
function showResults() {
var duration = (endTime - startTime) / 1000;
var bitsLoaded = downloadSize * 8;
var speedBps = (bitsLoaded / duration).toFixed(2);
var speedKbps = (speedBps / 1024).toFixed(2);
var speedMbps = (speedKbps / 1024).toFixed(2);
oProgress.innerHTML = "Your connection speed is: <br />" +
speedBps + " bps<br />" +
speedKbps + " kbps<br />" +
speedMbps + " Mbps<br />";
}
}
I want to get the value that this will return (I will edit the code so I am only getting one value) and then place it inside a php variable. The issue is when I run it on a webpage after using:
$Speed = file_get_contents( 'wiFiCalc.js');
$value = trim( str_replace( array( "document.write('", "');"), '', $Speed));
echo $value;
I just get the code on the html page, as clami219 stated above. I just want to return that value to print it and store it in the database.
Also, Jobst, the way you wrote was kind of hard to follow. I am using a form action in my html code to go to the speed so it can be stored in the database before it returns to the next HTML page so could you explain how your code works?

onkeyup function only firing once

I need the onkeyup to fire more than once, but it seems to be only firing once!
When I enter something into the input box, it searches, but then whenever I backspace and search something else, the div stay's the same..
Here is my code:
<script type="text/javascript">
function suggest1() {
var dam_text = document.getElementById('dam').value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('MicrosoftXMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
}
}
var target = 'dam_search.php?dam_text=' + dam_text;
xmlhttp.open('GET', target, true);
xmlhttp.send();
}
</script>
<input type="text" name="dam" id="dam" onkeyup="suggest1();"><br />
<div id="myDiv"></div>
Here is dam_search.php
<?php
//connect to db stuff here
if (isset($_GET['dam_text'])) {
$dam = $_GET['dam_text'];
getSuggest($text);
}
function getSuggest($text) {
$sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam_text%'";
$query = mysql_query($sqlCommand);
$result_count = mysql_num_rows($query);
while ($row = mysql_fetch_assoc($query)) {
echo $row['name'].'<br />';
}
}
?>
ALSO: I am wondering how I can put the return of the name's it has searched into a dropdown from the input box instead of into the div, so when I click on one of the names, it auto fills the input box.
Thank you!
Still not sure about your issue with the keyup only firing once per page-load. That's very hard to speculate reasonably on without seeing more code. Never-the-less, here's an example I just threw together of how you can present the returned data in a more useful way.
The code requires that you download the AjaxRequest library I mentioned in an earlier comment.
(http://ajaxtoolbox.com/request/)
Here, I demo a few principles.
Arranging the data into a php class
constructing an array of instances of this class
returning this array as JSON
catching the JSON text and turning it back into an object in JS
Processing the data
I've given 2 very simple example - the first simply loads all filenames in the current directory (that holds jsonDir.php) into a select element. Choosing a filename results in it being copied into a text input next to the button.
The second, only retrieves names of png files. It chucks them all into a select element too. This time however, when an item is selected it is used as the src for an image. In each case the filenames are only grabbed if/when the corresponding button is pressed. There's a bit of redundant/otherwise crappy code I could have done better, but after 20 hours awake, I'm ready for bed!
Hope it's useful for you. Any questions, just ask. :)
1. jsonDir.php
<?php
class mFile
{
public $name, $time, $size;
}
if (!isset($_GET['wildcard']))
$wildCard = "*.*";
else
$wildCard = $_GET['wildcard'];
foreach (glob($wildCard) as $curFilename)
{
$curFileObj = new mFile;
$curFileObj->name = $curFilename;
$curFileObj->time = date("d/m/Y - H:i", filectime($curFilename));
$curFileObj->size = filesize($curFilename);
$fileArray[] = $curFileObj;
}
printf("%s", json_encode($fileArray));
?>
2. readDir.html
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='script/ajaxRequestCompressed.js'></script>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function myGetAjaxResponseWithCallback(url, target, callbackFunc)
{
AjaxRequest.get(
{
'url':url,
'onSuccess':function(req){ callbackFunc(req.responseText, target); }
}
);
}
function getResults1()
{
var url = "jsonDir.php";
var target = byId('resultsDiv');
myGetAjaxResponseWithCallback(url, target, jsonDataReceived1);
}
function getResults2()
{
var url = "jsonDir.php?wildcard=*.png";
var target = byId('resultsDiv2');
myGetAjaxResponseWithCallback(url, target, jsonDataReceived2);
}
function jsonDataReceived1(responseText, targetContainer)
{
var resultObject = JSON.parse(responseText);
targetContainer.innerHTML = "";
var mStr = "There were " + resultObject.length + " records returned" + "<br>";
var mSel = newEl("select");
mSel.addEventListener('change', doAutofill, false);
var i, n = resultObject.length;
for (i=0; i<n; i++)
{
var curRecordOption = new Option(resultObject[i].name, i);
mSel.appendChild(curRecordOption);
}
targetContainer.innerHTML = mStr;
targetContainer.appendChild(mSel);
}
function jsonDataReceived2(responseText, targetContainer)
{
var resultObject = JSON.parse(responseText);
targetContainer.innerHTML = "";
var mSel = newEl("select");
mSel.addEventListener('change', showSelectedImg, false);
var i, n = resultObject.length;
for (i=0; i<n; i++)
{
var curRecordOption = new Option(resultObject[i].name, i);
mSel.appendChild(curRecordOption);
}
targetContainer.innerHTML = '';
targetContainer.appendChild(mSel);
}
function doAutofill(e)
{
var curSelIndex = this.value;
var curText = this.options[curSelIndex].label;
byId('autofillMe').value = curText;
}
function showSelectedImg(e)
{
byId('previewImg').src = this.options[this.value].label;
}
</script>
<style>
img
{
border: solid 2px #333;
}
</style>
</head>
<body>
<button onclick='getResults1()'>Get *.* dir listing</button> <input id='autofillMe'/>
<div id='resultsDiv'></div>
<hr>
<button onclick='getResults2()'>Get *.png dir listing</button> <img id='previewImg' width='100' height='100'/>
<div id='resultsDiv2'></div>
</body>
</html>
Found out my problem. The query wasn't correctly being processed!
I had the variable $dam_text as the LIKE statement, when it should have been $dam:
<?php
//connect to db stuff here
if (isset($_GET['dam_text'])) {
$dam = $_GET['dam_text'];
getSuggest($text);
}
function getSuggest($text) {
$sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam_text%'";
$query = mysql_query($sqlCommand);
$result_count = mysql_num_rows($query);
while ($row = mysql_fetch_assoc($query)) {
echo $row['name'].'<br />';
}
}
?>
Also, the variable $dam wasn't being submitted inide the function, so I moved it from the 'if' statement, into the function:
<?php
//connect to db stuff here
if (isset($_GET['dam_text'])) {
getSuggest($text);
}
function getSuggest($text) {
$dam = $_GET['dam_text'];
$sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam%'";
$query = mysql_query($sqlCommand);
$result_count = mysql_num_rows($query);
while ($row = mysql_fetch_assoc($query)) {
echo $row['name'].'<br />';
}
}
?>
The above code works perfectly! Turns out it wasn't onkeyup after all! Thanks for all your help!
OnKeyUp will only fire once per event. pressing 'A' 'B' and 'C' will result in three calls to suggest1();
To make sure your browser is working correctly try this
<script type="text/javascript">
function suggest1() {
document.getElementById('myDiv').innerHTML = document.getElementById('dam').value;
}
</script>
<input type="text" name="dam" id="dam" onkeyup="suggest1();"><br />
<div id="myDiv"></div>
You should see the div change for every keystroke that occurs in the input.
There is two many unknowns for me to directly point at your actual issue.
Your PHP will output nothing for a zero entry query, and will only output 1 item if you query LIKE only matches one thing. I think your problem lies elsewhere, an not with onkeyup
T test to onkeyup on your system/browser:
Try adding some debug header like echo strlen($text).'<br />'; to your PHP file. You should see the number change with out relying on your SQL query for every key press that adds or deletes text (that includes the backspace key).
Your code looks fine. And runs fine for me using the public HTTP GET echo service at http://ivanzuzak.info/urlecho/
Swapping out your PHP for the echo service works fine (with a bit of a typing delay)
<script type="text/javascript">
function suggest1() {
var dam_text = document.getElementById('dam').value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('MicrosoftXMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
}
}
var target = 'http://urlecho.appspot.com/echo?body=' + dam_text;
xmlhttp.open('GET', target, true);
xmlhttp.send();
}
</script>
<input type="text" name="dam" id="dam" onkeyup="suggest1();"><br />
<div id="myDiv"></div>

Categories