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
Related
I was wondering if there is any way to include a php file after an AJAX call and display that included file in my page as response.
For example this is an ajax call:
$('#id').change(function(){
var selected = $(this).val();
$.ajax({
url: "ajax.php",
type: "POST",
data: "select="+selected,
success: function (data) {
$("#here").html(data);
}
});
});
And this is what i tried in php but i got not result displayed on my html:
if(isset($_POST['select'])){
$post= $_POST['select'];
$class = ClassName::find_by_id($post);
$sql = " sp_SQLStoredproc {$class->id} ";
if($class->hasRows($sql)){
include("include.php");
}
}
Is there any way to display my included file in my html?
I tried to change my success response from Ajax $("#here").html(data); to $("#here").load(data); but it returned the whole page.
Any suggestions will help.
UPDATE: Inside the include.php file exist a long html code and some class methods
PS. Please don't mentioned that script is not safe, I know is just an example script.
Thank you in advance
In order to get the success data you need to return the data which you want to be included. And remember php will not work in html except it is action call. You can have php file for this since it has the html support also.
Also you need to remember, before setting the success data to the element it's better to console the value and make sure you are getting the correct data.
if(isset($_POST['select'])){
$post= $_POST['select'];
$class = ClassName::find_by_id($post);
$sql = " sp_SQLStoredproc {$class->id} ";
if($class->hasRows($sql)){
return include("include.php");
}
}
you can set all your "include.php" html in buffers and then you need to echo your content into console.
<?php
if(isset($_POST['select'])){
$post= $_POST['select'];
$class = ClassName::find_by_id($post);
$sql = " sp_SQLStoredproc {$class->id} ";
if($class->hasRows($sql)){
ob_starts();
include("include.php");
$include = ob_get_contents();
echo $include;
}
}
?>
I referred to some examples online and modified functions.php and the front end template to fire an ajax call to fetch some data. But I've hard time understanding on hoe the data is returned from the requested url.
At the end of functions.php, I added,
wp_enqueue_script('jquery');
function myFunction(){
echo "hi";
die();
}
add_action('wp_ajax_myFunction', 'myFunction');
add_action('wp_ajax_nopriv_myFunction', 'myFunction');
In my custom template page, I added,
var datavalue = 'test data string';
jQuery.ajax({
url: "/wp-admin/admin-ajax.php",
method: "GET",
data: { 'datavar' : datavalue }
}).success(function(data) {
console.log("successfully run ajax request..." + data);
}).done(function(){
console.log("I am from done function");
}).fail(function(){
console.log("I am from fail function.");
}).always(function(){
console.log("I am from always function");
});
});
After running it, I get these response.
I am from fail function.
I am from always function
I don't understand how to fetch data from a specific url and display the result in ajax's success function.
I don't even know how the function defined in function.php would be called by this ajax call? How are they related?
Please explain. Also I would like to fire ajax call to query database by passing keyword, how can I do that in wordpress?
Your AJAX function should include an action parameter to tell admin-ajax which function you would like to execute.
url: "/wp-admin/admin-ajax.php",
method: "GET",
data: {
action : 'myFunction'
}
(or, if you are set up for it, then you can include it in your url, as below)
url: "/wp-admin/admin-ajax.php?action=myFunction"
Also, your function in functions.php should be written in PHP:
function myFunction(){
echo 'hello';
die();
}
You have to use a action on ajax like.
jQuery.ajax({
url: "/wp-admin/admin-ajax.php",
method: "GET",
data: {
action : 'myFunction'
'datavar' : datavalue,
}
});
PHP function need to edit.
function myFunction(){
echo 'success calling functions';
wp_die();
}
you are not passing the "action" parameter in "data". Which contains callback function's name. Please check the attached link.
https://www.sitepoint.com/how-to-use-ajax-in-wordpress-a-real-world-example/
In this you've to make a callback functions.
Wordpress dsnt work with the specific url.
But if you still want to use the specific url. Follow the steps:-
1. Make a wordpress template.
2. Add your specific url code there.
3. Make a page in the admin panel and assign the template you've created above.
4. Now the permalink of that page can be used as a specific url in the jQuery ajax.
In addition to above answers, in your function.php, make use of $_REQUEST. The $_REQUEST contains all the data sent via AJAX from the Javascript call. Something like this
function myFunction() {
if ( isset($_REQUEST) ) {
{
global $wpdb;
$keyword = $_REQUEST["keyword"];
if($keyword){
$query = "
SELECT `$keyword`, COUNT($keyword) AS Total
FROM `profileinfo` GROUP BY `$keyword`
";
$result = $wpdb->get_results($query);
$data = array();
foreach($result as $row)
{
$data[] = $row
}
echo json_encode($data);
}
}
}
die();
}
add_action( 'wp_ajax_myFunction', 'myFunction' );
add_action('wp_ajax_nopriv_myFunction', 'myFunction');
I really have never done this before and I am getting frustrated because I'm not sure how it fits together. I have a function that I want to call my php (one php file selects info from a database and the second inserts into the database)... I need to use ajax in the way my site is setup but I don't know how to pass data from and to the php files.
In first .js file:
q1LoadVar();
This is my ajax function in second .js file that I have so far (not working):
//ajax code has been edited here since original post:
function q1LoadVar() {
alert("called"); //works!
$.get( "q1LoadVar1.php", function( data ) {
console.log(data); //nothing happens!
// alert(data); //nothing happens!
}, "json" );
}
And here is the code I have in q1LoadVar1.php that I want to select data back from and be able to populate a text area in my html:
/*works when I type this file path directly into the url;
but the file is not communicating back to the ajax function on the
.js file that is calling it*/
<?php
$config = parse_ini_file('../config.ini');
$link = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
echo '<script type="text/javascript">alert("working from php!");</script>';
$query = "SELECT * FROM Game1_RollarCoaster";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
$newRow[] = $row;
}
$json = json_encode($newRow);
echo $json; //works on php file directly!
/*while ($row = mysqli_fetch_array($result)) {
echo $row[Q1_AnswerChoosen];
}*/
mysqli_free_result($result);
mysqli_close($link);
?>
Can someone help me understand how to make this all work together? Thank you, Kristen
You can retrieve post data from ajax in php with
$_POST['action']
//in your case will return: test
To return data to ajax you need to use echo
If the success: callback function doesnt get called try to remove datatype: 'json'
I also think that you need to echo $newrow instead of $row.
If this still doesnt work you can catch the error with the error: callback function to see what is wrong.
Try to start with a simple request and work from there.
$(document).ready(function() {
$.ajax({
type: "POST",
url: "yourphp.php",
data: {simplestring: "hi"},
success: function(result){
alert(result);
}
});
});
and yourphp.php
<?php
$simplestring = $_POST['simplestring'];
echo $simplestring;
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.
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.