Save a variable from server - php

I am trying to make it possible for users to vote on some of my pictures online.
I am writing all my code in HTML, JavaScript and PHP.
When the user presses the vote button, it counts 1 up. Then when the user refreshes the page, I want to keep the vote, so it will still say 1, instead of resetting to zero.
My question is, how can I do this?
I found out I can't use javascript fileIO on my server.
I tried with some PHP, but most my code is in javascript and I can't figure out how to execute some code from a javascript function.
I have something like this in mind:
<body onload="opstart();">
When the body is loaded, I call a javascript function. Can I call some PHP here?
// Get number of votes from txt file
function opstart()
{
}
Inside this, I was thinking about reading the data from a text file and load it into the variable holding the number of votes.

Why are you storing these values in a text file. They should be in a database where you can easily pull them out in PHP. This will save you tons of time is much better practice.
You will need a users table with an ID for each user, an image table with an ID for each image, and a votes table recording who voted on what image ID. You then simply count the votes for each thing voted, and to stop someone from voting twice you can check if he has already voted!
See this answer for more details

Create one php page which accept your count and store in db
make ajax call in "opstart" function.
you can study following tutorial
http://net.tutsplus.com/tutorials/html-css-techniques/building-a-5-star-rating-system-with-jquery-ajax-and-php/

You could use a form as follows:
var feature_form =new Ext.form.FormPanel({
id: "featureInfo_panel",
url: 'myfile.php',
autoDestroy:true,
frame: true,
width: 410,
Where 'myfile.php' points to the name an location of the php you want to pass / get data from.
The php can easily trawl text files from there......

I think you dont have a proper database and you only want to do it using a text file. use Ajax to write in the text file about the last number of vote count done. Code will look something like this.
CODE
$.ajax(function(){
url:"voteup.php" //here you wrtie some function in php which takes care of file I/o
data:{votecount:9}//last vote count
success:function(){alert("success");}
}); // this function should to write new votes in your text file using ajax.
Now to read current votes on body onload. You have call a different ajax method to read that text file and get the current vote count..
CODE
function opstart()
{
$.ajax(function(){
url:"getvotes.php" //here you wrtie some function in php which takes care of file I/o
success:function(){alert("success");}
}); // this function should to read current votes in your text file using ajax.
}

Related

retrive from DB without click any button using onfocus

hi I have some problem with my code!
I have a textbox when the user write in this text box I want to retrieve from DB directly without clicking any button.
then some of my form will completed after writing in this textbox.
my JS code :
function centerIDfocus()
{
var id = document.getElementById("centerID").value;
var data = <?php $center_ID = echo mysql_num_rows(mysql_query("SELECT * FROM 'examcenter' WHERE 'id' = '".id."'")); ?> ;
}
window.onload = addEventsToHTML;
in my form:
<input name="centerID" id="centerID" onfocus="centerIDfocus();">
and that’s not working!
any ideas red face
You mixed 2 languages - javascript is run on client side and php on server side.
What You need to do is:
var data = function_to_get_data(); // in javascript
in that function call ajax request to the address of your php script - and only in that php script call your database to return desired data
You're PHP code will only run once, when the pages is loaded, after that it won't run again because there's nothing happening on the server side. If you want to run it each time you get the focus then you should be using AJAX.
Take a look at AJAX gets, I'm pretty sure that's what you want:
http://api.jquery.com/jQuery.get/
It is rather hard to know what you are intending to do, but...
My guess is that you are confused about when things happen and when "onfocus" is fired.
PHP is run on the server when the page is being constructed. In contrast, javascript is run in the browser, either after the constructed page has arrived (onload) or in response to a user click or other event such as onfocus.
Thus there is no way for the javascript (in the browser) to drop into PHP (on the server). For the same reason (and security) it is impossible for javascript to talk directly to the database.
There are two approaches you might take to do what (I think) you are attempting to do.
You could create a javascript array in PHP, indexed by ID, and containing all possible IDs and their data. Use PHP to read the database, and then echo the javascript to define the array. This would become part of the page sent. Then, in response to the event that means you want to fill the field, you extract the data from the array, and put it where you want it. This would be slow for the page to load, but very quick response to the click that triggered the change.
An alternative is to use ajax. The easiest way is to use jquery to send a GET request to the the server requesting the data related to the ID. The server must respond to that URL by extractign the ID, reading the database and generating the reply. I recommend using JSON. Then, when the jquery request returns, the javascript code can move the data from the JSON into your field. This would make the initial page lighter, but would have a fetch delay to the triggering click.
However I think you may also have an issue with the on-focus event. This fires when the user moves the cursor into the field, before they have entered any data. At that point it will contain the data that was set in the HTML. If you can set the ID at that point, you can also set it to the data from the database.
I think you want two fields - one for the ID and another for the looked up data. Then you run the javascript on the onblur event on the ID field.
Hope that helps.
use something like:
$('.centerID').keyup(function(){
var val = this.val();
var url = '/do.php'; // url to a php script
var val = 'action=checkValue&value='+val; // send it the value
$.getJSON(url, val, function(data){
// Something to do when you get the data back
});
});
then just create a php script that checks the database and returns a JSON answer and then do as you please with it.
BTW - I'm assuming you are ok using jQuery. You can apply this to your JavaScript too.
I used keyup() as one example but you can appy this to keydown(), click(), focus(), focusout() etc...
I have a do.php script that contains a switch statement with the possible value of action= and returns JSON. Everything from logging in, registering, activity monitor, to updating a database field without leaving the page.

Dynamic document.title using a $_SESSSION variable

I have a page that uses ajax to show users their current assignments. Instead of having to refresh the page to see if there are any updates, I'm using ajax to update the data every 4 seconds. It's been requested that I change the document title to show something like "Number of Tasks: 4" and have that update as well when the user either completes a new task, or gets assigned another one. I tried using a simple "setInterval" javascript function, but since PHP is server side, the variable piece doesn't update...
I've also tried setting "document.title" from within the ajax code, but that just plain didn't work.
Is there a simple way to update the document title to show the number of tasks assigned to the user viewing the page?
Return the value from the $_SESSION in the data sent with the AJAX response to the client Javascript code. Once you have it on the client side set whatever you need to it with javascript.
You'd have to call with ajax a php dedicated to return you only the number of tasks (and other information you may want).
To change the title you can just call document.title = "the data returned in ajax";.
And put all this code (ajax call and title set) inside a function with setinterval as you mentioned.

Using jQuery.post() to submit content and display what's going on

This is more of curiosity that anything, but I can think of several places (mainly in admin sections) where this could be useful. I know the title is confusing so this is what I mean:
Say you have a form that posts to example_cb.php. example_cb.php is a very large callback page that generates multiple thumbnails of an image, puts them in their respective directories, adds them to a database, etc. You already have the form posting by jquery with a function like this
$.post('example_cb.php', $(this).serialize(), function(data) {
// Success
}, 'json');
Before posting it updates a div to say "processing" of something. Then after it successfully completes the div fades out. However you want the div to show what is happening on the server side. i.e. Converting 200X200 thumb > Converting 350x350 thumb > Adding Records to Database > etc.
How can you accomplish this?
I know it's a loaded question, but I'm confident there are people on here smart enough to figure it out. If you need more info please comment :)
You could do something like -
Write each 'event' update to a database table
Write a page that retrieves the last n events from table
Use something like 'load' to call page update an onscreen div
with the updated progress.
Use 'setTimeout` to keep updating.
This could be accomplished most easily with using the push method, but I'm not too familiar with ajax push or comet technology, so I'll give you a pull solution.
Basically you need to create the initial ajax request to start the processing. Then, you need to have another request running in a tight loop that checks against a php page for the current status. For example, on the php page doing the processing, you can update a _SESSION key that stores the current processing information (like "Converting 200X200 thumb") at each step. Another php page will exist purely to print that information and you can retrieve it with the JS running in a loop.
pusher like services may be used for bi-directional communication.
I'm putting it down for reference, though this would be overkill for such a simple scenerio.

AJAX autorefresh making only last entry visible !

Iam new to PHP . I wanted to make a forum where users can ask questions.I am using ajax to auto refresh the page.But it creates some problems...
Firstly, if I make that particular div ,where most recent question will be displayed,refresh only the latest question is displayed .
let me clear it with an ex :
User A opens the forum
He gets questions qlatest,q1,q2,q3 . Where div containg qlatest refreshes every 1 sec
User B posts a question qlatest2
qlatest is replaced by qlatest2 !
Now should I make whole div conatining all the questions make refresh?
If I understand correctly you want to create something like the Twitter feed where the latest item is displayed on top of each other.
The reason that the entire DIV refreshes is because you are rewriting the entire inner HTML of that DIV. To avoid this, use .appendChild() and program your PHP callback file to only pull the latest record from the database.
http://www.ezineasp.net/post/Javascript-Append-Div-Contents.aspx
JQuery also has some very useful functions adding children. I suggest using a Javascript library if you are new to AJAX calls.
You have to:
Add some data source that returns last asked question.
Invoke that data source on a constant interval and load returned question into the div..
The simplest to explain is the following solution:
Write JavaScript code that uses JS builtin function setInterval() to load eg. script last_question.php into the div. You can do it eg. using jQuery load() function, which can look eg. like this (assuming your div has ID of "last_question"):
jQuery('#last_question').load('last_question.php');
Of course it can be optimized. To do so, read about:
Long polling
JSON format
jQuery.requestJSON() jQuery function
Maybe some effects to make the question change smoother (like slide out and slide in)

Refresh Using Ajax/PHP

Further to my question yesterday (here), I am working on a webpage that has a section that shows 'live' order details.
The top half of my webpage has Spry Tabbed Panels. One of the panels contains an include call to a separate php page that I have created (getOpenOrders.php). This contains an SQL query to obtain all open orders and then puts the details into a table.
As a result, the table of open orders is shown in the Spry panel. What steps do I now need to take to have this refresh every 15 seconds?
Do you really want to call the database every 15 seconds for each user? isn't that an overload?
I'm not saying that your database will be overloaded, but, thats how you shouldn't do things!
Edited
you should show an image, or the link to that page in order to gt an appropriate answer, because it all depends in what are you doing in the table.
because I don't know, I will give you an answer on what probably is happening.
Because you said that you're new to the ajax world, let's make things simple, and not to complicate on the you should return a JSON object and use it to re populate your table. :)
So we will start with 2 buttons (Previous and Next) so the user can move the data that is showing (you probably don't want to give him/her 100 lines to see right?)
let's say that you have 2 pages, a showData.php and getTable.php, in the showData.php you will need to load jQuery (wonderful for this) and add a little code, but where the table is to be placed, just add a div tag with an id="myTable" because we will get the data from the getTable.php file.
getTable.php file has to output only the table html code with all the data in, without no html, body, etc... the idea is to add inside the div called myTable all the code generated by getTable.php
Let's imagine that getTable.php gets a page variable in the queryString, that will tell what page you should show (to use LIMIT in your MySQL or PostgreSQL database)
You can use jQuery plugin called datatables witch is one of my choices, check his example and how small code you need to write! just using jQuery and Datatables plugin.
The first description follows the jQuery.Load() to load the getTable.php and add as a child of the div and wold do this for the previous and next buttons, passing a querystring with the page that the user requested. It's to simple and you can see the website for that, if you prefer to use the DataTables plugin, then just follow their examples :)
if you, after all this need help, drop me a line.
<META HTTP-EQUIV=Refresh CONTENT="15; URL=<?php print $PHP_SELF ?>">
This should be in between the head tags.
-or-
header('Refresh: 15');
This should be before the head tag and directly after the html tag.
As said by balexandre, a different method should be used. One that does not require a database hit every 15 seconds for every single user that is connected to the site. But, there is your answer anyways.
Although, balexandre makes a very good point, if you do decide that you need a refresh, you could simply do something like this in your JavaScript:
window.onload = function( )
{
setTimeout( 'window.location.refresh( )', 1500 );
}
(I've not tested the above code, so syntax may need to be tweaked a little, but you get the idea)

Categories