I just was wondering what you guys could recommend / suggest for an approach I am trying to take. I am trying to make my own simple Live Support chat system and need to make a feature for the Client to view when the Agent is typing a message. I've figured out how to do it for the person typing themselves but not for a remote person.
Please help as I am not very great at jQuery! Heres my current code that simply shows when you are typing in a input field with id of #chatMessage. Please note, this is a PHP, MySQL & jQuery chat system.
$('#chatMessage').keyup(function(){
if ($("#chatMessage").val() == ''){
$('#typing').html('');
}else{
$('#typing').html('The agent is typing a message..');
}
});
Thanks
You only need to add an ajax call to the server and then a timer on the client that checks for agent status...
// Agent side..
function checkStatus(){
jQuery.get('/server-url?agent_id=32&status', function(data){
if (data.status == 'typing')
$('#typing').html('The user/client is typing a message..');
else
$('#typing').html('');
checkStatus();
});
}
// Start the function begining.
setTimeout(checkStatus, 300);
var agent_timer;
$('#chatMessage').keyup(function(){
if (agent_timer)
clearTimeout(agent_timer);
if ($("#chatMessage").val() == ''){
status = 'empty';
} else {
status = 'writing';
}
agent_timer = setTimeout(function(){
// Send status to server php script
$.post('/server-url?agent_id=23', {status: status}, function(data){
// handle response
});
}, 400);
});
// Server side...
// check for agent, and other things...
if (isset($_GET['agent_id'])){
// Agent server side
if (isset($_POST['status']){
// Save status to database
$this->save(array('agent' => $agent, 'chat_id' => $chat_id, 'status' => $_POST['status']));
}
if (isset($_GET['status'])){
$data = $this->read(array('agent_id' => $chat_id));
}
} else {
// This is the client server side
if (isset($_GET['status'])) {
$data = $this->read(array('chat_id' => $chat_id));
return $data['status'];
}
}
// handle other things and return data if necessary
// echo json_encode($data);
// Client side JS
function checkStatus(){
jQuery.get('/server-url?chat_id=32&status', function(data){
if (data.status == 'typing')
$('#typing').html('The agent is typing a message..');
else
$('#typing').html('');
checkStatus();
});
}
// Start the function at begining.
setTimeout(checkStatus, 300);
// We can do the same, so the agent can know if user is typing too (you must also copy the above function)
var client_timer;
$('#chatMessage').keyup(function(){
if (client_timer) clearTimeout(client_timer);
if ($("#chatMessage").val() == ''){
status = 'empty';
} else {
status = 'writing';
}
client_timer = setTimeout(function(){
// Send status to server php script
$.post('/server-url?chat_id=23', {status: status}, function(data){
// handle response
});
}, 400);
});
Maybe there are better ways than updating a row in mysql... but I can't think one now..
Related
I have the following Jquery code that listens to a user typing in a captcha and sends an ajax request on each keyup to see if the correct code has been typed:
$('#joinCaptchaTextBox').keyup(function() {
$.get('scripts/ajax/script.php', {
'join_captcha': '1',
'captcha': $('#joinCaptchaTextBox').val()},
function(data) {
var obj = JSON.parse(data);
if(obj.ajaxResponse.status) {
$('#joinCaptchaNotAcceptable').hide();
$('#joinCaptchaAcceptable').show();
}else{
$('#joinCaptchaAcceptable').hide();
$('#joinCaptchaNotAcceptable').show();
}
});
});
The PHP script on the other end just checks the session and replies:
if($siteCaptcha == $_SESSION['secretword']) {
$this->captchaCompare = TRUE;
}else{
$this->captchaCompare = FALSE;
}
This works fine 95% of the time but I'm finding sometimes it reports the captcha typed is incorrect even though its correct. I think this could be because when typed fast many requests are sent to the server and the order or requests coming back isn't the order sent and therefore (as only one will be correct) a prior one is recieved last and incorrect is displayed.
Is there a better way to do this? Is there a way to ensure the last request sent is recieved last? Is there something I'm missing here. I can give more info.
thankyou
Add a timeout so as to not send a request on every keyup when the user types fast:
$('#joinCaptchaTextBox').on('keyup', function() {
clearTimeout( $(this).data('timer') );
$(this).data('timer',
setTimeout(function() {
var data = {
join_captcha: '1',
captcha : $('#joinCaptchaTextBox').val()
};
$.ajax({
url : 'scripts/ajax/script.php',
data: data,
dataType: 'json'
}).done(function(result) {
$('#joinCaptchaNotAcceptable').toggle(!result.ajaxResponse.status);
$('#joinCaptchaAcceptable').toggle(result.ajaxResponse.status);
});
},500)
);
});
I want to integrate a Java script Slot Machine game into my script.
You can see demo here ; http://odhyan.com/slot/
And also git hub is here ; https://github.com/odhyan/slot you can see all JS files here.
I created a Point Coloumn in User Table that people can play the game with this Point.
I think this JS Function in slot.js checking if user won the game or lose.
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
res = "You Win!";
} else {
res = "You Lose";
}
$('#result').html(res);
}
So i want to add +100 Point if user won the bet.
I made this PHP codes Uptading points For userid "1".
<?php
mysql_connect ("localhost","username","password") or die (mysql_error());
mysql_select_db('slot_machine');
$pointsql = mysql_query("SELECT * FROM user WHERE userid = 1");
while ($row = mysql_fetch_array($pointsql))
{
$row['point'] +=100;
$addpoint = mysql_query("UPDATE user SET point = '{$row['point']}' WHERE userid = 1");
}
?>
So how can i call or excute this PHP Codes in JavaScript function if user Win?
You'll need to trigger a network request from your javascript code to execute your php script server side. Using jQuery's $.ajax() function is an extremely common way to do this abstracting away various browser differences.
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
res = "You Win!";
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.ajax( "path/to/your.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });
} else {
res = "You Lose";
}
$('#result').html(res);
}
You can use jQuery's $.post() function to trigger an asynchronous request to your PHP file.
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
res = "You Win!";
// Here's the line you need.
$.post('score.php', {userid: 1}, function(data) {
alert("Score saved.");
});
} else {
res = "You Lose";
}
$('#result').html(res);
}
This will send POST data to score.php, or whichever file you want to send the data to. The PHP file can then access the userid sent to it by checking the value of $_POST['userid'].
As mentioned in the documentation, $.post() is a shortcut for jQuery's $.ajax() function that is simplified and has some of its options pre-set. The third argument in $.post() is a callback function, and the variable data will contain whatever is echoed out or printed from score.php by the time it's done executing. So, you could use alert(data) instead, to see what score.php printed out. This is useful for troubleshooting and error handling.
try this
$(document).ready(function(){
setInterval(function() {
$.get("databaseUpdated.php");//or what ever your php file name is with corrct path
return false;
}, 1000);
});
hope this will help you use it in your function
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
// if
setInterval(function() {
$.get("databaseUpdated.php");//or what ever your php file name is with corrct path
return false;
}, 1000);
} else {
res = "You Lose";
}
$('#result').html(res);
}
I have to process a Simple log-in File. In Many Web Tutorials I have read that for any Ajax requests in jquery the callback function is function(data) and the data is returned by the server side script.
Well, my server side script is PHP. I wish to know how can I return data from PHP which will be stored in jquery's data and I can use conditional loops to process them.
Here is my jquery Code:
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.post('login.php', querystring, processLI );
function processLI(data) {
if (data == 'success'){
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
}
else
alert ('Login Failed');
}
I am using simple return statement in my php file, which does not seem to work at all. here is the login.php file. I just posted the part necessary here.
$statement = $connection->prepare("SELECT * FROM users WHERE username = '$username'");
$statement->execute(array());
$result = $statement->fetch(PDO::FETCH_ASSOC);
if ($result['password'] == $safepass) {
setcookie("Login", true);
echo 'success';
}
else
echo "Failure";
Try doing it like this, by placing the function as the parameter, and not by calling the function.
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.post('login.php', querystring, function(data){
if (data == 'success') {
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
}
else
alert ('Login Failed');
});
Use the echo statement to output data, if the login is successful echo 'success';
This is an answer about how to debug AJAX requests. First, use Chrome (or Safari, or Firefox with Firebug plugin installed), then open up the developer tools from the settings menu. In the network panel, you can see the request/response. It may not be a direct answer, but please - try to use the Chrome developer tools with the "Net Panel" to see request/response/cookies/headers.
This will save you the trouble of having to guess, it will show you the response verbatim. Then you can solve it next time ;) and the time after
Have you been able to see the request/response? If not, I suggest a simple
alert(JSON.stringify(data))
...from your callback function if you have issues using the Chrome debugger.
Try giving the dataType for post as 'html'
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.ajax({
url : 'login.php?'+querystring,
cache : false,
success : function(data) {
if(data == "success") {
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
} else if(data == "failure") {
alert("Login Failed");
}
};
});
});
I'm new to JSON and AJAX, and as such have searched for solutions and experimented for a few days before resorting to asking here.
I am using AJAX to process a PHP page on submit. It is saving the information fine, but I also need the PHP page to pass back the inserted ID. Here is what I have so far.
In the success:
success: function(){
$('#popup_name img').remove();
$('#popup_name').html('Saved');
$('#fade , .popup_block').delay(2000).fadeOut(function() {
$('#fade, a.close').remove(); //fade them both out
$.getJSON(pathName, function(json){
alert('You are here');
alert("Json ID: " + json.id);
});
});
}
Then, the PHP script calls this method to insert the info and return the inserted id:
public static function doInsertQuery($sparamQuery="",$bparamAutoIncrement=true,$sparamDb="",$sparamTable=""){
//do the insert
$iReturn = 0;
$result = DbUtil::doQuery($sparamQuery);
if(!$result){
$iReturn = 0;
}
elseif(!$bparamAutoIncrement){
$iReturn = DbUtil::getInsertedId();
}
else{
$iReturn = DbUtil::getInsertedId();
}
//log the insert action
//if not a client logged in- cannot log to client db
if(Session::get_CurrentClientId() > 0){
if($sparamTable != LogLogin::table_LOGLOGINS()){
$oLog = new LogDbRequest();
$oLog->set_Type(LogDbRequest::enumTypeInsert);
$oLog->set_Request($sparamQuery);
$oLog->set_RowId($iReturn);
$oLog->set_TableName($sparamTable);
$oLog->set_Before("NULL");
$oLog->set_After(serialize(DbUtil::getRowCurrentValue($sparamDb,$sparamTable)));
$oLog->insertorupdate_LogDbRequest();
}
}
echo json_encode($iReturn);
return $iReturn;
}
I hope this makes sense. I'm at a complete loss here. Any help at all would be greatly appreciated!
~Mike~
It's simple really. The success function accepts an argument corresponding to the response from the server.
Client side:
$.ajax({
'url':'/path/to/script.php',
'dataType':'json',
'success':function(response){ //note the response argument
alert(response.id); //will alert the id
}
});
Server side:
<?php
//...previous stuff here...
$response = array('id' => $id); //where $id is the id to return to the client
header('Content-type: application/json'); //Set the right content-type header
echo json_encode($response); //Output array as JSON
?>
I was wondering if it's possible to long poll using $.getJSON and what the proper front and back end logic would be.
I've come up with this so far but haven't tested it yet since I'm pretty sure there is wrong and/or missing logic.
Here is the JS:
function lpOnComplete(data) {
console.log(data);
if (!data.success) {
lpStart();
}
else {
alert("Works!");
}
};
function lpStart() {
$.getJSON("http://path.to.my.URL.php?jsoncall=?", function(data) {
// What happens when no data is returned
// This is more than likely since there
// is no fall back in the PHP.
lpOnComplete(data);
});
};
PHP:
$time = time();
while((time() - $time) < 30) {
// only returns data when it's new.
$data = checkCode();
// What would be the proper way to break out
// and send back $data['success'] = false
// so the JS loop can continue?
if(!empty($data)) {
echo $_GET["jsoncall"] . "(" . json_encode($data) . ")";
break;
}
usleep(25000);
}
From what you've got there, the Javascript is going to make multiple requests to the server and each one is going to spin up that infinite loop, and never go anywhere. I'd suggest something like: js:
$.getJSON("http://my.site/startAsyncWork.php", null, function(data){
waitUntilServerDone(data.token, function(response){
alert("done");
});
});
function waitUntilServerDone(token, doneCallback){
$.getJSON("http://my.site/checkIfWorkIsDone.php", {"token": token}, function(response){
if(response.isDone){
doneCallback(response);
}
else{
setTimeout(function(){
waitUntilServerDone(token, doneCallback);
}, 1000);
}
});
}
I don't know php, so I'm not going to write sample code for that side, but basically, startAsycWork.php makes up a random token that associates to the request. Then it spawns a thread that does all the work needed, and returns the token back to the response.
When the worker thread is done, it writes the results of the work out to a file like token.dat (or puts it in a cache or whatever).
checkIfWorkIsDone.php checks for the existence of token.dat, and returns false if it doesn't exist, or returns the contents if it does.