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
Related
Is it possible to set PHP session variables using Javascript?
In JavaScript:
jQuery('#div_session_write').load('session_write.php?session_name=new_value');
In session_write.php file:
<?
session_start();
if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>
In HTML:
<div id='div_session_write'> </div>
The session is stored server-side so you cannot add values to it from JavaScript. All that you get client-side is the session cookie which contains an id. One possibility would be to send an AJAX request to a server-side script which would set the session variable. Example with jQuery's .post() method:
$.post('/setsessionvariable.php', { name: 'value' });
You should, of course, be cautious about exposing such script.
If you want to allow client-side manipulation of persistent data, then it's best to just use cookies. That's what cookies were designed for.
or by pure js, see also on StackOverflow :
JavaScript post request like a form submit
BUT WHY try to set $_session with js? any JS variable can be modified by a player with
some 3rd party tools (firebug), thus any player can mod the $_session[]! And PHP cant give js any secret codes (or even [rolling] encrypted) to return, it is all visible. Jquery or AJAX can't help, it's all js in the end.
This happens in online game design a lot. (Maybe a bit of Game Theory? forgive me, I have a masters and love to put theory to use :) ) Like in crimegameonline.com, I
initialize a minigame puzzle with PHP, saving the initial board in $_SESSION['foo'].
Then, I use php to [make html that] shows the initial puzzle start. Then, js takes over, watching buttons and modding element xy's as players make moves. I DONT want to play client-server (like WOW) and ask the server 'hey, my player want's to move to xy, what should I do?'. It's a lot of bandwidth, I don't want the server that involved.
And I can just send POSTs each time the player makes an error (or dies). The player can block outgoing POSTs (and alter local JS vars to make it forget the out count) or simply modify outgoing POST data. YES, people will do this, especially if real money is involved.
If the game is small, you could send post updates EACH move (button click), 1-way, with post vars of the last TWO moves. Then, the server sanity checks last and cats new in a $_SESSION['allMoves']. If the game is massive, you could just send a 'halfway' update of all preceeding moves, and see if it matches in the final update's list.
Then, after a js thinks we have a win, add or mod a button to change pages:
document.getElementById('but1').onclick=Function("leave()");
...
function leave() {
var line='crimegameonline-p9b.php';
top.location.href=line;
}
Then the new page's PHP looks at $_SESSION['init'] and plays thru each of the
$_SESSION['allMoves'] to see if it is really a winner. The server (PHP) must decide if it is really a winner, not the client (js).
You can't directly manipulate a session value from Javascript - they only exist on the server.
You could let your Javascript get and set values in the session by using AJAX calls though.
See also
Javascript and session variables
jQuery click event to change php session variable
One simple way to set session variable is by sending request to another PHP file. Here no need to use Jquery or any other library.
Consider I have index.php file where I am creating SESSION variable (say $_SESSION['v']=0) if SESSION is not created otherwise I will load other file.
Code is like this:
session_start();
if(!isset($_SESSION['v']))
{
$_SESSION['v']=0;
}
else
{
header("Location:connect.php");
}
Now in count.html I want to set this session variable to 1.
Content in count.html
function doneHandler(result) {
window.location="setSession.php";
}
In count.html javascript part, send a request to another PHP file (say setSession.php) where i can have access to session variable.
So in setSession.php will write
session_start();
$_SESSION['v']=1;
header('Location:index.php');
Not possible. Because JavaScript is client-side and session is server-side. To do anything related to a PHP session, you have to go to the server.
be careful when doing this, as it is a security risk. attackers could just repeatedly inject data into session variables, which is data stored on the server. this opens you to someone overloading your server with junk session data.
here's an example of code that you wouldn't want to do..
<input type="hidden" value="..." name="putIntoSession">
..
<?php
$_SESSION["somekey"] = $_POST["putIntoSession"]
?>
Now an attacker can just change the value of putIntoSession and submit the form a billion times. Boom!
If you take the approach of creating an AJAX service to do this, you'll want to make sure you enforce security to make sure repeated requests can't be made, that you're truncating the received value, and doing some basic data validation.
I solved this question using Ajax. What I do is make an ajax call to a PHP page where the value that passes will be saved in session.
The example that I am going to show you, what I do is that when you change the value of the number of items to show in a datatable, that value is saved in session.
$('#table-campus').on( 'length.dt', function ( e, settings, len ) {
$.ajax ({
data: {"numElems": len},
url: '../../Utiles/GuardarNumElems.php',
type: 'post'
});
});
And the GuardarNumElems.php is as following:
<?php
session_start();
if(isset ($_POST['numElems'] )){
$numElems = $_POST['numElems'];
$_SESSION['elems_table'] = $numElems;
}else{
$_SESSION['elems_table'] = 25;
}
?>
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);
})
I have one of those websites that basically gives you a yes or no response to a question posed by the url. An example being http://isnatesilverawitch.com.
My site is more of an in-joke and the answer changes frequently. What I would like to be able to do is store a short one or two word string and be able to change it without editing the source on my site if that is possible using only javascript. I don't want to set up an entire database just to hold a single string.
Is there a way to write to a file without too much trouble, or possibly a web service designed to retrieve and change a single string that I could use to power such a site? I know it's a strange question, but the people in my office will definitely get a kick out of it. I am even considering building a mobile app to manipulate the answer on the fly.
ADDITIONAL:
To be clear I just want to change the value of a single string but I can't just use a random answer. Without being specific, think of it as a site that states if the doctor is IN or OUT, but I don't want it to spit out a random answer, it needs to say IN when he is IN and OUT when he is out. I will change this value manually, but I would like to make the process simple and something I can do on a mobile device. I can't really edit source (nor do I want to) from a phone.
If I understand correctly you want a simple text file that you change a simple string value in and have it appear someplace on your site.
var string = "loading;"
$.get('filename.txt',function(result){
string = result;
// use string
})
Since you don't want to have server-side code or a database, one option is to have javascript retrieve values from a Google Spreadsheet. Tabletop (http://builtbybalance.com/Tabletop/) is one library designed to let you do this. You simply make a public Google Spreadsheet and enable "Publish to web", which gives you a public URL. Here's a simplified version of the code you'd then use on your site:
function init() {
Tabletop.init( { url: your_public_spreadshseet_url,
callback: function (data) {
console.log(data);
},
simpleSheet: true } )
}
Two ideas for you:
1) Using only JavaScript, generate the value randomly (or perhaps based on a schedule, which you can hard code ahead of time once and the script will take care of the changes over time).
2) Using Javascript and a server-side script, you can change the value on the fly.
Use JavaScript to make an AJAX request to a text file that contains the value. Shanimal's answer gives you the code to achieve that.
To change the value on the fly you'll need another server-side script that writes the value to some sort of data store (your text file in this case). I'm not sure what server-side scripting (e.g. PHP, Perl, ASP, Python) runtime you have on your web server, but I could help you out with the code for PHP where you could change the value by pointing to http://yoursite.com/changeValue.php?Probably in a browser. The PHP script would simply write Probably to the text file.
Though javascript solution is possible it is discouraged. PHP is designed to do such things like changing pieces of sites randomly. Assuming you know that, I will jump to javascript solution.
Because you want to store word variation in a text file, you will need to download this file using AJAX or store it in .js file using array or string.
Then you will want to change the words. Using AJAX will make it possible to change the words while page is loaded (so they may, but do not have to, change in front of viewers eyes).
Changing page HTML
Possible way of changing (words are in array):
wordlist.js
var status = "IN"; //Edit IN to OUT whenever you want
index.html
<script src="wordlist.js"></script>
<div>Doctor is <span id="changing">IN</span></div>
<script>
function changeWord(s) { //Change to anything
document.getElementById("changing").innerHTML = s;
}
changeWord(status); //Get the status defined in wordlist.js
</script>
Reloading from server
If you want to change answer dynamically and have the change effect visible on all open pages, you will need AJAX or you will have to make browser reload the word list, as following:
Reloading script
function reloadWords() {
var script = document.createElement("script"); //Create <script>
script.type="text/javascript";
script.src = "wordlist.js"; //Set the path
script.onload = function() {changeWord(status)}; //Change answer after loading
document.getElementsByTagName("head")[0].appendChild(script); //Append to <head> so it loads as script. Can be appended anywhere, but I like to use <head>
}
Using AJAX
Here we assume use of text file. Simplest solution I guess. With AJAX it looks much like this:
http = ActiveXObject==null?(new XMLHttpRequest()):(new ActiveXObject("Microsoft.XMLHTTP"));
http.onloadend = function() {
document.getElementById("changing").innerHTML = this.responseText; //Set the new response, "IN" or "OUT"
}
http.open("GET", "words.txt")
http.send();
Performance of AJAX call may be improved using long-poling. I will not introduce this feature more here, unless someone is interested.
I have an update panel with a timer control set up to automatically check for some data updates every minute or so.
If it sees that the data updates, it is set to call a local script with the serialized JSON data.
ScriptManager.RegisterStartupScript(UpdateField, GetType(HiddenField), ACTION_CheckHistoryVersion, "updateData(" & data & ");", True)
where "data" might look something like
{
"someProperty":"foo",
"someOtherProperty":"bar",
"someList":[
{"prop1":"value"},
{"prop2":"value"}, ...
],
"someOtherList":[{},...,{}]
}
"data" can get quite large, and sometimes only a few items change.
The problem I am having is this. Every time I send this back to the client, it gets added as a brand new script block and the existing blocks do not get removed or replaced.
output looks something like this:
<script type="text/javascript">
updateData({
"someProperty":"foo",
"someOtherProperty":"bar",
"someList":[
{"prop1":"value"},
{"prop2":"value"}, ...
],
"someOtherList":[{},...,{}]
});
</script>
<script type="text/javascript">
updateData({
"someProperty":"foo",
"someOtherProperty":"bar",
"someList":[
{"prop1":"changed"},
{"prop2":"val"}, ...
],
"someOtherList":[{},...,{}]
});
</script>
<script type="text/javascript">
updateData({
"someProperty":"foos",
"someOtherProperty":"ball",
"someList":[
{"prop1":"changed"},
{"prop2":"val"}, ...
]
});
</script>
with a new script block being created every time there is a change in the data.
Over time the amount of data accumulating on the browser could get potentially huge if we just keep adding this and I can't imagine how most people's browser would take it, but I don't think it could be good.
Does anyone know if there is a way to just replace the code that has been sent back to the browser rather than continuously adding it like this?
I came up with a hack that seems to work in my situation.
I am using jQuery to find the script tag that I am creating and remove it after it has been called.
Here is an example:
First I generate a guid:
Dim guidText as string = GUID.NewGuid().ToString()
I create a function like the following:
function RemoveThisScript(guid){
$("script").each(function(){
var _this = $(this);
if(_this.html().indexOf(guid)>-1)
_this.remove();
});
}
Then I add the following code to my output string:
... & " RemoveThisScript('" & guidText & "');"
This causes jQuery to look through all the scripts on the page for one that has the GUID (essentially the one calling the function) and removes it from the DOM.
I would recommend to use web service with some webmethod which you will call inside window.setInterval. In success handler of your webmethod (on client side) you can just take response and do whatever you want with it. And it will not be saved in your page (well, if you will do everything wrong). Benefit is that you will minimize request size(updatepanel will pass all your viewstate data, which could be large enough) and will limit server resources usage (update panel is causing full page live cycle, suppose slightly modified, but anyway - all those page_load, page_init, etc...) and with web service you will only what you need.
Here is an article where you can see how it could be created and used on client side. Looks like good enough.
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.