how to call external php file in WordPress using ajax - php

I have a little problem with calling a file in a WordPress plugin using ajax.I have this script:
<script type="text/javascript">
function setVal()
{
var val = jQuery('#custom_text_message').val()
alert('Setting the value to "' + val + '"')
jQuery.post('session.php', {value: val})
alert('Finished setting the value')
}
jQuery(document).ready(function() {
jQuery('#custom_text_message').blur(function() {setVal()});
//setTimeout('setVal()', 3000);
});
</script>
But when this function gets called, it shows an error in the console file not found. I want to know if this is the correct way to use ajax in WordPress. If not, how can I call a file which is in the root folder of site name session.php? I'm pretty new to WordPress.

I have solve my problem on my own.First i have define ajaxurl in my themes function.php like below:
<?php
add_action('wp_head','pluginname_ajaxurl');
function pluginname_ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<? }
?>
And I put the below script on the top of my plugin file.
<script type="text/javascript">
function setVal()
{
var val = jQuery('#custom_text_message').val()
var data = {
action: 'my_action',
value: val,
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
}
jQuery(document).ready(function() {
jQuery('#custom_text_message').blur(function() {setVal()});
//setTimeout('setVal()', 3000);
});
</script>
and here's the field, for which i am trying to do in my plugin.
<textarea name="custom_text_message" id="custom_text_message"></textarea>
and then I put my action which i m calling to my script in function.php.
add_action('wp_ajax_my_action', 'my_action_session');
function my_action_session() {
global $wpdb; // this is how you get access to the database
session_start();
$_SESSION['cus_msg'] = $_POST['value'];
die(); // this is required to return a proper result
}
and then call my session value in to my function.That's all i do and work for me and i hope this will helps someone else.
Note:
The wp_ajax_your_action action is for admin if you need to use it on the front end the action would be wp_ajax_nopriv_your_action.

In WordPress, Ajax requests should be made to http://your-wordpress-site/wp-admin/admin-ajax.php - which can be obtained using admin_url( 'admin-ajax.php' ) - and you should use action parameter to specify which function to call. You can pass the admin-ajax path to your javascript file via localization.
Add to your plugin PHP file after you enqueue your script:
wp_localize_script( 'your-script', 'js_obj', array('ajax_url' => admin_url( 'admin-ajax.php' ) );
In your javascript:
jQuery.post(js_obj.ajax_url, {value: val, action: 'run-my-ajax'})
Function to process the ajax in your plugin PHP file:
function call_my_ajax(){
// do stuff
exit;
}
add_action('wp_ajax_run-my-ajax', 'call_my_ajax');
add_action('wp_ajax_nopriv_run-my-ajax', 'call_my_ajax');
Read more: https://codex.wordpress.org/AJAX_in_Plugins

<script type="text/javascript">
function setVal()
{
jQuery.ajax({url:"<?php bloginfo('url');?>/wp-content/plugins/plugin_folder_name/session.php",success:function(result){alert(result);}}
}
</script>

WordPress works on absolute paths, use a complete URL instead of the relative URL:
jQuery.post('session.php', {value: val})
Use something like:
jQuery.post('<?php bloginfo('url');?>/wp-content/plugins/plugin_folder_name/session.php', {value: val})

Related

how to get result of a function as string with ajax in wordpress

I'm developing a plugin for wordpress and I want to use ajax in it. lets say I have the following function:
function ajax_say_hello(){
return "hello";
}
I want to get the result of ajax_say_hello() as a string with ajax. something like "hello".
to do this, I added the following:
in my plugins function.php >
add_action('wp_ajax_ajax_say_hello', 'ajax_say_hello');
add_action( 'wp_ajax_nopriv_ajax_say_hello', 'ajax_say_hello' );
and in my ajax.js >
jQuery(document).ready(function($) {
$('#myform').on('submit', function(e) {
var data = {
action: 'ajax_say_hello',
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
});
and ajaxurl is defined correctly.
but I get the entire page as result with no error in console. what is wrong here and what should I do?
Try the below code.
add_action('wp_ajax_ajax_say_hello', 'ajax_post_ajax_say_hello');
add_action( 'wp_ajax_nopriv_ajax_say_hello', 'ajax_post_ajax_say_hello' );
function ajax_post_ajax_say_hello(){
echo "hello";
die;
}

How to send ajax request in wordpress without displaying zero

I am trying to send ajax request to another php page in wordpress. But every time it returns zero with other results.I need to remove the zero. I tried die(); to remove the zero. But after calling this, whole screen becomes blank. My code is below,
Jquery,
<script type="text/javascript">
function key_press(){
jQuery.ajax({
url : '<?php echo get_admin_url()?>admin-ajax.php',
type : 'POST',
data : jQuery('[name="ans_name"]').serialize()
}).done(function(result) {
// ta da
//alert("success");
jQuery("#widget_poll_id").html(result);
});
}
</script>
PHP,
add_action( 'wp_ajax_nopriv_'.$_POST['ans_name'], 'my_ajax' );
add_action( 'wp_ajax_'.$_POST['ans_name'], 'my_ajax' );
function my_ajax() {
echo $_POST['ans_name'];
die();
}
How could I get rid of from this situation ?
It's because your actions are not being called.
You need to declare the property action as below so that WP knows which action to call.
In your particular case you'll also have to declare ans_name (as opposed to data), so that $_POST['ans_name'] exists. I'm guessing that you wish this AJAX request to be called on many occasions by the fact that you used $_POST['ans_name'] in your hook name. If that is not the case, I suggest you use something static, as the hook could be called during other requests when you do not want it.
Finally, I've retrofitted your code with the WP AJAX handler, which will ensure all of the WP goodness that you may need during an AJAX request is included.
<script type="text/javascript">
function key_press(){
var data = {
url: '<?php echo get_admin_url()?>admin-ajax.php',
type: 'POST',
action: jQuery('[name="ans_name"]').serialize(),
ans_name: jQuery('[name="ans_name"]').serialize()
};
var myRequest = jQuery.post(ajax_object.ajaxurl, data, function(response){
alert('Got this from the server: ' + response);
});
myRequest.done(function(){
alert("success");
});
}
</script>
add_action( 'wp_ajax_nopriv_'.$_POST['ans_name'], 'my_ajax' );
add_action( 'wp_ajax_'.$_POST['ans_name'], 'my_ajax' );
function my_ajax(){
echo $_POST['ans_name'];
die(); // Required for a proper Wordpress AJAX result
}
Addition
To ensure AJAX requests for non-logged in users (the nopriv hook) are handeled correctly, add this to your functions.php file.
<?php
add_action('wp_head', 'plugin_set_ajax_url');
function plugin_set_ajax_url() {
?>
<script type="text/javascript">
var ajax_object = {};
ajax_object.ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
?>

php : how to pass database value into a javascript/jquery function

I am implementing tags feature in my project.
In my demo tags i found they are passing names in a javascript function for the autocomple.
This is a function in my demo project,
<script>
$(function()
{
var sampleTags = ['c++', 'scala', 'groovy', 'haskell', 'perl', 'erlang', 'apl', 'cobol', 'go', 'lua'];
..................
.................
So , i want pass values from my php controller to this function ,inorder to get the autocomplete value from my database table
For example i am getting tags values from my db in my Controller like this:
` $data["query"] = $this->ordermodel->fetch_orderlist();`
$this->load->view('tagpage', $data); //loading my page tag page where above function exists
Now how can i pass that $data["query"] values into the above javascript function?
Please help
You could echo the variable onto the page using PHP's json_encode. This function will convert a PHP array or object into a JSON object, which JavaScript can work with:
<script>
$(function() {
var sampleTags = <?php echo json_encode($query); ?>;
})();
</script>
But a better way would be to request these values via Ajax. Say you have a PHP script named values.php:
<?php
#...
#assign $query here
#...
echo json_encode($query);
Then, in JavaScript (on the page where you want to use the sampleTags variable), you can use jQuery's .ajax function to make an easy Ajax request:
<script>
var sampleTags;
$.ajax({
url: 'values.php'
}).done(function(data) {
if (data) {
sampleTags = data;
}
});
</script>
I haven't tested this example. Obviously you'll want to tweak it to fit your environment.
You will have to write an ajax function for this
$.ajax(
url : "<?php echo site_url('controller/method')?>",
type : 'POST',
data : 'para=1',
success : function(data)
{
if(data){
var sampleTags = data;
}
}
);
Just echo your php variable
$(function()
{
var sampleTags = '<?php echo $data["query"]; ?>'

jquery code snippet on load

I'm working with this code snippet plugin : http://www.steamdev.com/snippet/ for my blog
but the plugin doesn't work on page load.
It only works at first page refresh.
I load my content in a specific div with jquery.ajax request and i'm trying this :
$(window).on("load", function(){
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
});
I also tried to trigger the load event but i don't know if it is correct..
Another question : i build my html with php string like this example:
$string = '<pre class="cplus">
#include <iostream>
int main()
{
//c++ code
}
</pre>
<pre class="php">
<?php
function foo()
{
// PHP code
}
?>
</pre>';
echo $string; // ajax -> success
but the PHP snippet shows empty (the c++ is ok). Any other way (or plugin) to show php code snippet on my page?
Thank you.
SOLVED:
The problem isn't the plugin or Iserni suggestions.. i had a problem in page load (ajax)..
This is how i load the pages:
function pageload(hash) {
if(hash == '' || hash == '#php')
{
getHomePage();
}
if(hash)
{
getPage();
}
}
function getHomePage() {
var hdata = 'page=' + encodeURIComponent("#php");
//alert(hdata);
$.ajax({
url: "homeloader.php",
type: "GET",
data: hdata,
cache: false,
success: function (hhtml) {
$('.loading').hide();
$('#content').html(hhtml);
$('#body').fadeIn('slow');
}
});
}
function getPage() {
var data = 'page=' + encodeURIComponent(document.location.hash);
//alert(data);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
$('.loading').hide();
$('#content').html(html);
$('#body').fadeIn('slow');
}
});
}
$(document).ready(function() {
// content
$.history.init(pageload);
$('a[href=' + window.location.hash + ']').addClass('selected');
$('a[rel=ajax]').click(function () {
var hash = this.href;
hash = hash.replace(/^.*#/, '');
$.history.load(hash);
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
$('#body').hide();
$('.loading').show();
getPage();
return false;
});
// ..... other code for menus, tooltips,etc.
I know this is experimental , i have made a mix of various tutorials but now it works..
comments are much appreciated..
Thanks to all.
The PHP snippet seems empty because the browser believes it's a sort of HTML tag.
Instead of
$string = '<pre class="php">
<?php
function foo()
{
// PHP code
}
?>
</pre>';
you need to do:
// CODE ONLY
$string = '<?php
function foo()
{
// PHP code
}
?>';
// HTMLIZE CODE
$string = '<pre class="php">'.HTMLEntities($string).'</pre>';
As for the jQuery, it is probably due to where you put the jQuery code: try putting it at the bottom of the page, like this:
....
<!-- The page ended here -->
<!-- You need jQuery included before, of course -->
<script type="text/javascript">
(function($){ // This wraps jQuery in a safe private scope
$(document).ready(function(){ // This delays until DOM is ready
// Here, the snippets must be already loaded. If they are not,
// $("pre.cplus") will return an empty wrapper and nothing will happen.
// So, here we should invoke whatever function it is that loads the snippets,
// e.g. $("#reloadbutton").click();
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
});
})(jQuery); // This way, the code works anywhere. But it's faster at BODY end
</script>
</body>
Update
I think you could save and simplify some code by merging the two page loading functions (it's called the DRY principle - Don't Repeat Yourself):
function getAnyPage(url, what) {
$('.loading').show(); // I think it makes more sense here
$.ajax({
url: url,
type: "GET",
data: 'page=' + encodeURIComponent(what),
cache: false,
success: function (html) {
$('.loading').hide();
$('#content').html(hhtml);
$('#body').fadeIn('slow');
}
// Here you ought to allow for the case of an error (hiding .loading, etc.)
});
}
You can then change the calls to getPage, or reimplement them as wrappers:
function getHomePage(){ return getAnyPage('homeloader.php', "#php"); }
function getPage() { return getAnyPage('loader.php', document.location.hash); }
ok for the first issue I would suggest to
see what your JS error console saying
ensure correspondent js plugin file is loaded
and use the following code when you are using ajax (the key thing is "success" event function):
$.ajax({
url: 'your_url',
success: function(data) {
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
}
});
for the second issue lserni answered clearly
you need to use to jquery on load function like so:
$(function(){
RunMeOnLoad();
});

buddy press ajax new message notifiction

i am working on one buddy press theme and want to display unread messages count via ajax.
i have bellow code in function.php of my theme
<?php
function addMessageRefresh()
{
?>
<script type="text/javascript">
function getMessages(){
jQuery('#user-messages span').text("Unread Messages: (<?php echo messages_get_unread_count(); ?>)");
}
setInterval("getMessages()", 10000);
</script>
<?php
}
add_action( 'wp_head', 'addMessageRefresh');
?>
it worked.
but its only show unread count on page load, but if user receive any message this did’t update.
the main purpose of this script is to display total number of unread messages and it should update via ajax means if user receive any message, it should show total number of unread messages without reloading page.
Thanks
somehow it..
function getMessages(){
jQuery.ajax({
url: '../url.php'
dataType: 'html',
success: function (data) {
jQuery('#user-messages span').text("Unread Messages: " + data);
}}
)
}
../url.php code
<?php echo messages_get_unread_count(); ?>
There are several steps, that you need to do:
1) Place element which contain unread message count. This should be adde to your template.
<div id="unread_messages"></div>
2) Add javascript code which will update your count value.You can add this to your template or you can print it from wp_head/wp_footer hooks
<script type="text/javascript">
function update_unread_count() {
jQuery('#unread_messages').load(
'<?php echo admin_url('admin-ajax.php'); ?>',
{ 'action': 'get_unread_message_count' }
);
}
jQuery(document).ready(function() {
// update every 15 seconds, after page loaded
setInterval('update_unread_count()', 15000);
});
</script>
3) Register ajax request handler. You should add this lines into your functions.php theme file
function my_get_unread_message_count() {
echo messages_get_unread_count();
die();
}
add_action('wp_ajax_get_unread_message_count', 'my_get_unread_message_count');
Something like that.
Your issue lies within:
jQuery('#user-messages span').text("Unread Messages: (<?php echo messages_get_unread_count(); ?>)");
What is being done is when the page is being loaded PHP processes the messages_get_unread_count() function and uses that value to render the page. From there the generated JavaScript will be called at your interval but it will have a static value defined in your preprocessed markup.
You will need to have an AJAX call to a url that will return your message count.
This is the functionality to allow you to get the updated message count.
function add_message_count_js() {
?>
<script type="text/javascript">
//<![CDATA[
var msg_count;
function updateMessages() {
jQuery.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {"action": "view_message_count"},
success: function(data) {
jQuery('#user-messages span').text("Unread Messages: "+data);
}
});
return false;
}
setInterval('updateMessages()', 10000);
//]]>
</script>
<?php
}
add_action('wp_head', 'add_message_count_js');
This will add the appropriate AJAX hooks.
add_action('wp_ajax_view_message_count', 'view_message_count');
add_action('wp_ajax_nopriv_view_message_count', 'view_message_count');
function view_message_count() {
if (is_user_logged_in())
echo messages_get_unread_count();
die();
}
Both of these snippets should go in your functions.php file.

Categories