I try to get information with ajax from my php class but it doesn't work.
PHP Static class:
static public function showOnlineUsers() {
$db = Db::getInstance();
$time = time() + (24 * 60 * 60);
$sql = 'SELECT * `'._DB_PREFIX_.'prestaChat_users` WHERE `lastActivity`="1333333092"';
$users = $db->ExecuteS($sql);
$count = count($users);
throw new Exception($users);
}
Ajax php file:
require "prestaChat.php";
$type = strtolower($_POST['type']);
$array = array('getusers', 'getmessages');
if(in_array($type, $array)) {
// switch($type) {
// case 'getusers': prestaChat::showOnlineUsers();
// break;
// }
try {
prestaChat::showOnlineUsers();
} catch (Exception $exc) {
print_r($exc->getMessage());
}
}
jQuery $.ajax query:
$.ajax({
type: 'POST',
url: 'modules/prestaChat/ajax.php',
data: {'type': 'getusers'},
success: function(asd) {
console.log(asd);
}
});
So where is the false? I'm newbie in object-oriented php and last ajax thing which I create with jquery (ajax) and oop php works fine, but it send information doesn't get it...
I recently had issues using ajax and couldn't find the false for awhile. I don't know if the same reason I was getting mine, is why you are getting yours but I had my handler php file/script in the same directory as my javascript file calling the handler so I put my url as 'handler.php' but that was actually wrong. Even though they were in the same folder, the main script evoking those scripts was not in the js folder so I needed to change my url to 'js/handler.php' and it worked.
Like I said, I dunno if this is the case from what you presented, but the hierarchy is worth looking at.
Related
I've got a problem that I'm stuck on for days now...
I'm trying to use a simple ajaxPOST function to send data to a MySQL database (not WP database).
This code is located within "single-post.php" in the theme, because it must be checked before every post.
$.ajax({ url: 'library/functions/admin_checkuser.php',
data: {action: userID},
type: 'post',
success: function(output) {
alert(output);
}
});
I'm simply sending a variable to a "admin_checkuser.php" script which in turn calls another script that take actions on the database.
This is the code for "admin_checkuser":
$userid = $_POST['action'];
echo $userid;//for testing
$oMySQL = new MySQL();
$query = "Select * FROM videotable WHERE uid = '$userid'";
$oMySQL->ExecuteSQL($query);
$bb = $oMySQL->iRecords;
$aa = $oMySQL->aResult;
echo $bb;
if ($bb == 0){
$query = "INSERT INTO videotable VALUES ('','$userid','true')";
$oMySQL->ExecuteSQL($query);
echo 'true';
exit();
}else{
$sharing = mysql_result($aa,0,"share");
echo $sharing;
exit();
}
But I don't think the calls go through to the script.
These scripts where tested outside of WordPress and did work, so it must be something in WordPress that blocking the ajax call.
BTW, I tried placing the "admin_checkuser.php" in many diffrent folders but nothing worked.
Thanks in advance.
You're much better off using the inbuilt Wordpress AJAX request.
So in your themes functions.php file, add your function to be called, for example:
function checkUser() {
$userid = $_POST['user']; //validation also :)
$oMySQL = new MySQL();
$query = "Select * FROM videotable WHERE uid = '$userid'";
$oMySQL->ExecuteSQL($query);
$bb = $oMySQL->iRecords;
$aa = $oMySQL->aResult;
echo $bb;
if ($bb == 0){
$query = "INSERT INTO videotable VALUES ('','$userid','true')";
$oMySQL->ExecuteSQL($query);
echo 'true';
exit();
} else {
$sharing = mysql_result($aa,0,"share");
echo $sharing;
exit();
}
}
After that, you add your hook with connects to the inbuilt AJAX System
add_action('wp_ajax_check_user', 'checkUser');
add_action('wp_ajax_nopriv_check_user', 'checkUser');
wp_ajax_nopriv_%s allows it to be called from the front end.
And then, in your javascript file, you just fire off your ajax request.
$.post(ajaxurl, { action: 'check_user', user: userId }, function(output) {
alert(output);
});
If ajaxurl is undefined, you will need to create it in your template file, something like this should work, but there are other ways.
add_action('wp_head','ajaxurl');
function ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
Backend of wordpress does the rest.
It takes the action passed in the AJAX request, looks for the corresponding `wp_ajax(_nopriv)_%s hook and then calls the function that is assigned to the hook.
It will also pass in either the $_POST or $_GET depending on the type of AJAX request.
You can read a little more about using AJAX inside of Wordpress.
You should check your url for your ajax call.
Maybe use the full url instead of the relative one.
It could be because of the location of your theme makes the url incorrect. I'm assuming your ajax code is in your theme folder.
There are some wordpress functions that get the theme directory.
For example if you at this page http://yourwebpage/test/ then the ajax call will go here http://yourwebpage/test/library/functions/admin_checkuser.php. This I assume would be the incorrect location.
This is why you need to add the absolute url to your script. And if it is in your theme, you can use this method get_template_directory_uri() to get the template directory.
See here: http://codex.wordpress.org/Function_Reference/get_template_directory_uri
I'm running into trouble accessing global variables when I make an AJAX call to a php function in the MediaWiki framework.
My jQuery AJAX call looks like this:
jQuery.ajax({
url: 'GeneralFunctions.php',
type: 'GET',
dataType: 'json',
data: {
text: anchorText
},
success: function (data) {
alert("data: " + data);
}
});
My GeneralFunctions.php file looks like this:
<?php
if (isset($_GET['text'])) {
jsonInlineParse((string) $_GET['text']);
}
function jsonInlineParse($wikiText)
{
global $wgOut;
$return = $wgOut->parseInline($wikiText); //fails here
echo json_encode($return);
}
?>
When I run the jQuery call through a click event I get as far as the parseInline() function. The global variable is never defined in the scope and I get the error:
Fatal error: Call to a member function parseInline() on a non-object in /path/to/file/GeneralFunctions.php on line 54
I'm not sure how to make the parse call and define the global variable when the AJAX call is made?
UPDATE
$wgOut is the OutputPage object associated with MediaWiki. It holds all the HTML of the page and is used throughout the MediaWiki framework to add content to a page or article. It is used on the server side to create customized output for wiki articles. I use it to create forms or add HTML on many of our wikis.
More info here: http://www.mediawiki.org/wiki/Manual:$wgOut
UPDATE 2
#Juhana I changed my function to look like this which results in the same error as before. Each echo outputs "NULL".
<?php
function jsonInlineParse($wikiText)
{
include_once '/path/to/file/includes/OutputPage.php';
include_once '/path/to/file/includes/parser/Parser.php';
echo var_dump($wgOut);
global $wgOut;
echo var_dump($wgOut);
$return = $wgOut->parseInline($wikiText);
echo $return;
echo json_encode($return);
}
?>
I took a different approach after running into global variable problems. I changed the AJAX call I was making and the code below works very well for me. I'm using the editable jquery table you can find here.
PHP
function ajax_parse(){
global $wgRequest;
if($wgRequest->wasPosted()){
$text = $wgRequest->getVal("text");
wfDebug("Recieving::::".$text);
if(!strpos($text, "href")){
$text = myInlineParse($text);
$text = str_replace("<pre>", "", $text);
$text = str_replace("</pre>", "", $text);
}
wfDebug("Returning::::".$text);
echo $text;
}
exit;
}
function myInlineParse( $wikiText ) {
global $wgOut;
return $wgOut->parseInline( $wikiText );
}
JavaScript
// inject wikitext after hitting save
function postSave(o) {
var response = new Array("");
for(var i=0;i<o.row.length;i++){
new Ajax.Request(wgScript +'/Special:EditClass/ajax_parse',
{
asynchronous: false,
parameters: {'text': o.row[i].innerHTML},
onSuccess: function(text){
response.push(text.responseText);
}
}
);
}
return response;
}
For whatever reasons, extensions don't seem to have access to $wgOut. I solved this for my extension by using the hook: OutputPageParserOutput for the code I needed output (I needed to inject some scripts and stylesheets as well as using another hook to modify links and didn't want to bother with Resource_Loader though it is useful and recommended):
$wgHooks['OutputPageParserOutput'][] = array($this, 'doOutputPageParserOutput'); // 'doOutputPageParserOutput' defined as method in my class
As with other hooks, you can get rid of the array in favor of just a function name if you don't want to execute within a class.
I'm looking for a PHP component for asynchronous data processing.
Basically what I need is to display a page with a progress bar that's refreshed with javascript which displays the progress on some data processing.
On the backend you'll define your data process limit. This is the start, end and function to call for processing individual items.
There are plenty of solutions for this on CMS and frameworks. I'm looking for something in raw PHP that I can include in my application.
I did something similar not too long ago. I wrote a function that logs the progress to a text file as a JSON object. Then I wrote a PHP function that returns that JSON object to the browser at certain intervals as requested by jQuery.
My PHP code looks similar to this:
function logProgress($task, $status, $progress) {
$basedir = "/var/www/" . SITE_ROOT . "/";
$log_file = $basedir . "logs/progress.log";
$logFileContent = file_get_contents($mrp_log_file);
if($logFileContent){
$logFileArray = json_decode($logFileContent, TRUE);
} else {
$logFileArray = array();
}
$logFileArray[$task]=array('task'=>$task,'status'=>$status,'progress'=>$progress);
$logFile = fopen($log_file, 'w+') or error_log("Failed to open progress file $mrp_log_file for writing");
fwrite($logFile, json_encode($logFileArray));
fclose($logFile);
}
Retrieving the data is as simple as this:
function readProgressLog() {
//Returns a JSON object stored in the progress log.
$basedir = "/var/www/" . SITE_ROOT . "/";
$log_file = $basedir . "logs/progress.log";
$logFileContents = file_get_contents($log_file);
return $logFileContents;
}
From jQuery, you would make two AJAX calls, one to initiate your process, and one to poll the text file. My javascript for the polling call looks like this:
function updateProgress() {
var data = {
action:'getProgressUpdate'};
var settings = {success: function(json){
var done = false;
if(json!=null) {
//Put your code to update the progress bar here.
//I look for a JSON property called Done to flag the process as completed.
if(json.Done==null) {
var t2 = setTimeout("updateProgress()", 1000);
} else {
clearTimeout(t2);
done = true;
clearProgressLog();
}
} else {
var t2 = setTimeout("updateProgress()", 1000);
}
},
data:data,
cache:false,
type: 'POST',
dataType:"json"};
$.ajax('/ajax/polling.ajax.php', settings);
}
One thing I noticed is that you should make sure your polling AJAX call uses a different PHP file than your process AJAX call, otherwise your polling call won't finish until the process call is finished.
I have a directory tree structure. Each time I click a folder, jQuery.ajax fires and opens a jquery.php file.
This is my javascript code that triggers the jQuery.ajax:
jQuery('.directory').live('click',function() {
// Get dir name clicked
var dir = jQuery(this).find('span').html();
// Update dir list
getHTML('getDirList',dir, function(html){
jQuery('#fileDirList').html(html);
});
// Update file list
getHTML('getRowList',dir, function(html){
jQuery('#fileList').html(html);
});
});
function getHTML(instance, dir, callback) {
jQuery.ajax({
type: "POST",
url: "../wp-content/plugins/wp-filebrowser/jquery.php",
dataType: 'html',
data: {instance: instance, dir: dir},
success: function(html){
callback(html);
},
error: function(e) {
callback('[Error] ' + e);
}
});
}
In this file I have the following code in my jQuery.php file:
<?php
class jQueryFactory {
/**
* Get and output directory list
*/
public function getDirList() {
echo parent::getDirList();
}
/**
* Get images and list them in row format
*/
public function getRowList() {
echo parent::getRowList();
}
/**
* Create new directory
*/
function createDir() {
if(isset($_POST['new_dir'])) {
$result = parent::createDir($_POST['new_dir']);
echo $result;
}
}
/**
* Delete file
*/
function deleteFile() {
if(isset($_POST['file'])) {
$file = $_POST['file'];
parent::deleteImage($file);
}
}
}
// Does this work?
if(!isset($factory))
$factory = new jQueryFactory();
switch($_POST['instance']) {
case 'deleteImage' : $factory->deleteFile(); break;
case 'createDir' : $factory->createDir(); break;
case 'getDirList' : $factory->getDirList($dir); break;
case 'getRowList' : $factory->getRowList($dir); break;
}
?>
My question is: Do I have to fire this function each time I click?
Or can I fire once and then just call the various functions within the same user session?
Every Ajax request you make is going to result in a new request on server side.
It is normal in PHP to initialize classes and configuration variables on every request, so the way you show is fine and trying to persist the jQueryFactory object across requests is not an idea worth pursuing. It shouldn't be much of a performance problem either.
If the process really needs speeding up, look into things like opcode caching.
can you store $factory in a $_SESSION variable?
maybe something like this? (untested, and i'm not familiar with jQueryFactory)
session_start();
$factory = isset($_SESSION["factory"]) ? $_SESSION["factory"] : makeNewFactory();
function makeNewFactory() {
$fact = new jQueryFactory();
$_SESSION["factory"] = $fact;
return $fact;
}
I am developing one website using cakephp and jquery technologies.
Server-side there are some functions which handles SQL queries.
As per requirement I want to modify server side functions on client side using jQuery AJAX call.
E.g. : Below is the function on server side to modify users information.
function modifyUser(username,userid) {
//update query statements
}
Then jquery AJAX call will be like this:
$.ajax({
url: 'users/modiyUser',
success: function() {
alert("Updation done") or any statements.
}
});
and I want to modify above i.e. server side function depending upon client input criteria.
$.ajax({
function users/modiyUser(username,userid) {
// I will write here any other statements which gives me some other output.
}
});
Above AJAX call syntax may not present, but i think you all understood what I am trying to do I simply wants to modify/override server side functions on client side.
Please let me know is there any way to resolve above mentioned requirement.
Thanks in advance
You cannot call a PHP functions from the client directly. You can only make an HTTP request to a URI.
The URI determines the PHP script run. Input can be taken via $_GET, $_POST, and $_COOKIE (among others, but those are the main ones).
You can either write separate scripts for each function or determine what to do based on the user input.
You could have a server-side function in a separate PHP file to do this, and make an AJAX call call into that function first to perform the modification. But client-side changes to server-side code are just not possible.
I can't actually imagine why you would want to do this, though.
why override a function???
can i suggest this?
in PHP
try {
// functions here....
function modifyUser($username,$userid) {
//update query statements
if(!is_string($username)) throw new Exception("argument to " . __METHOD__ . " must be a string");
if(!is_string($userid)) throw new Exception("argument to " . __METHOD__ . " must be a string");
// do some modification codes....
}
function delete($userid){
// do stuff blah blahh...
}
// $_POST or $_GET etc. here
if(isset($_GET["modify"])){ // I make use of get for simplicity sake...
$username = $_GET['username'];
$userid = $_GET['userid'];
modifyUser($username,$userid);
$ret = array();
$ret["error"] = false;
$ret["msg"] = "$username has been modified";
echo json_encode($ret);
} else if(isset($_GET["delete"])) {
$userid = $_GET['userid'];
delete($userid);
$ret = array();
$ret["error"] = false;
$ret["msg"] = "$username has been deleted";
echo json_encode($ret);
}else {
// the client asked for something we don't support
throw new Exception("not supported operation");
}
}
catch(Exception $e){
// something bad happened
$ret = array();
$ret["error"] = true;
$ret["msg"] = $e->getMessage();
echo json_encode($ret);
}
in jQuery ajax
$.ajax({
url: 'ajax.php',
data : { modify : true, // sample for modify... can also be delete : true,
username : $('#username').val(),
userid : $('#userid').val() },
type: 'GET',
dataType: 'json',
timeout: 1000,
error: function(){
alert('error in connection');
},
success: function(data){
if(data.error)
alert('Something went wrong: ' + data.msg);
else {
alert('Success: ' + data.msg);
}
}
});