I'm building a site which allows users to log on to it, and uses jquery to dynamically update the page to show all users who are currently on.
I want to have a button beside each users name that would let another user select that person (a game match-making service, if you will.)
Currently I'm generating the names with a combination of jquery and php.
Jquery does long polling:
function waitForMsg(){
$.ajax({
url: "tictac_code1.php",
type: 'POST',
data: 'longpoll=1',
async: true, /* If set to non-async, browser shows page as "Loading.."*/
cache: false,
timeout:10000, /* Timeout in ms */
success: function(data){ /* called when request to barge.php completes */
$('#loggedinnames').empty();
$('#loggedinnames').append(data);
setInterval(waitForMsg, 10000);
//setTimeout(
// 'waitForMsg()', /* Request next message */
// 1000 /* ..after 1 seconds */
//);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
//alert("error in waitformsg.");
addmsg("error", textStatus + " (" + errorThrown + ")");
setInterval(waitForMsg, 10000);
//setTimeout(
// 'waitForMsg()', /* Try again after.. */
// "15000"); /* milliseconds (15seconds) */
}
});
};
$(document).ready(function(){
waitForMsg(); /* Start the inital request */
});
PHP does the sql queries and returns data to the jquery to be displayed.
if (isset ($_POST['longpoll'])) {
if (filter_input(INPUT_POST,'longpoll') == '1') {
$name = $_SESSION['name'];
$result = mysql_query("select name from tictac_names where logged_on='1' AND name!='$name'", $db);
$rowCheck = mysql_num_rows($result);
if ($rowCheck > '0') {
while ($row = mysql_fetch_assoc($result)){
foreach ($row as $val){
$spanid = 'sp_' . $val;
$buttonid = 'b_' . $val;
//echo "<br><span id=\"$spanid\">$val</span></br>";
//<input type ="button" id="nameButton" value ="OK"/><br>
echo "<br><span id=\"$spanid\">$val <input type =\"button\" id=\"$buttonid\" value =\"Button!\"/> </span></br>";
//echo "<br><p><span id=\"$spanid\">$val</span>Click here to play a game with this player.</p></br>";
}
}
} // end rowcheck
}
} //////////// end of the LONGPOLL if
So it successfully puts out the name and a button, but the button's ID is not unique. If I want it to be clickable, I'm sure that the ID will have to be unique, but then there will need to be additional jquery to catch the button click.
How can I make this work?
Should I take a different approach, perhaps names with radio buttons, and a single "Match us!" button?
An alternative to #Craig M 's answer would be to use the built in delegate features in jQuery.
$('#loggedinnames').delegate('span','click',function(){
alert($(this).text());
});
It does the same thing but you can use any selector, not just tag name, and you don't need to code all of the boiler plate delegation code.
You could remove the buttons, and use event delegation to figure out which username the person clicked on. Then do what you need to do with it in the click handler.
To do this, set a click handler on #loggedinnames like so:
$('#loggedinnames').click(function(e) {
if ($(e.target).is('span')) { //e.target is the element that was actually clicked.
alert($(e.target).text());
}
});
The advantage of this approach is that you only have one click handler and don't need to bind an event every time the list of logged in users changes.
What I usually do in this situation is to build the button in JavaScript rather than on the server. Then you can just keep a global variable that serves as a counter, increment it each time you add a button, and use that to put together your unique button ID.
I've used this approach in a lot of situations, and 90% of the time, it works every time.
Give all of your buttons the same class and unique ids. Write an event handler in JQuery using live() for your class where you get the id of this and use it in your code. This way the code works for ALL buttons (including new ones) and you do not have to duplicate any code.
$('#loggedinnames .button').live('click', function() {
someMethod($(this).attr('id')); //run your code here
});
Related
I have a page with several buttons whose values and names are retrieved from the database. I'm trying to run an insert query on any button clicked, my code so far:
<?php
$sqlGetIllness = "SELECT * FROM illnissesandconditions ";
$resultGetIllness = $conn->query($sqlGetIllness);
while ($rowGetIllness= mysqli_fetch_array($resultGetIllness)){
echo "<div class='col-md-3'style='margin-top:20px;'><button onclick='insert(".$rowGetIllness['illness'].");' class='button button1' style=' color:white;' value='".$rowGetIllness['illness']."'>".$rowGetIllness['illness']."</button></div>";
}
function insert($value) {
$value='';
$sqlGetId = "SELECT commonID from common group by commonID DESC LIMIT 1 ";
$resultGetId = $conn->query($sqlGetId);
$r=mysqli_fetch_array($resultGetId);
$id=$r['commonID'];
$sqlGetIllness = "INSERT INTO medicalrecords (CommonID,Medical_Condition) VALUES (".$id.",'".$value."')";
$resultGetIllness = $conn->query($sqlGetIllness);
}
The value passed to the function inside onclick is correct when I inspect it in the browser, however nothing happens. I have a database connection on already, what could be wrong? Is it possible to do it like that in php without refreshing the page? Or do I need to use a client side lang like AJAX? Please note that I've never worked in AJAX btw.
New EDIT:
<script>
$("button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
condition: $(this).val(), // < note use of 'this' here
},
success: function(result) {
alert('Condition Inserted!');
},
error: function(result) {
alert('error');
}
});
});
</script>
Solution:
I got it worked out, after writing the script, i retrieved the variable value on top of the page
if (isset($_POST['condition'])) {
$value=$_POST['condition']; }
inside $_SERVER['REQUEST_METHOD'] == 'POST' ) and now it inserts the value when ever any button is clicked, my next step is to give the clicked button a background color
Solution is in the post under Solution, was my first time trying ajax and it did work indeed, gave the button an id, and took its value ( any button clicked ) through this.val and sent via post, retrieved and used the value in a variable for the insert query.
I asked this question but did not explain it thoroughly. I have a regular link:
Click Me
I want the change the href after the link is clicked 10 times not by the individual use but clicked 10 total times by all users.My jquery is obviously flawed but here is what i have:
var count = 0;
$(document).ready(function(){
$('a').click(function(){
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});
I am new to jQuery but from what ive read cookies and local storage store individual users information not the total websites information. So how could i use ajax with a database to do this? maybe even php?
You have a huge fundamental misunderstanding of how JavaScript works.
Firstly, when someone clicks that link, they're going to be navigated away from your page unless you do something to prevent that (e.preventDefault or return false in jQuery). Once they're navigated away, your counter is lost because is stored locally, in memory, for the life of the page.
Secondly, even if the counter wasn't cleared, or you stored the counter in a cookie, or localStorage, it will only count for a single user. If you want to count the clicks by all users, you're going to have to do that server side. i.e., in PHP.
So... how do we do that? Well, as I said before, when a user clicks that link, they're going to be sent to Google. Your site will have no knowledge of what has occurred.
We have two options to deal with this. We can intercept the click, and use AJAX (more appropriately "XHR") to send a request back to your server, where you can log the click, before forwarding them off to Google.
Or, you re-write the URL to something like /log_click.php?forward=http://google.com. Now when the user clicks the link, they will actually be sent to your log_click.php script, where you can log the click to your database, and then use $_GET['forward'] in combination with header('location: ...') to forward them off to their destination. This is the easiest solution. Through some JavaScript hackery, you can hide the link so that when they mouse over it, they won't even know they're being sent to your site (Google does this).
Once you've accumulated your 10 clicks, you again use PHP to write out a different HTML link the next time someone views that page.
HTML
<a href='http://www.google.com' data-ref='99'>Click Me</a>
Javascript
$("a").click(function() {
var _this = $(this);
var ref = $(this).data('ref');
$.ajax({
url: '/click_url.php',
type: 'POST',
data: {id:ref}
success: function(href) {
if(href != '')
_this.attr("href",href);
}
});
}
PHP (click_url.php)
if($_POST['id'] > 0){
$id = $_POST['id'];
//count increment
$sql = "UPDATE table SET count = count + 1 WHERE id = '$id'";
mysql_query($sql);
//get row count
$sql = "SELECT * FROM table WHERE id = '$id' LIMIT 1";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
//if count > 10 , return new url
if($row['count'] > 10){
die($row['href']);
}
}
While clicking the link you can call an ajax request and increment the count in the server. So that u should remove link from href and call manually by using javascript window.location.href each time. Hope that helps
var count = 0;
$(document).ready(function(){
$('a').click(function(e){
e.preventDefault();
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});
and use ajax like below
//send set state request
$.ajax({
type: "POST",
contentType: "text/xml; charset=utf-8",
datatype: "xml",// you can set json and etc
url:"your php file url",
data: {test:test1},// your data which you want to get and post
beforeSend: function (XMLHttpRequest) {
// your action
},
success: function (data, textStatus, XmlHttpRequest) {
// your action },
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
for more deatils see Ajax
Mark's answer is more useful, even you want to implement for the sake of some constraints then try below with jQuery 1.9
I have implemented for 3 clicks, AFAIU you need to change the URL on every 3rd successive click
var c=0;
$(document).on('click', 'a#ten', function(e){
c++;
alert('clicked ' + c + ' times');
if(c%3 == 0) {
$('a').attr("href","https://www.yahoo.com");
alert('changed');
c = 0;
}
e.preventDefault();
})
working DEMO
You must save no of times that link has been clicked in the database with php. when you render the link(with php) check the no of times it has been called before and decide what link to render.
Click Me
write this javascript in the page wher you place your link
$(function()
{
$('.mylink').click(function()
{
$.ajax({
type: "POST",
url: "listening/end/point", // enter your counting url here
async: false
);
});
});
And in server on the listening end point write php script to store no of times that link has been called.
The attached picture shows the results page of the search engine that I'm building. For each return result, the user may click on the result (i.e. "Food Science") and it will expand out accordion-style to reveal information about that particular result.
I want to log each time the user clicks on a result (for learning/intelligence purposes) and store it in a database table that I have created which stores the session ID, the query, the position of the result, and the order in which the user clicked the item.
Using JQuery, I already have a function that will pull the title of the result that was clicked, and I have it set where I want to log the click, but I don't know how to do it since JQuery is client side and PHP is server side.
How can I use the JQuery to trigger a PHP function so that I can query the database to insert the click logs into my table?
Below is the JQuery function.
$(document).ready(function() {
$('.accordionButton').click(function(e) {
if($(this).next().is(':hidden') == true) {
$(this).addClass('on');
$(this).next().slideDown('normal');
$(this).next().slideDown(test_accordion);
// SEND CLICK ACTION TO LOG INTO THE DATABASE
alert($(this).find('h3:last').text()); // displays the title of the result that was just clicked
}
else {
$(this).removeClass('on');
$(this).next().slideUp('normal');
$(this).next().slideUp(test_accordion);
}
});
}
You can do something like this (untested):
Define a javascript variable to track the order of the clicks, outside your click function:
var order = 0;
Add this into your click function, at the bottom:
order++;
var sessionID = $("input[name='sessionID']").val(); // assuming you have sessionID as the value of a hidden input
var query = $("#query").text(); // if 'query' is the id of your searchbox
var pos = $(this).index() + 1; // might have to modify this to get correct index
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order});
In your php script called "logClick.php" (in the same directory):
<?php
// GET AJAX POSTED DATA
$str_sessionID = empty($_POST["sessionID"]) ? '' ; $_POST["sessionID"];
$str_query = empty($_POST["query"]) ? '' ; $_POST["query"];
$int_pos = empty($_POST["pos"]) ? 1 ; (int)$_POST["pos"];
$int_order = empty($_POST["order"]) ? 1 ; (int)$_POST["order"];
// CONNECT TO DATABASE
if ($str_sessionID && $str_query) {
require_once "dbconnect.php"; // include the commands used to connect to your database. Should define a variable $con as the mysql connection
// INSERT INTO MYSQL DATABASE TABLE CALLED 'click_logs'
$sql_query = "INSERT INTO click_logs (sessionID, query, pos, order) VALUES ('$str_sessionID', '$str_query', $int_pos, $int_order)";
$res = mysql_query($sql_query, $con);
if (!$res) die('Could not connect: ' . mysql_error());
else echo "Click was logged.";
}
else echo "No data found to log!";
?>
You can add a callback function as a third parameter for the $.post() ajax method if you want to see if errors occured in the script:
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order},
function(result) {
$('#result').html(result); // display script output into a div with id='result'
// or just alert(result);
})
);
EDIT: If you need the value of the order variable to persist between page loads because you paginated your results, then you can pas the value of this variable between pages using either GET or POST. You can then save the value in a hidden input and easily read it with jQuery. (Or you could also use cookies).
Example (put this in every results page):
<?php
$order = empty($_POST["order"]) ? $_POST["order"] : "0";
$html="<form id='form_session' action='' name='form_session' method='POST'>
<input type='hidden' name='order' value='$order'>
</form>\n";
echo $html;
?>
In your jQuery, just change var order = 0; to
var order = $("input[name='order']").val();
Then, when a user clicks on a page link, prevent the default link action, set the order value and the form action, and then submit the form using javascript/jQuery:
$("a.next_page").click(function(event) {
event.preventDefault();
var url = $(this).attr("href");
$("input[name='order']").val(order);
$("#form_session").attr('action', url).submit();
});
All the 'next' and 'previous' pagination links must be given the same class (namely 'next_page' (in this example).
EDIT: If your pagination is as follows:
<div class='pagination'>
<ul><li><a href='page1.url'>1</a></li>
<li><a href='page2.url'>2</a></li>
</ul>
</div>
then just change this:
$("div.pagination a").click(function(event) {
etc.
This one is pretty easy, you need a PHP-Script to handle AJAX requests which are sent from your Search page.
In your search page you'll need to add an .ajax to create an AJAX request to your Script.
Everything you need to know about AJAX can be found here: http://api.jquery.com/jQuery.ajax/
In your PHP-Script you'll handle the Database action, use GET or POST data to give the script an ID over Ajax.
Use Ajax. Write a simple php-script that writes clickes to the database. I don't know how you log the clicks in the database exactly, but you can send the clicked item unique identifier to a php script with ajax, for example via POST variables.
A little example, on click:
$.post(
'count_click.php',
{ id: "someid" },
function(data) {
// data = everything the php-script prints out
});
Php:
if (isset($_POST['id'])) {
// add a click in the database with this id
}
Send a request to a PHP page using jQuery AJAX. See here for more info (it is really simple):
http://api.jquery.com/jQuery.ajax/
In this particular case, as you do not need to return anything, it may be better to just use the POST or GET methods in jQuery:
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.get/
Something like:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston"
success: function(data){
alert('done');
});
I recently learned that when using onclick, for a button, the field name and button id have to each be unique. While thats not a problem, depending on how many rows my script outputs, this could be a lot of waste.
For example, i have a while loop, it does this for each person on my server (minecraft), so it could be 10, it could be 50.
this is the code to create the js objects
$kickbtn .= " $('#kick_btn$k').click(function(event) {
var player_name$k = jQuery('input[name=\"player$k\"]').val()
jQuery.get('testing.php?action=kick', { player_input: player_name$k} );
alert('Successfully kicked');
});\n\n";
this is the form data
<form name=\"$pdata[name]\" action=\"\">
<input type=\"hidden\" name=\"player$k\" value=\"$pdata[name]\">
<input type=\"submit\" id=\"kick_btn$k\" value=\"Kick Player\">
</form>
$k++;
Is there an easier way to accomplish this without creating all this excess code?
The output is nice in the html, and it does work, just hoping theres something a little more dynamic i can do, and not so messy in the code. Below is from the parsed code and works and looks good.
$('#kick_btn14').click(function(event) {
var player_name14 = jQuery('input[name="player14"]').val()
jQuery.get('testing.php?action=kick', { player_input: player_name14} );
alert('Successfully kicked');
});
Only one delegated event handler is needed, which means attaching it to a parent/container element, unless you want 50+ click handlers in your document which will unnecessarily slow things down:
// bind to all elements starting with 'kick_btn' within #container
// (could even be 'body')
$("#container").delegate('[id^="kick_btn"]', "click", function(event) {
// get the current player number from the id of the clicked button
var num = this.id.replace("kick_btn", "");
var player_name = jQuery('input[name="player' + num + '"]').val();
jQuery.get('testing.php?action=kick', {
player_input: player_name + num
});
alert('Successfully kicked');
});
Reference:
http://api.jquery.com/attribute-starts-with-selector/
http://api.jquery.com/delegate/
How would I fill in the boxes of my form if I select one of the values from the dropdown menu (The dropdown is got from the DB) Somehow in my javascript I need to connect to functions as there is to different tables involved with the form fields.
Question
Do I need to set the fields using $field name?
if(document.id('LoadExtension') && document.id('ExtensionResponse')) { // id of select box
var sel = document.id('LoadExtension'); // ser select box as var.
sel.addEvent('change', function(chg) { // add change event to select box.
if(sel.getSelected().get('value') != '') { // on change if selected value is not empty.
new Request.HTML({
url : 'http://domain.co.nz/index.php?extension='+ sel.getSelected().get('value'),
onRequest: function() {
},
onComplete: function(r1, r2, html, js) {
document.id('ExtensionResponse').set('html', html);
}
}).send();
}
});
}
The above code was set up to get from another document in the url: box but I would like to do it in one page.
for your code:
http://www.jsfiddle.net/dimitar/TXHYg/4/
(function() {
// anon closure for scope purposes of local vars.
// cache selectors used repeatedly into local vars.
var sel = document.id('LoadExtension'), resp = document.id('ExtensionResponse');
// if they are in the dom...
if (sel && resp) {
// ... then attach event listener.
sel.addEvent('change', function(event) {
// this == sel.
var value = this.get("value"); // cache getter.
if (value === '') {
return false; // do nothing if not selected/
}
// otherwise, it will run the request
new Request.HTML({
method: "get", // or post.
data: {
extension: value // etc etc, can add more object properties and values
},
url: 'http://domain.co.nz/index.php',
onComplete: function(r1, r2, html, js) {
resp.set('html', html);
}
}).send();
});
} // end if
})(); // end closure.
you should really look at some tutorials and examples and the documentation for Request and Request.HTML/JSON/JSONP
an example, similar to yours that works for jsfiddle through its echo testing service (slightly different data object that simulates the response)
http://www.jsfiddle.net/dimitar/TXHYg/3/
instead of document.id('ExtensionResponse') you can write $('ExtensionResponse')
an if you only update a content of a element you can use the update parameter from Request.HTML.
new Request.HTML({
url : 'http://domain.co.nz/index.php',
data: 'extension='+ sel.getSelected().get('value'),
update: $('ExtensionResponse')
}).send();
#medrod;
That's right about the $(), but using the latest version of mootools + making sure Jess stays library safe, document.id() is a much safer option for compatibility.
you need to build the rest of your form, and populate it, with in the result of the ajax request.
eg: http://domain.co.nz/index.php?extension=
start your first HTML form with only the drop down, then your ajax'd script will build and populate the rest of the form.