I'm trying to get a online/offline status update for a chatsystem. Currently I'm stuck on how to update a span in real time. I got things working but it keeps adding the value (person which is online) to my span. What I want to achieve is to have a static list of people (those who are inside my database), and next to it a green bullet if they are online.
This is my jQuery script:
function theStatus(type, msg){
$("#status").append(
"<span class='status "+ type +"'>"+ msg +"</span>"
);
}
function getStatus(){
$.ajax({
type: "get",
url: "php/ajax/status_users.php",
async: true,
cache: false,
timeout: 1000,
success: function(data){
theStatus("rt", data);
setTimeout(
getStatus,
1000
);
}
});
};
$(document).ready(function(){
getStatus();
});
All help is welcome!
I don't know what your php script returns now, but I would have it return key - value pairs of username slugs and statuses.
Then you could add the username slug as an ID to each user span and target the correct span to change the status if necessary or to add an additional user if it is not found in the html.
At the moment you are simply appending span's each time your ajax function returns a result instead of checking the existing list against the returned list from the server.
Related
This is my first time attempting filtering and searching the mySQL database. From my research I have found out I need an AJAX call and some PHP query that will help my achieve the filtering I want to achieve.
This is what I want the AJAX search to do:
Have an Apply button. When I click the button I want a URL to get generated and the AJAX call to happen.
Only reload part of the page where the data queried is contented.
So far I have managed to create this:
$("#filteridname").change(function() {
$value=$(this).val();
$.ajax({
type: "get",
url: "{{$myurl}}",
data: {'search':$value},
success: function(data){
$('#data-holder').html(data);
}
});
});
This manages to create the URL one of the filters, but it does not take the other filters into consideration. I also did not manage to create the button. I am guessing you would need a where statement in the PHP to filter the database?
Would anyone be willing to assist me in creating the AJAX call and PHP query for the filters?
In total I have three filters, and when I click a button I want an AJAX call to filter my database with the three filters and return the results without having to reload the whole webpage.
EDIT: Here is my JS AJAX query:
$("#apply").click(function() {
$country=$('#filter-country').val();
$type=$('#filter-type').val();
$year=$('#filter-year').val();
$.ajax({
type: "GET",
url: "{{$launchsitename->site_code}}",
data: {'country':$country, 'type':$type, 'year':$year},
success: function(data) {
$('#data-holder').append(data);
}
});
});
Now I just need to create a PHP query.
you can use propriety called .Append() instead of .html() ,also here you are getting one element value on change , if you want to get the three of them at one button click , you can make it the same way that you got the val of the first one , and just adding it to the request and handle it back in PHP to divide and execute each one or just pass the three of them to your procedure , depends on what you have
$("#filteridname").change(function() {
$value=$(this).val();
$.ajax({
type: "get",
url: "{{$myurl}}",
data: {'search':$value},
success: function(response){
$('#data-holder').append(response);
}
});
});
Read about .append()
I'm having a list with a lot of entries (100+) identified by an (MongoDB-)ID. Each of the entries is in an html-table and has a checkbox. When the user now selects a group, I need to query the server if each of the entries is in the specific group. The query for getting the membership isn't to heavy, but I can't execute it 100+ times, that's too much load.
Currently I have php code for getting the group membership (too long to post) and following javascript code, which is executed whenever the select is changed:
$('checkbox[data-type="group"]').each(function(idx, val) {
// get the ID and set it checked/unchecked
});
My problem is: How can I query performantly the Server once and then check for every ID if the entry is in the selected group?
Your question is a little hard to understand, but I think you should post a JSON list and post that in one query, and handle the iteration server-side, like so:
id_list = {};
$('checkbox[data-type="group"]').each(function(idx, val) {
the_id = //get the id into a variable somehow;
id_list[the_id] = val;
});
$.ajax({
url: "some url",
dataType: "json",
type: "post",
data:id_list
}).done(function(data) {
//using returned data, set each to check/unchecked
//assuming that the returned data had format of id:boolean, and the boolean defines whether it should be checked (e.g. {1: true, 2: false, 3: false} )
$.each(data, function(index,value) {
if (value == true) {
$('checkbox#'+index).attr('checked',true);
} else {
$('checkbox#'+index).attr('checked',false);
}
});
If this doesn't answer your question then please rephrase your question with more detail.
There is one feature on my site: delete without page refresh. The user just presses 'delete' and the browser will send Ajax-request. It will load 'delete' script with id parameter.
All work well. But it is not very good because of referential integrity of the database. For example, It is possible to delete street, where some people are living.
I want to upgrade my script. I want to add a check to delete script and don't let delete data if some 'people' are connected to 'street' table.
jQuery handler of button click:
$('body').on('click', '.deleteStreet', function()
{
var id = $(this).attr('id');
var hideMe = $(this).parent().parent();
var dataString = 'id=' + id;
if(confirm("Are you sure you want to delete street? It is possible some people living there!"))
{
$.ajax({
type: "GET",
url: "/index.pl?mode=streets&action=delete",
data: dataString,
cache: false,
success: function(e)
{
hideMe.hide();
}
});
return false;
}
});
It will call script anyway and now will delete data anyway. I can add some checks to delete script now and it wouldn't delete, but jquery script would work anyway and will hide table row anyway (because request was send ok, without 404, etc)
1) Is it possible to see delete script result and hide or not hide row depending on it? For example, it will return true or false, js script will catch it and show message about deleting or not deleting of data depending on it.
2) This problem caused by structure of my site. There are some switches on index.pl and load appropriate scripts loading depending on query (mode=street then load street.pl, mode=user then load users.pl etc). So it will show all data loaded before delete.pl script and it will be impossible to check script returned true or false.
Any help? :) Thank you!
P.S.: I am very sorry for my awful english.
You can have the result of your ajax call in the first parameter of the success callback. ex:
$.ajax({
type: "POST",
url: "/index.pl?mode=streets&action=delete",
data: dataString,
cache: false,
success: function(e)
{
if(e === '1'){
hideMe.hide();
}
}
});
try to log your result in the console for tests: console.log(e).
For deleting data you should use a POST request ( or DELETE but not supported by all browsers).
I dont know how your datas (streets) looks like but an other way could it be to return all your existing streets in a json object on the delete request result. And refresh all lines.
I have a jquery script that accesses a db and returns a numeric result and writes that result into a table cell. This scripts runs when the page loads but also when the drop down menu is changed. I want to be able to limit only 1 result per table cell.
Right now when page loads it writes the result to the cell and when the drop down menu is changed it just adds the new result to the cell instead of replacing it.
I have search quite a bit trying to figure out how to do this and can not come up with anything. Can someone help me?
Here is the jQuery:
$(document).ready(function(){
$('.typeval').change(function(){
var movement = $(this).val();
var client_id = $(this).parent().siblings().find('.clientval').val();
var class_id = <? echo $class_id; ?>;
$count = $(this).parents('tr').find('label.count');
$.ajax({
type: "POST",
url: "movement_count.php",
data: {movement:movement, client_id:client_id, class_id:class_id},
dataType: "json",
async: false,
success:(function(output) {
$.each(output, function(index, value){
//alert(value);
$count.append(output[index]);
}); // each
})
}) // ajax
}).change(); // .typeval
}); // document
Here is the table cell where I only want to show one result at a time.
<td><label class="count">5</label></td>
Please let me know if I have not provided enough info for the assistance needed.
Use .text() instead of .append():
$count.text(output[index]);
As its name implies, .append() adds the content to the end of the container. Whereas, .text() sets the text displayed in the container, overwriting any existing text.
Actually, .html(), behaves more like .append() than .text() does, but I don't recommend using .html() unless you are actually setting .html(). Since you said the result is numeric, .text() is better.
Try updating your AJAX call to clear the contents before adding new results:
$.ajax({
type: "POST",
url: "movement_count.php",
data: {movement:movement, client_id:client_id, class_id:class_id},
dataType: "json",
async: false,
success:(function(output) {
$.each(output, function(index, value){
//alert(value);
$count.html(''); // Clear current content
$count.append(output[index]); // Append new content
}); // each
})
}) // ajax
I have a page and I ask them zipcode. While they are filling the form right after they finish writing 5 numbers of zipcode, It will check if it is covered from my database and will show a check or cross sign near it and will disable submit.
To summarize.
Will wait for visitor to type 5 digits zip code( If we can check if customer only enters number it will be a plus and great)
It will check if it is covered in database ( I don't ask for php part. Probably we will send it as POST to a php file)
If it exists in database it will show check else it will show cross and will not allow the form to be submitted.
I checked some websites but couldn't find an exact solution.
Thank you
Probably you need have an image tag besides the zip code text box with the src attribute set to an invisible image. Then perform an ajax upon the blur event.
HTML:
<input type="text" id="zip" name="zip"> <img id="imgconf" src="images/blank.png">
Javascript:
$('#zip').blur(function() {
$.ajax({
url: "script.php",
type: "POST",
data: "zip=" + $('#zip').val(),
dataType: "text",
success: function (data){
if (data=="1"){
$('#imgconf').attr("src", "images/correct.png");
} else {
$('#imgconf').attr("src", "images/wrong.png");
}
}
});
});
For the numeric validation, you may use the same PHP script to return another flag besides "1" and display it in another span element that the data entered is not numeric. Just add another key-value pair in the data part, maybe.
You will need to use AJAX. JQuery has a built in AJAX function. On each keyup event, you can have it run this AJAX function. The PHP should return a value of either 1 or 0 to make it easy. 1 obviously is match, and 0 is no-match.
$('#YourObjectID').keyup(function (event) {
searchZips();
})
function searchZips()
{
var myJSON = $.ajax({
url: options.script + '?Q=' + curValue,
type: 'POST',
contentType: 'application/json',
success: function (msg) {
if(msg==="1"){
// CODE TO SHOW YOUR X DIV
}
}
}
You will want to also add functionality on clearing the search, checking if null or empty string, etc., etc., but this is the basics that should get you going. I use this all the time. Once you get the hang of it, it's VERY useful. Then look into building a jQuery plugin. Once you can do the above functionality, you can build it into a plugin (with tons of cool options!) GOOD LUCK and happy programming.