I'm making a messaging system and I am currently reloading the content of the div holding the messages every 10 seconds using jQuery's .load(), but I have a problem: When trying to make a "Select all" button, "Delete selected" button, etc. when that 10 seconds comes up it reloads the buttons and it reloads the messages, so the messages get deselected because of the reload.
What I would like to know is how to make it actually load in new messages, but not actually reload the whole div. I know that Gmail does not reload the whole div because it works properly.
This is my JavaScript function that reloads the div and changes the page title (that has inbox count) so it stays updated:
function title() {
setTimeout("document.title = $('#heading').text();", 500);
}
function ajaxStuff() {
setTimeout("$('#heading').load('/employee/message/inbox.php #h1_head'); $('#messages').load('/employee/message/inbox.php #messages_inner');title();ajaxStuff();", 10000);
}
ajaxStuff();
Here is how I have the inbox set up:
Basically what I want to do is load in new messages with AJAX but somehow not refresh the div. I tried looking at Gmail's source but there's too much to go through and they make it confusing with a bunch of random classes and IDs.
Note: I have searched this on Google for a while now and did not find anything.
In response to comments:
I don't think a tutorial is warranted here. Change your server code to return the "new" messages with a class="new" attribute, then use:
$.ajax({
url: "/employee/message/inbox.php",
success: function(result) {
$(result).find(".new").prependTo("#heading");
}
});
Of course, that code may need some modifications to fit your environment/return data.
When checking for new messages send an ID of the newest message in your request. Then your php will return only everything newer that you add to your existing data.
jQuery.ajax({
type: 'get',
dataType: 'text',
url: "/employee/message/inbox.php",
data: {
from_user : from_user,
to_user: to_user,
message_id: message_id,
something_else_you_need_to_send: its_value
t: Math.random()
},
success: function(data, textStatus){
// whatever you need to do with the result returned from php (server)
}
Then in your sql query you do
select * from table
where user_id=user_id_from_ajax
and message_id > message_id_from_ajax`
update
in your php you use
$from_user = $_REQUEST['from_user'];
$to_user = $_REQUEST['to_user'];
$message_id = $_REQUEST['message_id'];
Related
So, I want delete records from database using confirm() function, inside this alert should been shown what will be deleted when "OK" button will be clicked. To sum up, I just want to put php file inside the confirm().
function deleteGame() {
if(confirm('Do you want delete this?')){
$(".deleteButtton").load('deleteGame.php?id=' + $(".deleteButtton").data("id"));
}
}
Hmmm, I guess you must try AJAX Request for deleting record, check the following code for reference.
if (confirm("Do you want this to be deleted?")){
//HERE YOU CAN SHOW SOME PROGRESS WHILE THE JS IS REQUESTING PHP TO DELETE FILE
$.get(
"deleteGame.php",
{
id: $(".deleteButtton").data("id")
},
function (result){
/*ASSUMING THAT YOUR PHP FILE WILL RETURN "deleted" AFTER DELETING RECORD.*/
if (result === "deleted"){
alert('DELETED!); //SOME ACTION AFTER DELETING.
}else{
alert('ERROR'); //SOME ACTION FOR ERROR
}
}
);
}
I WOULD SUGGEST USING POST METHOD INSTEAD OF GET METHOD FOR SECURITY ISSUES.
Whenever you want to run a php function similar to deletion of a db record you have pretty much 2 options.
Open a new page in your browser or redirect a user to a new page.
Open a new page "silently" in a background without user knowing it.
The first option is ok, if you dont mind showing user a different page. For example if you wanted to show a page that would have text in it "Thank you for deleting this record". Achieving this would be really simple, you could just use javascript redirect like this:
if(confirm('Do you want delete this?')){
window.location.href = 'deleteGame.php?id=' + $(".deleteButtton").data("id");
}
However in some cases you want to run the php function without leaving the current page. In cases like this you should use AJAX. My simplification: Using AJAX you can open the php file in the background, run the function and once its done you can run javascript to inform a user the operation was successful.
To achieve this you would need to add the AJAX call like this:
if(confirm('Do you want delete this?')){
$.ajax({
url: "deleteGame.php",
method: "POST",
data: { id: $(".deleteButtton").data("id")},
success: function (result) {
alert("The operation was successful")
}
});
}
And in your deleteGame.php file you would need to listen to incoming data:
$id = $_POST['id'];
//Your own script to delete the record. You can access the record id by $id
I have the following program in which a user can enter any name in a search box after which I redirect the user to a page called usernameSearchResults.php where I print a list of the usernames obtained in the form of an array from usernamesearch.php. Here is the javascript:
$(window).on('load', function() {
$(".searchBarForm").submit(function(e){
e.preventDefault();
var search=document.getElementsByClassName("search")[0].value;
$.ajax
({
type: 'POST',
url: 'usernamesearch.php',
data:
{
search:search
},
success: function (response)
{
window.location.href="usernameSearchResults.php";
response = JSON.parse(response);
var array_length = Object.keys(response).length;//getting array length
for(var i=0;i<array_length;i++){
if(i==0){
document.getElementById("searchResults").innerHTML=""+response[0].username+"<br>";//i=0
}else{
document.getElementById("searchResults").innerHTML+=""+response[i].username+"<br>";
}
}
window.stop();//stops page from refreshing any further(put here to fix a bug that was occuring)
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
})
});
This is usernameSearchResults.php(inside tags):
<h1>Username Search Results</h1>
<p id="searchResults"></p>
But the problem is that whenever I go to any other page say index.php and enter the username to be searched, the page redirected to is indeed usernameSearchResults.php but the page is blank and error in the console shown says document.getElementById("searchResults") is null.But if I stay at the page usernameSearchResults.php and refresh it and then search any name again, then the results are correctly obtained. What is the problem here?
I would say that the user is being redirected to usernameSearchResults.php but the JavaScript code is still being executed from the current page, which have no element with id "searchResults" defined.
As #Kashkain said, one way to achieve what you want is to pass your response variable in your redirection url and process it then into your other page.
I think the problem here is that the new document could very well still not have been loaded when you call getElementById.
You could add a listener on your target element which would trigger on the load event. In this event's handler you could execute the operations that are now giving you an error.
I have never done or tried this, but maybe something like this would work:
$('#searchResults').on('load', function() {
//execute code here
});
Or you could add a form to the page with action="target_url" method="post" and send your response data through post by doing form.submit, and place the problematic code into usernameSearchResults.php, which will need to read data from POST - this way you can send your ajax data to the new page
I’m creating a Javascript game and I’m currently trying to write some code that will show the player’s “Gold Balance” in real time on a html webpage.
The Gold amount is contained in my SQL database, so I’m using setInterval with a Javascript function that contains an AJAX call which calls a PHP script that grabs the current balance amount for the player and sends it back as “response”.
I’m able to have this amount appear as a Javascript alert, however I need to have the response appear as text on the webpage inside a <div> instead.
This is my current code:
<script>
setInterval("checkGold()",5000);
function checkGold()
{
$.ajax({
url: 'scripts/checkGold.php',
data: "",
dataType: 'json',
success: function(response){
alert(response);
}});
};
</script>
I have this in my html source code, I would like to place the function in a separate file and call it from there, but when I tried this I wasn't able to send the response back to the html page correctly.
I was wondering if anyone knows how to have this response appear as text on the page inside <div> </div>?
Also, I was wondering if this method will really update the div in real time (ie, will it auto-refresh the div part of the webpage, showing an up to date value (every 5000 milliseconds)?
Thanks in advance!
Since you are using jQuery, you can use text() to alter the contents of an existing div (which id is "yourDiv"):
setInterval("checkGold()",5000);
function checkGold()
{
$.ajax({
url: 'scripts/checkGold.php',
data: "",
dataType: 'json',
success: function(response){
$('div#yourDiv').text(response);
}
});
};
You have two questions here, so I will try to address both
1) How to append to the DOM using jQuery, instead of an alert:
in the success callback function, instead of alerting the response, you can simply call
$('body').append("<div>"+response+"</div>")
2) "Real time" Gold Balance
You should use websockets. Racthet is a good websocket PHP library to help you with this: http://socketo.me/
i have a search box flight search in my home page (similar to http://www.travelpack.com/)
When you search in http://www.travelpack.com/ you will see a "We are searching for flights that meet your requirements.
Please wait...
" screen i didn't have it and i want a similar screen in my site.
the problem is that when i click search from my home page
i am using javascript to submit the form
document.flight_search.action = 'php/flt-show-availability.php?&s=1&Sort=P';
document.flight_search.method = 'post';
document.flight_search.submit();
how can i create a loading screen similar to that in the travel pack.
in jQuery one would show the screen, and forward after the ajax call (which tells the appilcation to generate a result) is completed, much like that:
$('.search').click(function(event){
event.preventDefault();
$('#loadAnimationWrapper').show();
$.ajax({
cache: false,
async: false,
type: 'GET',
url: '/your/callback/url',
success: function(data) {
// your forwarding code
}
});
});
But in My Opinion, the example page you give has the Problem that the content shown does is not represented in the url, so, for example you can't give the url to somebody else to let him have a see at the results.
So, ajax magic - sure, but be careful.
You could redirect to the result page, hiding the list of results behind a div that contains the loading message. Then you receive the results via javascript (ajax or similar) and build up the list in background.
When the server is finished searching your request finishes and you can hide the div that contains the loading message (for example in the callback function).
well, you can send your form via ajax-request and wait for the answer.
while waiting display the loader.
if the request succeeds you can react differently:
- replace the content
- goto the generated output page
I'm trying to figure out how to use AJAX to create a Twitter-like feed that displays user's posts on the same page immediately after they push the submit button. It would be an infinite-feed site that would have a "more" button at the bottom.
All I'm trying to make is a simple page containing a textarea box with a submit button and to have user submissions appear below the box as they are submitted.
If possible, a walk through or discussion of the script needed to do this would be great.
Thanks so much
All you need is a server-side script with an SQL query that would return newer posts.
have your javascript store a variable of the date or of the last post id (used PHP for clarification):
result = mysql_query("SELECT ID,POST FROM POSTS WHERE DATE>" . $_GET['date']); //or use WHERE ID> $_GET['id']
while(rows[] = mysq_fetch_array(query));
print json_encode(rows);
now you have a server-side script that will return new posts, so all you have to do is write javascript function for the more button:
updatePosts = function () {
$.ajax({
url: 'serversiderUrl?lastId=' + last_id, //last_id is global variable for the id of the last post on the page
success: function(data){
data = JSON.parse(data);
for(i in data){
$('#posts_container').append(data[i].post); //do your appending functions here
last_id = data[i].id;
}
}
}
now for posting new entries create a server-side script of your favorite language that handles new posts:
result = mysql_query("INSERT INTO POSTS VALUES(''," . urldecode($_POST['POST']) . ")");
now for the client side:
submit_post = function(){
$.ajax({
type: 'POST',
url:'yourposturl',
data: "post=" + encodeURIComponent($('#textArea').text()),
success: function(){
updatePosts(); // call the function that update the posts so the new entry is now added to the page
}
});
}
Now bind the functions to the appropriate buttons when the document is fully loaded:
$(document).ready(function (){
$('#moreButtonId').click(updatePosts);
$('#submitButtonId').click(submitPost);
});
There are many ways such as the submit button kept sending it to the database while we'd append text to a container underneath. Or we can update the container underneath to create a container (page) that are similar, after the ajax response is successful then we append the data to the container beneath
$.post(url,function(data){
//Here you can append the data responsed by the ajax request to the container underneath
});
But you have to have a exactly same view with a conatiner (feed container) existing in the currently page