I edited my original text to demostrate my entire set of code for those that weren't understanding my question. All this works perfect when I had my database use MyISAM but when I changed over to InnoDB I now have to account for my foreign key or the mysql_queries won't successfully execute. I have the user_id in a session variable that gets created at the time a user logs in. I would figure I need to relay that number (int) from this session variable and append it to the $_GET so that it can be transferred to the todo.class.php for processing right?
the final get() would perhaps need to look like this ?action=new&user_id=1 (or what ever number the user is)&text=text type by user...
if there is a better way to do this, i'm all ears and ready to learn! ;-)
todo.js
$(document).ready(function(){
$(".todoList").sortable({
axis : 'y',
containment : 'window',
update : function(){
var arr = $(".todoList").sortable('toArray');
arr = $.map(arr,function(val,key){
return val.replace('todo-','');
});
$.get('././process/todo/todo.ajax.php',{action:'rearrange',positions:arr});
},
/* Opera fix: */
stop: function(e,ui) {
ui.item.css({'top':'0','left':'0'});
}
});
var currentTODO;
$("#dialog-confirm").dialog({
resizable: false,
height:130,
modal: true,
autoOpen:false,
buttons: {
'Delete item': function() {
$.get("././process/todo/todo.ajax.php",{"action":"delete","id":currentTODO.data('id')},function(msg){
currentTODO.fadeOut('fast');
})
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
});
$('.todo').live('dblclick',function(){
$(this).find('a.edit').click();
});
$('.todo a').live('click',function(e){
currentTODO = $(this).closest('.todo');
currentTODO.data('id',currentTODO.attr('id').replace('todo-',''));
e.preventDefault();
});
$('.todo a.delete').live('click',function(){
$("#dialog-confirm").dialog('open');
});
$('.todo a.edit').live('click',function(){
var container = currentTODO.find('.text');
if(!currentTODO.data('origText'))
{
currentTODO.data('origText',container.text());
}
else
{
return false;
}
$('<input type="text">').val(container.text()).appendTo(container.empty());
container.append(
'<div class="editTodo">'+
'<a class="saveChanges" href="#">Save</a> or <a class="discardChanges" href="#">Cancel</a>'+
'</div>'
);
});
$('.todo a.discardChanges').live('click',function(){
currentTODO.find('.text')
.text(currentTODO.data('origText'))
.end()
.removeData('origText');
});
$('.todo a.saveChanges').live('click',function(){
var text = currentTODO.find("input[type=text]").val();
$.get("././process/todo/todo.ajax.php",{'action':'edit','id':currentTODO.data('id'),'text':text});
currentTODO.removeData('origText')
.find(".text")
.text(text);
});
var timestamp=0;
$('#addButton-todo').click(function(e){
if((new Date()).getTime() - timestamp<5000) return false;
$.get("././process/todo/todo.ajax.php",{'action':'new','text':'New Todo Item. Doubleclick to Edit.','rand':Math.random()},function(msg){
$(msg).hide().appendTo('.todoList').fadeIn();
});
timestamp = (new Date()).getTime();
e.preventDefault();
});
});
todo.class.php
<?php
class ToDo{
private $data;
public function __construct($par){
if(is_array($par))
$this->data = $par;
}
public function __toString(){
return '
<li id="todo-' . $this->data['id'] . '" class="todo">
<div class="text">' . $this->data['text'] . '</div>
<div class="actions">
Edit
Delete
</div>
</li>';
}
public static function edit($id, $text){
$text = self::esc($text);
if(!$text) throw new Exception("Wrong update text!");
mysql_query("UPDATE `todo` SET `text` = '".$text."' WHERE `id`=".$id );
if(mysql_affected_rows($GLOBALS['link'])!=1)
throw new Exception("Couldn't update item!");
}
public static function delete($id){
mysql_query("DELETE FROM `todo` WHERE `id` = ".$id);
if(mysql_affected_rows($GLOBALS['link'])!=1)
throw new Exception("Couldn't delete item!");
}
public static function rearrange($key_value){
$updateVals = array();
foreach($key_value as $k=>$v)
{
$strVals[] = 'WHEN '.(int)$v.' THEN '.((int)$k+1).PHP_EOL;
}
if(!$strVals) throw new Exception("No data!");
mysql_query("UPDATE `todo` SET `position` = CASE `id`".join($strVals)." ELSE `position` END");
if(mysql_error($GLOBALS['link']))
throw new Exception("Error updating positions!");
}
public static function createNew($uid,$text){
$text = self::esc($text);
if(!$text) throw new Exception("Wrong input data!");
$posResult = mysql_query("SELECT MAX(`position`)+1 FROM `todo`");// WHERE `user_id` = 1");
if(mysql_num_rows($posResult))
list($position) = mysql_fetch_array($posResult);
if(!$position) $position = 1;
mysql_query("INSERT INTO `todo` SET /*`user_id` = {$uid},*/ `text` = '".$text."', `position` = ".$position);
if(mysql_affected_rows($GLOBALS['link'])!=1)
throw new Exception("Error inserting TODO!");
echo (new ToDo(array(
'id' => mysql_insert_id($GLOBALS['link']),
'text' => $text
)));
exit;
}
public static function esc($str){
if(ini_get('magic_quotes_gpc'))
$str = stripslashes($str);
return mysql_real_escape_string(strip_tags($str));
}
}
?>
todo.ajax.php
<?php
require "../../dbc.php";
require "../../resources/classes/todo.class.php";
$id = (int)$_GET['id'];
try{
switch($_GET['action'])
{
case 'delete':
ToDo::delete($id);
break;
case 'rearrange':
ToDo::rearrange($_GET['positions']);
break;
case 'edit':
ToDo::edit($id,$_GET['text']);
break;
case 'new':
ToDo::createNew($_GET['text']);
break;
}
}
catch(Exception $e){
echo $e->getMessage();
die("0");
}
echo "1";
?>
Why do you need the session id on the client side? jQuery is sending a GET request to a PHP script on your server. To your PHP script it looks like any other request. The $_SESSION array will be in place and all the session-related functions will work just fine.
Trusting the client to provide a session id is a really bad idea.
I don't follow your script entirely, but to my knowledge the only way to get the current session ID reliably into JavaScript space is
(... head section of the HTML document ...)
<script type="text/javascript">
php_session_id = "<?php echo session_id(); ?>"
alert("The PHP session ID is "+php_session_id);
</script>
#s2xi I realize you are looking for an answer to a simple question, "How do I get the PHP session id into my javascript?" and Unicron's answer is a foolproof way of doing that.
I think we are just trying to figure out why you need to put the PHP session id in your GET request. Your PHP script will always know the user's session id, you just need to call session_id(). There's no need to put it in your GET request. (Let's ignore the cookies-disabled edge case for now, I think it's clear we have bigger fish to fry)
Other things I'm worried about:
Tying data in your database to the session id doesn't make a whole lot of sense. As soon as that user's session expires, you will never be able to tie that data back to them. Am I missing something here?
You are using GET requests to perform actions and modify data. This is a really bad idea.
Related
I am submitting data to a controller function via AJAX, doing what I need to do with the data, and trying to echo it back out to the ajax function.
The issue I am having, is the controller is dumping out the error message and trying to redirect me to the actual function. Obviously the function doesn't have a view, which results in a blank white screen with the response echoed out in the top left corner.
Here is the ajax:
$('#submit_new_split_promo').on('click',function(e){
e.preventDefault();
var id = $(this).data('id');
$('#d_overlay').show();
form = {};
$.each($('#promo-mail-split-add-'+id).serializeArray(),function(k,v){
form[this.name] = this.value;
});
$.ajax({
url:$('#promo-mail-split-add-'+id).attr('action'),
type:"POST",
dataType: "json",
data: form
}).done(function(result){
var res = JSON.parse(result);
if (res == 'Duplicate') {
$('#ms-promo').css('border','3px solid red');
$('#ms-promo').effect('shake');
$('#dynamodal-unique-title').text('That code has been used. Please enter a new Promo Code.');
$('#dynamodal-unique-title').text('That code has been used. Please enter a new Promo Code.').css('color','red').delay(2000).queue(function(next){
$('#dynamodal-unique-title').text('Create Mail Split Promo');
next();
});
return false;
}
$('#mail_split_promo_'+id).modal('toggle');
if (res == false) {
alert('Mail Split Promo did not save. Please try again.');
} else {
$('#add-promo-to-split-'+id).prop('disabled',true);
$('#promo-view-abled-'+id).hide();
$('#promo-view-disabled-'+id).show();
$('#promo-view-disabled-'+id).prop('disabled',false);
}
}).fail(function(){
}).always(function(){
$('#d_overlay').hide();
});
});
Here is the Controllers code
public function addpromo() {
$this->Authorization->skipAuthorization();
$this->request->allowMethod(['get','post']);
$this->autoRender = false;
$data = $this->request->getData();
$mail_split_id = $data['mail_split_id'];
$code = $data['code'];
$result = false;
$doesExist = $this->Promos->findByCode($code)->toArray();
if ($doesExist) {
$result = 'Duplicate';
}
if ($result !== 'Duplicate') {
$MailSplits = $this->getTableLocator()->get('MailSplits');
$mailSplit = $MailSplits->get($mail_split_id);
$entity = $this->Promos->newEmptyEntity();
foreach ($data as $key => $val) {
$entity->$key = $val;
}
$entity->record_count = $mailSplit->record_count;
$result = $this->Promos->save($entity);
if ($this->get_property($result,'id')) {
$promo_id = $result->id;
$MailSplits = $this->loadModel('MailSplits');
$mentity = $MailSplits->get($mail_split_id);
$mentity->promo_id = $promo_id;
$updated = $MailSplits->save($mentity);
if ($this->get_property($updated,'id')) {
$result = true;
} else {
$result = false;
}
$output = [];
exec(EXEC_PATH.'AddPromoToRecordSplits '.$promo_id,$output);
} else {
$result = false;
}
}
ob_flush();
echo json_encode($result);
exit(0);
}
The URL it is trying to redirect me to is: /promos/addpromo when I really just need to stay on the same page, which would be /mail-jobs/view
Response dumped to browser
A couple of things to note:
I have tried adding the function to the controllers policy, and actually authorizing an initialized entity. This has no effect and does not change the issue I am facing.
Something that is more frustrating, I have essentially the same code (ajax structure and controller structure) for other forms on the page, and they work just fine. The only difference seems to be any form that utilizes ajax that is on the page on render, works just fine. The ajax functions I am having an issue with, all seem to be from the forms rendered in Modals, which are different elements. Every form in a modal / element, gives me this issue and that's really the only pattern I have noticed.
Any help is greatly appreciated, I know it's an odd and vague issue.
Thank you!
Hello guys im trying to create a simple voting for comments like and dislike but i want to do that with jquery Ajax so i don't want to refresh the page when someone like it.
And this is my jquery code
$(document).ready(function(){
$(".vote-btn").click(function() {
var voteId = this.id;
var upOrDown = voteId.split('_');
// alert(upOrDown); = provides --> id,name
// var all = 'voteId:'+upOrDown[0]+ ',upOrDown:' +upOrDown[1];
// alert(all);
$.ajax({
type: "POST",
url: "http://localhost/Dropbox/cipr/index.php/demo",
cache: false,
dataType:'json',
data:{'voteId='+upOrDown[0] + '&upOrDown=' +upOrDown[1],
success: function(response){
try{
if(response=='true'){
var newValue = parseInt($("#"+voteId+'_result').text()) + 1;
$("#"+voteId+'_result').html(newValue);
}else{
alert('Sorry Unable to update..');
}
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
});
});
this is my Controller code Demo.php
<?php
class Demo extends CI_Controller {
function Demo(){
parent::Controller();
$this->load->model('sygjerimet');
}
public function index(){
$voteId= $this->input->post('voteId');
$upOrDown= $this->input->post('upOrDown');
$status ="false";
$updateRecords = 0;
if($upOrDown=='voteup' || true){
$updateRecords = $this->sygjerimet->updateUpVote($voteId);
}else{
$updateRecords = $this->sygjerimet->updateDownVote($voteId);
}
if($updateRecords>0){
$status = "true";
}
echo $status;
}
And this is my model code sygjerimet.php
<?php
Class Sygjerimet extends CI_Model
{
function shtoSygjerimin()
{
$permbajtja = $this->input->post('idea');
$data = array(
'permbajtja' => $permbajtja
);
$this->db->insert('pr_sygjerimet', $data);
}
function updateDownVote($voteId){
$sql = "UPDATE pr_sygjerimet set vote_down = vote_down+1 WHERE ID =?";
$this->db->query($sql, array($voteId));
return $this->db->affected_rows();
}
function updateUpVote($voteId){
$sql = "UPDATE pr_sygjerimet set vote_up = vote_up+1 WHERE ID =?";
$this->db->query($sql, array($voteId));
return $this->db->affected_rows();
}
}
And this is my view Code
<?php
$query = $this->db->query('SELECT * FROM pr_sygjerimet');
foreach ($query->result() as $row)
{
echo "<div class='sygjerimi'>";
echo htmlspecialchars($row->permbajtja);
if(!$log_in):
echo '<br>';
echo ' <button id="'.$row->ID.'_votedown" class="vote-btn"><i class="fa fa-thumbs-down">'.htmlentities($row->vote_down).'</i></button> ';
echo ' <button id="'.$row->ID.'_voteup" class="vote-btn"><i class="fa fa-thumbs-up">'.htmlentities($row->vote_up).'</i></button> ';
endif;
echo "</div>";
}
?>
That's it guys when i cilck vote it executes this code
alert('Error while request..');
If anyone can help that would be Great :) Thanks
Most likely this is the CI CSRF protection; if you use POST, CI automatically checks the CSRF hidden field and since you are building the ajax post yourself, it's not sending the hidden field so it bags on you.
Check the several $config['csrf_*'] lines in your config/config.php file. You can disable (but I don't recommend this). You can also serialize the form in jQuery and send that, and it should work for you, and keep you a bit more protected from CSRF attacks.
Just to rule this in or out, you can disable the 'csrf_protection' and if it works then, you can enable it again and then change your javascript to serialize the form and use that as your data with your ajax post.
try this
$.ajax({
//pull the toke csrf like this
data:{'<?php echo $this->security->get_csrf_token_name();?>':'<?php echo $this->security->get_csrf_hash();?>'},
});
I'm beginning to hate AJax, I'm finding it really difficult to get any kind of useful information back when posting with jQuery.
I have a script that adds or removes some info when a button is clicked. The jquery posts to a file which calls a function in a class. This part works, but I cant get a success message back to manipulate the front end. Here is my code.
The php works but I keep getting the error JSON.parse: unexpected character which I have googled, but my json looks ok?
jQuery
$('.fave').click(function(){
var favId = $(this).attr('data-user-fave');
var params = {};
params['fave_id'] = favId;
params['fav_flag'] = '1';
$.post('index.php?link=my_applications', params, function(data){
var data = $.parseJSON(data);
if(data.message === 'success'){
alert(data.flag);
}
else{
alert("Fail");
}
});
code in file that jQuery posts to
$profile = new profile();
if($_POST['fav_flag'] == '1'){
$js = $profile->fave_user();
echo json_encode($js);
}
function in class profile
function fave_user(){
$query = "SELECT * FROM `favourite` WHERE user_id = '{$_SESSION['loginArr']['user_id']}' AND fave_id = '{$_POST['fave_Id']}'";
$nr = $GLOBALS['DB']->num_rows($query);
if($nr >= 1){
//exists so remove
$query = "DELETE FROM `favourites` WHERE user_id = '{$_SESSION['loginArr']['user_id']}' AND fave_id='{$_POST['fave_Id']}'";
$GLOBALS['DB']->deleteQuery($query);
$return["message"]="success";
$return["flag"]="del";
return $return;
}
else{
//not a fave so add
$query = "INSERT INTO `favourite` (user_id, fave_id) VALUES ('{$_SESSION['loginArr']['user_id']}', '{$_POST['fave_id']}')";
$GLOBALS['DB']->insertQuery($query);
$return["message"]="success";
$return["flag"]="ins";
return $return;
}
}
I would suggest using $.ajax method: it is more advanced.
I need your help guys, I'm building my own web chat for my online radio site. I already have a AJAX PHP Web chat from Tutorialzine. I want to modify it. But i don't know where to start. I want it to integrate with Facebook. I want it instead of asking for username and email, there will be a button that says 'Connect to Facebook'. and the Profile Picture and Name of the user will automatically saved to the database. I really need it. And i want it to be moderated. Thank You! and God bless everyone! :)
ajax.php
<?php
/* Database Configuration. Add your details below */
$dbOptions = array(
'db_host' => 'localhost',
'db_user' => 'root',
'db_pass' => '',
'db_name' => 'chat'
);
/* Database Config End */
error_reporting(E_ALL ^ E_NOTICE);
require "classes/DB.class.php";
require "classes/Chat.class.php";
require "classes/ChatBase.class.php";
require "classes/ChatLine.class.php";
require "classes/ChatUser.class.php";
session_name('webchat');
session_start();
if(get_magic_quotes_gpc()){
// If magic quotes is enabled, strip the extra slashes
array_walk_recursive($_GET,create_function('&$v,$k','$v = stripslashes($v);'));
array_walk_recursive($_POST,create_function('&$v,$k','$v = stripslashes($v);'));
}
try{
// Connecting to the database
DB::init($dbOptions);
$response = array();
// Handling the supported actions:
switch($_GET['action']){
case 'login':
$response = Chat::login($_POST['name'],$_POST['email']);
break;
case 'checkLogged':
$response = Chat::checkLogged();
break;
case 'logout':
$response = Chat::logout();
break;
case 'submitChat':
$response = Chat::submitChat($_POST['chatText']);
break;
case 'getUsers':
$response = Chat::getUsers();
break;
case 'getChats':
$response = Chat::getChats($_GET['lastID']);
break;
default:
throw new Exception('Wrong action');
}
echo json_encode($response);
}
catch(Exception $e){
die(json_encode(array('error' => $e->getMessage())));
}
?>
script.js
$(document).ready(function(){
// Run the init method on document ready:
chat.init();
});
var chat = {
// data holds variables for use in the class:
data : {
lastID : 0,
noActivity : 0
},
// Init binds event listeners and sets up timers:
init : function(){
// Using the defaultText jQuery plugin, included at the bottom:
$('#name').defaultText('Nickname');
$('#email').defaultText('Email (Gravatars are Enabled)');
// Converting the #chatLineHolder div into a jScrollPane,
// and saving the plugin's API in chat.data:
chat.data.jspAPI = $('#chatLineHolder').jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
}).data('jsp');
// We use the working variable to prevent
// multiple form submissions:
var working = false;
// Logging a person in the chat:
$('#loginForm').submit(function(){
if(working) return false;
working = true;
// Using our tzPOST wrapper function
// (defined in the bottom):
$.tzPOST('login',$(this).serialize(),function(r){
working = false;
if(r.error){
chat.displayError(r.error);
}
else chat.login(r.name,r.gravatar);
});
return false;
});
// Submitting a new chat entry:
$('#submitForm').submit(function(){
var text = $('#chatText').val();
if(text.length == 0){
return false;
}
if(working) return false;
working = true;
// Assigning a temporary ID to the chat:
var tempID = 't'+Math.round(Math.random()*1000000),
params = {
id : tempID,
author : chat.data.name,
gravatar : chat.data.gravatar,
text : text.replace(/</g,'<').replace(/>/g,'>')
};
// Using our addChatLine method to add the chat
// to the screen immediately, without waiting for
// the AJAX request to complete:
chat.addChatLine($.extend({},params));
// Using our tzPOST wrapper method to send the chat
// via a POST AJAX request:
$.tzPOST('submitChat',$(this).serialize(),function(r){
working = false;
$('#chatText').val('');
$('div.chat-'+tempID).remove();
params['id'] = r.insertID;
chat.addChatLine($.extend({},params));
});
return false;
});
// Logging the user out:
$('a.logoutButton').live('click',function(){
$('#chatTopBar > span').fadeOut(function(){
$(this).remove();
});
$('#submitForm').fadeOut(function(){
$('#loginForm').fadeIn();
});
$.tzPOST('logout');
return false;
});
// Checking whether the user is already logged (browser refresh)
$.tzGET('checkLogged',function(r){
if(r.logged){
chat.login(r.loggedAs.name,r.loggedAs.gravatar);
}
});
// Self executing timeout functions
(function getChatsTimeoutFunction(){
chat.getChats(getChatsTimeoutFunction);
})();
(function getUsersTimeoutFunction(){
chat.getUsers(getUsersTimeoutFunction);
})();
},
// The login method hides displays the
// user's login data and shows the submit form
login : function(name,gravatar){
chat.data.name = name;
chat.data.gravatar = gravatar;
$('#chatTopBar').html(chat.render('loginTopBar',chat.data));
$('#loginForm').fadeOut(function(){
$('#submitForm').fadeIn();
$('#chatText').focus();
});
},
// The render method generates the HTML markup
// that is needed by the other methods:
render : function(template,params){
var arr = [];
switch(template){
case 'loginTopBar':
arr = [
'<span><img src="',params.gravatar,'" width="23" height="23" />',
'<span class="name">',params.name,
'</span>Logout</span>'];
break;
case 'chatLine':
arr = [
'<div class="chat chat-',params.id,' rounded"><span class="gravatar"><img src="',params.gravatar,
'" width="23" height="23" onload="this.style.visibility=\'visible\'" />','</span><span class="author">',params.author,
':</span><span class="text">',params.text,'</span><span class="time">',params.time,'</span></div>'];
break;
case 'user':
arr = [
'<div class="user" title="',params.name,'"><img src="',
params.gravatar,'" width="30" height="30" onload="this.style.visibility=\'visible\'" /></div>'
];
break;
}
// A single array join is faster than
// multiple concatenations
return arr.join('');
},
// The addChatLine method ads a chat entry to the page
addChatLine : function(params){
// All times are displayed in the user's timezone
var d = new Date();
if(params.time) {
// PHP returns the time in UTC (GMT). We use it to feed the date
// object and later output it in the user's timezone. JavaScript
// internally converts it for us.
d.setUTCHours(params.time.hours,params.time.minutes);
}
params.time = (d.getHours() < 10 ? '0' : '' ) + d.getHours()+':'+
(d.getMinutes() < 10 ? '0':'') + d.getMinutes();
var markup = chat.render('chatLine',params),
exists = $('#chatLineHolder .chat-'+params.id);
if(exists.length){
exists.remove();
}
if(!chat.data.lastID){
// If this is the first chat, remove the
// paragraph saying there aren't any:
$('#chatLineHolder p').remove();
}
// If this isn't a temporary chat:
if(params.id.toString().charAt(0) != 't'){
var previous = $('#chatLineHolder .chat-'+(+params.id - 1));
if(previous.length){
previous.after(markup);
}
else chat.data.jspAPI.getContentPane().append(markup);
}
else chat.data.jspAPI.getContentPane().append(markup);
// As we added new content, we need to
// reinitialise the jScrollPane plugin:
chat.data.jspAPI.reinitialise();
chat.data.jspAPI.scrollToBottom(true);
},
// This method requests the latest chats
// (since lastID), and adds them to the page.
getChats : function(callback){
$.tzGET('getChats',{lastID: chat.data.lastID},function(r){
for(var i=0;i<r.chats.length;i++){
chat.addChatLine(r.chats[i]);
}
if(r.chats.length){
chat.data.noActivity = 0;
chat.data.lastID = r.chats[i-1].id;
}
else{
// If no chats were received, increment
// the noActivity counter.
chat.data.noActivity++;
}
if(!chat.data.lastID){
chat.data.jspAPI.getContentPane().html('<p class="noChats">No chats yet</p>');
}
// Setting a timeout for the next request,
// depending on the chat activity:
var nextRequest = 1000;
// 2 seconds
if(chat.data.noActivity > 3){
nextRequest = 2000;
}
if(chat.data.noActivity > 10){
nextRequest = 5000;
}
// 15 seconds
if(chat.data.noActivity > 20){
nextRequest = 15000;
}
setTimeout(callback,nextRequest);
});
},
// Requesting a list with all the users.
getUsers : function(callback){
$.tzGET('getUsers',function(r){
var users = [];
for(var i=0; i< r.users.length;i++){
if(r.users[i]){
users.push(chat.render('user',r.users[i]));
}
}
var message = '';
if(r.total<1){
message = 'No one is online';
}
else {
message = r.total+' '+(r.total == 1 ? 'person':'people')+' online';
}
users.push('<p class="count">'+message+'</p>');
$('#chatUsers').html(users.join(''));
setTimeout(callback,15000);
});
},
// This method displays an error message on the top of the page:
displayError : function(msg){
var elem = $('<div>',{
id : 'chatErrorMessage',
html : msg
});
elem.click(function(){
$(this).fadeOut(function(){
$(this).remove();
});
});
setTimeout(function(){
elem.click();
},5000);
elem.hide().appendTo('body').slideDown();
}
};
// Custom GET & POST wrappers:
$.tzPOST = function(action,data,callback){
$.post('php/ajax.php?action='+action,data,callback,'json');
}
$.tzGET = function(action,data,callback){
$.get('php/ajax.php?action='+action,data,callback,'json');
}
// A custom jQuery method for placeholder text:
$.fn.defaultText = function(value){
var element = this.eq(0);
element.data('defaultText',value);
element.focus(function(){
if(element.val() == value){
element.val('').removeClass('defaultText');
}
}).blur(function(){
if(element.val() == '' || element.val() == value){
element.addClass('defaultText').val(value);
}
});
return element.blur();
}
If you only want to connect with facebook for the user name and picture then all you need to do is include the Facebook Javascript SDK, and then either use the Login Button plugin or use the Client-Side authentication.
If you want to connect with the Facebook internal chat, then you can use the Chat API which has two authentication methods: Facebook Platform and Username/Password.
If you want the first method (sounds like what you want) then you'll need to authenticate the user, either with the client side flow or the server side flow and ask for the "xmpp_login" permission.
There are php examples in the chat API documentation.
I have a situation where I call Facebook.showPermissionDialog('offline_access'...) then later I make an ajax.post call. The ajax.post call fails if the call to the permission dialog was made prior. But it succeeds when the permission dialog was not called prior. Is anyone aware of some relationship between this dialog and ajax.post?
If you want to check out the problem firsthand, visit my app at http://apps.facebook.com/rails_dev (THIS IS A FACEBOOK APP SO YOU MUST GRANT ACCESS TO YOUR PROFILE).
Here's the code that calls Facebook.showPermissionDialog():
<?php
echo $this->jsInit($config);
if(!$userNamespace->newGame) {
$log->debug('NOT new game, calling turnResume()');
echo 'setVarBalance(' . $this->gamePlayerData['funds'] . ');'."\n";
echo 'turnResume();'."\n";
}
echo $this->drawTrack($this->routeData, $this->trainData);
echo $this->drawCityGoods($this->cityGoodsData);
//$link = 'startSetCity()'; //$config->url->absolute->fb->canvas . '/turn/start-set-city';
echo $this->drawCitiesAjax($this->cityDescData);
$log->debug('view: end start-select-city');
if(!$facebook->api_client->users_hasAppPermission('offline_access', $this->fbUserId)):
?>
var dialog = new Dialog().showMessage('Constant Authorization', 'Rails Across Europe is about to request \'Constant Authorization\' to your account. If you don\'t give us constant authorization, Facebook will eventually cause your game to timeout, thereby losing all game information. By granting this authorization, Facebook will not cause your game to timeout. This is the only reason we need this authorization.');
dialog.onconfirm = function() {
Facebook.showPermissionDialog('offline_access', null, false, null);
}
<?php
endif;
?>[
Here's the FBJS code that calls ajax.post:
switch(state) {
case START_SET_CITY:
//new Dialog().showMessage('test', 'START_SET_CITY');
//console.time('start_set_city');
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
//console.time('ondone');
//new Dialog().showMessage('in ajaxSetCity.ondone');
//new Dialog().showMessage('test', 'city=' + dump(data.city, 3) + '::: train=' + dump(data.train, 3));
drawCityAjax(data.city, data.train);
setVarBalance(data.funds);
ajax.responseType = Ajax.JSON;
ajax.post(baseURL + '/turn/start');
//console.timeEnd('ondone');
};
ajax.post(baseURL + '/turn/start-set-city', param); // <=== THIS IS THE AJAX CALL THAT FAILS
var actionPrompt = document.getElementById('action-prompt');
var innerHtml = '<span><div id="action-text">Build Track: Select a city where track building should begin</div>'+
'<div id="action-end">'+
'<input type="button" value="End Track Building" id="next-phase" onClick="moveTrainAuto();" />'+
'</div></span>';
actionPrompt.setInnerXHTML(innerHtml);
var btn = document.getElementById('next-phase');
btn.addEventListener('click', moveTrainAutoEvent);
state = TRACK_CITY_START;
//console.timeEnd('start_set_city');
// get funds balance from backend and call setVarBalance()
break;
I had the same problem if ajax.requireLogin parameter was true. Since you are already asking for extended permissions you can set it to false. Code below works for me:
Facebook.showPermissionDialog("publish_stream", function(permissions) {
var form_data = form.serialize();
var ajax = new Ajax();
ajax.responseType = Ajax.RAW;
ajax.requireLogin = false;
ajax.ondone = function(data) {
console.log("onerror")
};
ajax.onerror = function() {
console.log("onerror")
};
ajax.post("http://foo.example.com/submit", form_data);
return false;
});