So I made a website that displays FPS information stored in a mysql database. For each second of gameplay I have a pair of number(fps)-image(screenshot).
I display the numbers in a line chart made with JavaScript. The behaviour desired is when I click on a bullet in the chart, the screenshot for that particular second is displayed in a div on the page.
I have to mention that the screenshots are stored in the database and they are very low in size. I display then using PHP like this:
$query = "SELECT `image` FROM `logs` WHERE `session_id`=".$_GET['session']." AND `second`=".$second;
$sth = $mysqli->query($query);
$result=mysqli_fetch_array($sth);
if (!empty($result))
echo ' <img id="screen" src="data:image/jpg;base64,'.base64_encode($result['image']).'"/>';
The method I'm using now is when I click on a bullet in the chart (action recorded in JS), I send it as a GET parameter and read it with PHP afterwards, like this:
window.location.href = url + "?second=" + second;
This method obviously will refresh my page. The problem is, the chart I made also has a zoom/scroll option and that resets whenever the page is refreshed, making the experience very bad for the user.
Is there any method to display the screenshots without refreshing the page, for this particular case (where I have to query the database for each click/picture)? Maybe there is a better way of approaching this problem?
Thanks.
I think you've got 2 solutions which are Ajax or Websocket depending your needs.
AJAX
Ajax permit to asynchronously, only when you need, call the server and get datas from an URL which could be a webservice or PHP page... Perhaps, it's the better solution in your case.
To make it easy, you can use JQuery library by donwloading the script and insert it in your HTML :
<script src="jquery-3.0.0.min.js"></script>
To call the server, using JQuery :
$.ajax({
url: url + "/yourphppage.php",
data: "parameter=" + yourOptionelParameter,
async: false,
success: function(data) {
refreshYourChart(data);
},
error: function() {
alert("Your error");
},
contentType: 'charset=utf-8'
});
Or if your prefer pure javascript.
Now, you just have to work on the presentation of your data, on the server side. It could be what you want HTML, TXT, JSON, XML...
Websocket
Websocket is like a permanent tunnel opened between your server and the client. Each side can ask or send datas in real time.
It seems to be a library server side :
http://socketo.me/
And client side, it's very easy :
Nice documentation on mozilla website
Hope it helps. Good luck.
To change a picture source, as I see the easiest way is using an ajax call, so you can send any kind of parameters to your server, and in return your will get your new picture source.
$.get('urlToYourServer.com?parameter=1', function(data){
$('#img').attr('src', data.imgSrc);
})
Related
I have problems when saving html5 data from a page into mysql through an ajax request and trying to retrieve it back with ajax. HTML attributes that trigger some javascript such as
<onload> or <iframe> will be stored as <on<x>load> and <if<x>rame> in the database and thus screw up the page when loading it.
Here's a short description of what I am trying to accomplish: I want registered users to have the ability to highlight text on my site and get the highlighted text back after refreshing the page, relogging etc.
What I have done so far: I implemented a javascript highlight library on my server that allows users to highlight text. That works well.
By clicking a button, those data are then saved into mysql through jquery ajax post. See specific code here:
Javascript
$(document).ready(function() {
//saves highlighted data in var "highlighted"
$('#savehighlights').click(function() {
var highlighted = $('.tabcontent.content1').html();
//send data to server
$.ajax({
url: 'highlight.php',
type: 'POST',
data: {highlighted: highlighted},
dataType: 'html',
success: function(result) {
console.log(result);
}
});
});
Saving the data to mysql works generally, but it looks as if certain commands are disabled through the process (e.g. onload becomes on<x>load5). The data are stored in the database as longtext and utf8_bin. I also tried blob, but problem remains. I also tried different dataTypes with Ajax such as 'text' and 'script'. 'Text' causes the same problem and 'script doesn't work at all. I also tried the ajax .serialize function, but no luck either.
I really don't know what to do about it and I am not sure what is causing the problem, Ajax or mysql? I was searching the web for an answer, including many articles in stackoverflow (which normally always give me the answer), but this time I am stuck. Either I don't know enough about it to look for the right question, or I just don't have any luck this time. So, any help would be greatly appreciated.
I was requested to add some more information. Here it is:
I am actually doing this on my local server (localhost) with XAMP, so security issues should not be a problem, right? If it is of any help, I am doing this in a Tiki Wiki CMS. The php script that is called through ajax (highlight.php) is the following:
require_once ('tiki-setup.php');
include_once ('lib/highlights/highlightslib.php');
$highlighted = $_POST['highlighted'];
$highlightslib->save_highlights($user, $highlighted);
The highlightslib library is here:
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
header("location: index.php");
exit;
}
class HighlightsLib extends TikiLib
{
function save_highlights($user, $highlighted) {
$saveHighlights = $this->table('tiki_user_highlights');
$saveHighlights->insert
(array(
'user' =>$user,
'highlightId' =>'',
'data' =>$highlighted,
'created' =>$this->now,
)
);
return true;
}
};
$highlightslib = new HighlightsLib;
I'm having a bit of difficulty conceptualising this: I have some data stored to a button:
var input2 = '<button id="viewmap1" class="viewmap">Find on Map</button>';
//MAKE DATA
$(input2).data('longlat', coords);
Now I want to send that data to another page. I understand I am to use jQuery post, eg:
$.post("test.html", { func: "getNameAndTime" },
function(data){
alert("Hello");
}, "json");
But im not entirely sure how to go about it. Can any one point me in the right direction? Thanks
Sending data to a different page isn't as simple as it sounds. If it were simple, crackers could manipulate all the other pages that you currently have open in browser tabs.
When you call $.post(), that just sends data to the server, not to another page. The URL is a way to tell the server how to process the data but it doesn't magically connect you to the browser tab/window which has test.html open.
The usual solution is to use a single page which contains the button and the elements to display the results (a.k.a "view"). You send the POST request and then update the view in the callback function.
$(input2).on('click', function(){
// do your post stuffs
});
then need to trigger the button click
$(input2).click();
How can I send just one element from browser to server fast and without reloading browser page?
Is there an AJAX way to do this, that is a NON-FILE method? The opposite of ".load"?
.load works great sending a single element from server to browser without page reload.
How to do the opposite direction?
Browser is JavaScript.
Server is vxworks with windmarks.
PRESENT METHOD THAT WORKS BUT RELOADS PAGE:
Presently, the browser element is and I use submit to send it to the server, but this takes too long and reloads the browser page.
The element's innerHTML contains data formatted as a vxworks WINDMARK.
(When the vxworks server receives this submission, it reads the windmark and copies it to a 'C' string for backend software to process.)
If you're using jQuery and PHP then something like this should work:
JS:
$.ajax('doServerSuff.php?action1=saveLog', function() {
// do stuff after server received the data
});
PHP (doServerStuff.php):
<?php
if ($_GET['action1'] == 'saveLog') {
//do stuff
}
?>
You can get and send data using jQuery. using something like this:
$.post('urlfromserver',browserdata,function(datafromserver){
//do stuff
})
if you let me put a little bit more, it's a good idea to use JSON to send/receive data to/from server. Having that in mind, you can do something like:
$.post('urlfromserver',{browserdata: JSON.stringify(browserdata)},function(datafromserver){
javascriptObject = jQuery.parseJSON(datafromserver)
//do stuff
})
And in your PHP code, it would be as simple as using json_encode to send data to javascript and json_decode to receive data from javascript
UPDATE
Obtaining the data in the server should be as simple as requesting the object via post or get depending on your send method, and parsing the JSON.
In PHP, this is an example of obtaining data using the above code:
$dataFromBrowser = json_decode($_POST['browserdata'])
Use $.post in jQuery to send the data.
The load intruction can also be used to transmit data to the server:
$().load("url", {limit: 25}, function(){
//transmission finished
});
In this example the parameter limit with the value 25 wil be transmitted to the server.
Taken from:http://api.jquery.com/load/
You can simply do with the ajax call like this
$.ajax({
type: "POST",
url: "yourpage.php?id=someValue",
success:function(data){
//do some stuff here
});
I got it working. Here is the corrected JavaScript, from the above answer.
Here is how to change a single element at the server.
This is also an example of how to write to a vxworks windmark string at a vxworks web server, without reloading the page.
NOTE: no URL is specified, so that the same page is used.
$.ajax({
type: "POST",
url: "?general_page_to_MM_data_1_windmark=CCCCCCCCCCCCCC",
success:function(data_from_server){
}});
I am using the following click function for a purpose. What can I add so it will add 1 in a txt file when it is clicked? Like a counter on how many times it was clicked.
Thank you
$("#clearme").click(function(e) {
e.preventDefault();
// i have some stuff here
});
You can't access or edit files from the front-end. You'll need PHP or something. You can save it in a variable and pass it and process it with ajax. Something like this, untested:
var num = 0;
$button.click(function(){
$.ajax({
url: 'bla.php',
type: 'POST',
data: { num: ++num }
//...
});
});
And in PHP:
$num = $_POST['num'];
// Add to file stuff
you will have to modify the text file on the server. Send a ajax request every time the click event happens.
$("#clearme").click(function(e) {
$.post("url")
e.preventDefault();
// i have some stuff here
});
Text file where? On the server or the client machine?
If you're aiming for the client machine, javascript and jquery alone aren't going to work. There are security measures to prevent this so that would be hackers don't drop trojans on our machines every time we visit a website.
That leaves the server.
Accomplishing this depends entirely on the server side language/framework you are using (i.e. PHP, JSP, .NET).
You didn't post the reason behind needing to do this, so I'll offer the option of writing the value to a cookie instead of a file, but since you haven't told us more about what you're up to, this might not be a viable solution.
i need to change something in my site, if some fields changed in database, but without reloading the page! but i have no idea how i can do it.
could you give me an idea? thanks
example:
for example, i have a forum, and i need to show a image, if new comment resieved! i can write all functions, but i don't understand when i must call the function?
maybe window.onload?
Then you need AJAX!
Explanation:
You need two pages, the main page which does not "reload". And a second one which returns two versions of the small image based on the database field.
Page one has this JavaScript in it:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
/* normal ajax without periodical refresh
$.ajax({
url: 'page2.php',
success: function(data) {
$('#database_status').html(data);
}
});
*/
var refreshId = setInterval(function() {
$('#database_status').load('/path/to/your.php');
}, 3000);
</script>
// Or you use the jQuery plugin Heartbeat: http://www.jasons-toolbox.com/JHeartbeat/
And a div <div id="database_status">empty</div>
The second page, returns a image tag based on the database setting for example in PHP:
<?php
// do db request
if ($request) {
echo '<img src="true.gif"> TRUE';
} else {
echo '<img src="false.gif"> FALSE';
}
Ajax
Once you've familiarized yourself with the concept, you can reference the jQuery AJAX documentation for information on how to implement it with jQuery.
You can use jQuerys load- or JSON-method to get data from your server.
In your case the following scenario is possible:
The site loads.
Your JavaScript loads the initial data from the server.
Now, every couple of seconds or minutes (Depending on your use case), the JavaScript asks the server if anything changed since it last asked (Use timestamps in your request, for example).
If so, change the website accordingly.
Goto 3.
Please keep in mind that excessive polling might but enormous strains on your server, especially if you have a lot of users. Long-polling or Comet are advanced techniques to handle the load.
The easiest way to perform an ajax request with jquery is the load method. On that page you can also see plenty of examples.
There are two basic approaches you can take:
Use setInterval to make an Ajax request periodically that ask the server if there are any updates.
Use Comet to fake server push
Try Ajax, e.g: using jquery which allows you to handle those in a high level js.
example in this site when you do the send email