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.
Related
I'm developing a like/dislike system using php and MySQL, but I have a problem. When I add a like, let's say, I do it by adding a row to the likes table, that contains the post id and the user id. The user id is stored in a $_SESSION, and I can't just pass it to the html and make a AJAX request to run some php code and add the like, because this way it's too easy to simply change the user id.
So basicaly I don't want to reload the page to first get the $_SESSION value but I don't now how to get it's value after the page has loaded. I don't know if this is doable with php only, if not, what language should I use
if you're using send ajax request for saving the like or dislike value. after saving the like/dislike value. you have to return a new like value count. in PHP simply echo the value that will automatically come to your ajax success if not simply return the new like/dislike info, encode with JSON and return the value.
get these values in the success function and target the like and dislike button or div and change the new value with an ajax response.
if you want to code answer please share your code here so it's better understood by everyone
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.
Is there a way to trigger a function when a $_POST is received?
I have a php page that finishes executing and calls another page. The other page performs certain actions and POST updates back to this page. I need to be able to update a div as and when a POST is received.
Making an ajax request and using "success" callback as a trigger doesn't work since this will update my div ONLY ONCE. The problem is that this page will receive POST multiple times at irregular intervals and I need a way to trigger an action whenever POST is received.
Use Ajax (I'd use jQuery) and set a time interval to check if there was a status change. The "other page" should not post back to the first page, but save data in a "requestable" area (might be an database, a file etc) where this new info/status will be stored and retrieved periodically by the Ajax request.
Use AJAX, because you can't trigger $_POST recieving in php,
As I understand you just need to update some <div> inner html after post is recieved, and you are able to do it with jQuery events
I would do this in the following way (below is the PHP code, just FYI):
if (!empty($_POST)) {
// do whatever you mean by 'updating the div'
}
However AJAX may be more appropriate and it is (believe or not) more flexible.
AJAX call will be smaller load on your server and can update the box single or multiple times (depending on how you write the JS code) - in such case I recommend using jQuery for simplicity (if you are not familiar with JS).
usually, I would do something like this...
$var_posted=0;
if($_POST['var']){$var_posted=1;}
then...
if($var_posted==1){some_function();}
I currently have an Ajax-based chat, which I am trying to streamline by only loading the chat script when an update occurs. Thus, nothing needs to keep loading if nothing has changed in the database.
My current logic says:
JavaScript function fires every 1/2 second to get chat logs (setInterval())
If nothing has changed, though, it seems fairly inefficient to keep calling it. Instead, what I'd like to do is:
JavaScript function checks if there are any new logs in the database
If YES - load the new logs, if NO - leave the currently displayed logs alone.
How would I go about this, though? The function I am currently using is:
function updateShouts() {
$('#chatArea').load('chat.php'); // load chat logs
}
setInterval("updateShouts()", 500); // call function every half a second
I would pass timestamps (or message_ids) along with any chat messages that the server-side script sends to a client. Then the client simply asks for new messages, and the server sends only what's new.
So, imagine that each chat message has an ID. I'd design my chat.php to accept a parameter like so:
chat.php?since=12345
12345 would be the id of the last message the client has seen. chat.php essentially does something like:
SELECT * FROM chatmessages WHERE id > $since
... and passes back a nice little data structure (an array of objects, encoded in JSON, let's say).
So, if there are no new chat messages, the server is just passing back an empty array.
I don't think you can be any more efficient than that.
EDIT:
I realize that doing it this way requires a little more client-side coding. You're no longer just updating some div with the whole chat history. You'll also need to have a handler on your ajax call that iterates over the results, and for each message, programatically construct a div for that line, then appends it to your chat div.
One relatively simple way to do this is to use AJAX to fetch a page that simply tells you if there has been any update. So for example, you could fetch a page like checkForUpdate.php that has a 1 or a 0 to indicate if there is anything new in the chat. If you got a 1 back, you could go ahead and load the full chat.php page.
(If you haven't used AJAX before, this is a pretty good tutorial: http://www.tizag.com/ajaxTutorial/)
Another solution (and one that I think is probably better) is to load a page that only has the most recent chat lines. For example, say you are currently displaying lines 1-14 of the chat. You could then use AJAX to fetch the content of, for example, getLines.php?s=14. This page would only display the lines of the chat after line 14. You would then just append those lines to the end of the current chat window.
As you know the .load function fills an element with the output returned by your chat.php file. This .load function does two steps: It makes an ajax request to the chat.php and then sets the value of the element to the output of chat.php. What you want to do is just the first step. To do this use the .ajax function
http://api.jquery.com/jQuery.ajax/
Instead of using the chat.php file I would suggest calling a different script like isChatUpdated.php. That script will do just like the name suggests and check if there has been any changes in the chat. You can then use that result to figure out whether you need to call your .load function.
Either way you need to query the db in the server side, so is almost irrelevant if it returns log data or a single value.
You can decide not to update #chatArea, based on a return value, but you have to make another call to retrieve the logs, otherwise.
I would first create a file called for example messages.php that looked something like this:
<?php header('Content-Type: application/json');
$messages_since = !empty($_POST['since'])
? mysql_real_escape($_POST['since'])
: '0000-00-00 00:00:00');
// Get all messages from database since the $messages_since date_time
echo json_encode($array_with_messages);
Then on the client side using jQuery or something like that I would do something like this:
Get messages using something like $.post('messages.php', new_messages_handler)
In the handler I would create html for each new message we got back and append/prepend it to the chat container as well as store what time the latest message was created.
Wait a while
Get new messages using something like $.post('messages.php', {since: latest_datetime_we_have}, new_messages_handler)
Go to 2
At least it works pretty nicely in my head :p
I'm writing an app that uses ajax to retrieve data from a mysql db using php. Because of the nature of the app, the user clicks an href link that has an "onclick" event used to call the javascript/ajax. I'm retrieving the data from mysql, then calling a separate php function which creates a small html table with the necessary data in it. The new table gets passed back to the responseText and is displayed inside a div tag. The tables only have around 10-20 rows of data in them. This functionality is working fine and displays the data in html form exactly as it needs to be on the page.
The problem is this. the HREF "onclick" event needs to run multiple scripts one right after the other. The first script updates the "existing" data and inside the "update_existing" function is a call to refresh a section of the page with the updated HTML from the responseText. Then when that is done a "display_html" function is called which also updates a different section of the page with it's newly created HTML table. The event looks like this:
Update
This string gets built dynamically using php with parameters supplied, but for this example I simply took the parameters out so it didn't get confusing.
The "update_existion() function actually calls the display_html() function which updates a section of the page as needed. I need to update a different section of the page on the same click of the mouse right after the update, which is why I'm calling the display_html() again, right after it. The problem is only the last call is being updated on my screen. In other words, the 2nd function call "display_html()" executes and displays the refreshed data just fine, but the previous call to update_existing() runs and updates the database properly, but doesn't display on the screen unless I press the browsers "refresh" button, which of course displays the new data exactly how I want it to, but I don't want the users to have to press the "refresh" button. I tried adding multiple "display_html() calls one right after the other, separating all of them with the semicolon and learned that only the very last function call actually refreshed the div element on the html page with the table information, although all the previous display_html() calls worked, they couldn't be seen on the page without a refresh of the browser.
Is this a problem with javascript, or the ajax call, or is this a limitation in the DOM that only allows one element to be updated at a time. The ajax call is asynchroneous, but I've tried both, only async works period. This is the same in both Firefox and Internet Explorer
Any ideas what's going on and how to get around it so I can run these multiple scripts?
I'd recomment you to use jQuery javascript library. It has some funcions, like live() that can "wait" for that table to appear on the browser and apply the remaining functions on it.
Also, it's a great set of functions that will certainly help you out reducing the ammount of code you write, making it more human-readable.