html5 - Server side events: Replace line instead of append - html

I am aiming at using HTML5 SSE (Server Side Events) to send updates of data from server to the client. Currently the time is appended as an extra line. I am using the [\n\n] in the php-file in order to stop the stream.
Question: How can I replace the complete line insted of having it appended? I want the replacement to be in the same place, thus be kept inside the div [result].
I have tried to remove the br-tag at line 17 of the html-file, but it did not remove the "newline".
My html5 file, with js included:
<h1>SSE test</h1>
<div id="result"></div>
<script>
// Create an object
var source = new EventSource("updater.php");
// Detect message receipt
source.onmessage = function(event) {
// Write the received data to the page
document.getElementById("result").innerHTML += event.data + "<br>";
};
</script>
my php file:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
// The server time
$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>

In your source.onmessage callback, just change the line to this:
document.getElementById("result").innerHTML = event.data + "<br>";
The problem is caused by the += operator, which appends the new result to the previous one. Now, with = it overwrites the old result, thereby solving the problem.

Related

The following data would have been submitted to the server (in Laravel 8)

I try using modal on this page but I encountered an error saying
127.0.0.1:8080 says The following data would have been submitted to the server
Fixed
I am able to fix this by locating this file "js/pages/data-table.js" and I comment out the "Form inputs"
//---------------Form inputs
// var table = $('#example6').DataTable();
// $('button').click( function() {
// var data = table.$('input, select').serialize();
// alert(
// "The following data would have been submitted to the server: \n\n"+
// data.substr( 0, 120 )+'...'
// );
// return false;
// } );
If for some reason commenting the form input did not work out. All you have to do is copy the entire code in the Js/pages/data-table.jd into another JS file. Include the new js file into your project
Remember to comment out or remove the form input example6 data table in your new js file.
Enjoy

Phoegap/Cordova to load specific DB row after AJAX GET

Im building an app using PHoneGap as the compiler so using HTML5, CSS, JQuery, AJAX etc. Ive manage to get AJAX to GET all the rows from the Database perfectly well, as I have to use .HTML extension on my files I'm struggling to be able to link through to specific DB record. I can do this perfectly in PHP. Im struggling with the HTML part.
Here is my AJAX Loader to get all Rows from DB
var inProcessVideos = false;//Just to make sure that the last ajax call is not in process
setTimeout( function () {
if (inProcessVideos) {
return false;//Another request is active, decline timer call ...
}
inProcessVideos = true;//make it burn ;)
jQuery.ajax({
url: 'https://MY-URL.COM/videos-mysql.php', //Define your script url here ...
data: '', //Pass some data if you need to
method: 'POST', //Makes sense only if you passing data
success: function(answer) {
jQuery('#videos-modules').html(answer);//update your div with new content, yey ....
inProcessVideos = false;//Queue is free, guys ;)
},
error: function() {
//unknown error occorupted
inProcessVideos = false;//Queue is free, guys ;)
}
});
}, 500 );
And here is the contents of the PHP File that renders all the Results from the Database. This part displays the content perfectly.
<?php
include ("../config/mysqli_connect.php");
$sql = ("SELECT * FROM videos");
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "
<a href='" . $row["id"]. "'>
<div class='video-module'>
<div class='video-thumb'><img src='https://MY-URL.COM/thumbs/" . $row["video_thumb"]. "'></div>
<div class='video-thumb-details'>
<div class='video-thumb-title'> " . $row["id"]. " - " . $row["video_title"]. "</div>
" . $row["publisher_name"]. "
</div>
</div></a>
";
}
} else {
echo "0 results";
}
?>
After the ECHO statement I would normally put something like video-Profile.php?id=$id and it would go to that page and pull in that record from the Database.
However now that I have to do it only in HTML, and im assuming AJAX, how to I achieve this.
Here is the PHP and the MYSQL Query to GET the specific record from the Database. Its currently in MYSQL, I will convert it to MYSQLi once I've got it working and got my head around it.
<?php
// Use the URL 'id' variable to set who we want to query info about
$id = ereg_replace("[^0-9]", "", $_GET['id']); // filter everything but numbers for security
if ($id == "") {
echo "Missing Data to Run";
exit();
}
//Connect to the database through our include
include_once "../config/connect_to_mysql.php";
// Query member data from the database and ready it for display
$sql = mysql_query("SELECT * FROM videos WHERE id='$id' LIMIT 1");
$count = mysql_num_rows($sql);
if ($count > 1) {
echo "There is no user with that id here.";
exit();
}
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$video_title = $row["video_title"];
$video_thumb = $row["video_thumb"];
$publisher_name = $row["publisher_name"];
$video_directory = $row["video_directory"];
$video_path = $row["video_path"];
$upload_date = $row["upload_date"];
$video_views = $row["video_views"];
}
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<?php echo ("$id");?> - <?php echo ("$video_thumb");?>
</body>
</html>
I know this works if I'm running PHP files, and my server is set to PHPv5.3., but before I make it live, it will be sorted to MYSQLi and run on PHP7???
Im looking for inspiration to get this to function via HTML only files.
thanks for your help everyone.
This is a pretty brutalistic way of doing this - typically you'd return JSON or similar from the PHP and then process this into the HTML elements within your JS. But for this case you can do this:
//within call
success: function(answer) {
var contents = jQuery(answer); // You have now converted the HTML into a jquery model
contents.filter(function(element){
return $(element).attr('id') === id
}) // This allows you to search your child elements and pick them based on criteria
jQuery('#videos-modules').html(contents); // now assign the remaining elements into your html as before
},
I have Tried this but i cant seem to find out how to Run a Console Log as it is Run on iOS iPad at the moment. Can not get it to render in the Browser.
var inProcessVideos = false;//Just to make sure that the last ajax call is not in process
setTimeout( function () {
if (inProcessVideos) {
return false;//Another request is active, decline timer call
}
inProcessVideos = true;//make it burn ;)
jQuery.ajax({
url: 'https://MYURL.COM/appFiles/tablet/video-profile.php', //Define your script url here ...
data: '', //Pass some data if you need to
method: 'GET', //Makes sense only if you passing data
success: function(answer) {
var contents = jQuery(answer); // You have now converted the HTML into a jquery model
contents.filter(function(element){
return $(element).attr('id') === id;
});
jQuery('#videoProfile').html(answer);//update your div with new content, yey ....
inProcessVideos = false;//Queue is free, guys ;)
},
});
}, 500 );
Struggling with this, i've looked at all the JQuery, AJAX MySQL web sites i can find including W3Schools, Jquery.com and many others. Just can not get it to pass the ID to the PHP file to get the Record from the DB via AJAX.
My Links in the first JQuery AJAX Call are:
<a href='video-Profile.html' data='".$row["id"]."' value='".$row["id"]." '>Some HTML STUFF/Images/Text etc</a>
I can get the ID and the First AJAX Call to show ALL the rows in the DB Table. Now just need to show Record by ID. This is what i cant get my head around. And it must be in .HTML Page as its an App compiled via PhoneGap. I know im repeating my self, Just not to sure if im making my point clear. Thanks for the help in advance.

HTML5 - Server side events - Using external text file as data input

I am attempting of using a plain text-file (text.txt) as part of html5 - server side events.
Currently I am not seeing any printout of text in browser. If just running this line, without using an external file for input data, it works:
echo "data: test\n\n";
Question: What do I need to adjust to make the external file data to be visible in the browser, assuming the setup of below files?
My html file
<h1>SSE</h1>
<div id="result"></div>
<script>
// Create an object
var source = new EventSource("updater.php");
// Detect message receipt
source.onmessage = function(event) {
// Write the received data to the page
document.getElementById("result").innerHTML += event.data + "<br>";
};
</script>
my php file
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
// Include files
echo include("text.txt");
flush();
?>
my text file:
"data: t1972\n\n";
The solution for the question, works if using [file_get_contents] as specified below.
$data = file_get_contents('text.txt');
echo "data: " . $data . "\n\n";
This also means that the file [text.txt] is left with only text, removing the [data: ] and [\n\n].

Google Translate free api assist

I am kind of new to javascript and building websites, I program c# most of the times.
I am trying to build something and I need to use google translate api, the problem that is cost money so I prefer use Free API so I found this.
https://ctrlq.org/code/19909-google-translate-api
so I changed it a bit and tried alone, because I wasn't sure what e type ment.
so this is my code:
function doGet(text) {
var sourceText = text;
var translatedText = LanguageApp.translate('en', 'iw', sourceText);
var urllog = "https://translate.googleapis.com/translate_a/single?client=gtx&sl="
+ "en" + "&tl=" + "iw" + "&dt=t&q=" + encodeURI(text);
var result = JSON.parse(UrlFetchApp.fetch(urllog).getContentText());
translatedText = result[0][0][0];
console.log(translatedText);
}
so the url is downloading me a text file called "f.txt" that include the translate code the problem is that I doesnt want it to download File,
I just need the translate inside the txt file its gives me,
also the problem is I am not sure how to get that info inside a javascript variable, And I doesnt want it to give me that file as well..
So how Can I read it?
how can I use the file without download it, and How can I push it to a string variable?
And How I can cancel the download and get only the translate?
THANKS!
By the way
and if anyone know the function doGet(e) that I showed on the link, what is "e"? what does the function wants?
I know I'm a year late but I came to same problem and fixed it using PHP. I have created this simple PHP function:
function translate($text, $from, $to) {
if($text == null)
echo "Please enter a text to translate.";
if($from == null)
$from = "auto";
if($to == null)
$to = "en";
$NEW_TEXT = preg_replace('/\s+/', '+', $text);
$API_URL = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" . $from . "&tl=" . $to . "&dt=t&q=" . $NEW_TEXT;
$OUTPUT = get_remote_data($API_URL);
$json = json_decode($OUTPUT, true); // decode the JSON into an associative array
$TRANSLATED_OUTPUT = $json[0][0][0];
echo $TRANSLATED_OUTPUT;
}
Example usage (English to Spanish):
translate("Hello", "en", "es"); //Output: Hola
/*
sourceLanguage: the 2-3 letter language code of the source language (English = "en")
targetLanguage: the 2-3 letter language code of the target language (Hebrew is "iw")
text: the text to translate
callback: the function to call once the request finishes*
* Javascript is much different from C# in that it is an asynchronous language, which
means it works on a system of events, where anything may happen at any time
(which makes sense when dealing with things on the web like sending requests to a
server). Because of this, Javascript allows you to pass entire
functions as parameters to other functions (called callbacks) that trigger when some
time-based event triggers. In this case, as seen below,
we use our callback function when the request to google translate finishes.
*/
const translate = function(sourceLanguage,targetLanguage,text,callback) {
// make a new HTTP request
const request = new XMLHttpRequest();
/*
when the request finishes, call the specified callback function with the
response data
*/
request.onload = function() {
// using JSON.parse to turn response text into a JSON object
callback(JSON.parse(request.responseText));
}
/*
set up HTTP GET request to translate.googleapis.com with the specified language
and translation text parameters
*/
request.open(
"GET",
"https://translate.googleapis.com/translate_a/single?client=gtx&sl=" +
sourceLanguage + "&tl=" + targetLanguage + "&dt=t&q=" + text,
true
);
// send the request
request.send();
}
/*
translate "This shouldn't download anything" from English to Hebrew
(when the request finishes, it will follow request.onload (specified above) and
call the anonymous
function we use below with the request response text)
*/
translate("en","iw","This shouldn't download anything!",function(translation) {
// output google's JSON object with the translation to the console
console.log(translation);
});

How to Pass a PHP Variable to a MySql Query to Create an Excel Document Download

I am trying to pass a variable from one PHP page to another PHP page, which will trigger an Excel download. However, I cannot figure out how to pass the variable and still have the download trigger. I understand that my PHP page which creates the Excel file cannot have any variables passed to it, or the download will not trigger.
For example, I would like to do the following (very simple example):
variable.php
<?php
$date = '2012-02-15';
echo '<input type="text" id="date" value="'.$date.'"/>';
echo '<span onclick="excelDownload()">Click</span>';
?>
passing.js
function excelDownload(str)
{
Ajax...
var date = document.getElementById('date').value;
var queryString = "?date=" + date;
xmlhttp.open("GET", "excel.php" + queryString, true);
Ajax....
}
excel.php
<?php
Connect to database...
$date = $_GET['date'];
$file = "Names: ";
$result = mysql_query("SELECT * FROM Something WHERE date_field = '$date'");
$data = mysql_fetch_array($result);
$file.= $data['names']." ";
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=names.xls");
header("Pragma: no-cache");
header("Expires: 0");
print $file;
?>
Unfortunately, the $_GET[date'] variable causes the excel.php to not download. I have been able to get away with writing static MySql queries within the excel.php page, so I do not have to pass any variables. However, I now have the need to create dynamic excel downloads, but I am not strong enough in php to figure out my options. On a side note, I use Ajax and do not utilize "submit". Will this be a problem?
I figured out my problem and wanted to share my findings to close out this question. Basically, I should have been more detailed in my question. My Ajax function needed some tweaking so that the variable would pass and allow the headers to trigger a download.
I was using the following in my Ajax function:
Ajax...
{
if (xmlhttp.readyState == 4)
{
//nothing to allow download to trigger
}
}
var date = document.getElementById('date').value;
var queryString = "?date=" + date;
xmlhttp.open("GET", "excel.php" + queryString, true):
xmlhttp.send(null);
However, I should have used this:
Ajax...
{
if (xmlhttp.readyState == 4)
{
window.location = "excel.php" + queryString;
}
}
var date = document.getElementById('date').value;
var queryString = "?date=" + date;
xmlhttp.open("GET", "excel.php" + queryString, true):
xmlhttp.send(null);
While I was thinking my problem had to do with output before header(), the real issue was passing the variable.