Inserting Option via AJAX using Settings API - php

I am making a plugin and need to insert a value using the 'add_option()' function - or something that achieves the same result.
This is what I use to call my AJAX:
// localize script
wp_localize_script('button-js', 'the_ajax_script', array('ajaxurl' => admin_url('admin-ajax.php')));
And what launches the PHP function:
add_action('wp_ajax_process_form', array($this, 'process_ajax'));
I need to run add_option() in the function called after my AJAX runs (my AJAX code below):
function post(num) {
var data = {
action : 'process_form',
form_number : num
};
$.post(the_ajax_script.ajaxurl, data).error(
function() {
alert('error');
}).success(function() {
console.log(data);
});
return false;
}
And here is the function that is run by AJAX:
public function process_ajax() {
$num = $_POST['form_number'];
if(isset($num)) {
add_option('form-num', $num);
}
die();
}
My AJAX code runs successfully, and the correct values are logged to the console - however upon using
<?php echo get_option('form_num'); ?>
The value is blank.

Related

Ajax function call to php function

I have a simple php function as below defined in one of my php file
add_action('wp_ajax_test','test');
add_action('wp_ajax_nopriv_test','test');
function test(){
echo "Hello";
}
I am calling above "test" function using below ajax function call
jQuery(document).ready(function(){
jQuery('#prev_button_id').click(function(){
jQuery.post(
myAjax.ajaxurl,
{
action:"test",
success: (response)=>{
console.log('Success:'+ response);
},
error:(response)=>{
console.log('Failure:'+ response);
}
});
});
});
I am expecting console output of "Hello" but I getting below undefined response
Success:undefined
Failure:undefined
jQuery(document).ready(function(){
jQuery('#prev_button_id').click(function(){
var params = {action:"test"}
jQuery.post(myAjax.ajaxurl,params,function(data){
if( data ){
console.log ( data );
}
});
});
});
add_action( 'wp_ajax_test','test' );
add_action( 'wp_ajax_nopriv_test','test' );
function test() {
echo "Hello";
die;
}
Try this code and don't forget to die after AJAX call also
make sure you are getting proper AJAX URL in myAjax.ajaxurl
I followed the below video, step by step and it worked.
Probably it had something to do with nonce
AJAX in WordPress using admin-ajax.php

Wordpress Ajax Request returns 0 in chrome, works fine in FF

I have a front-end Ajax call set up to randomize an image whenever a button is pressed. I set it up as follows:
Functions.php
define("AJAX_URL", admin_url('admin-ajax.php'));
add_action("wp_enqueue_scripts", "enqueue_eyewebz_scripts");
function enqueue_eyewebz_scripts()
{
wp_enqueue_script("jquery");
...
wp_enqueue_script("root-js", JS_URL . "/root.js", array("jquery"));
$script_params = array(
'ajax_url' => AJAX_URL
);
wp_localize_script('root-js', 'theme_vars', $script_params);
}
root.js
function parallax_randomize(e)
{
var data = {
'action': 'randomize_parallax',
'dataType': 'json'
};
console.log(theme_vars.ajax_url);
jQuery.post(theme_vars.ajax_url, data, function(response) {
console.log(response);
var dynb = JSON.parse(response);
jQuery('#front-location span').html(dynb.location);
jQuery('.parallax-slider').fadeOut('fast', function () {
jQuery('.parallax-slider').attr('src', dynb.url);
jQuery('.parallax-slider').fadeIn('fast');
});
});
}
Dynamic background callback
class Dynb
{
function Dynb()
{
...
$this->set_up_ajax();
...
}
public function set_up_ajax()
{
add_action('wp_ajax_randomize_parallax', array($this, 'randomize_parallax'));
}
public function randomize_parallax()
{
$data = set_dynamic_background(true);
echo json_encode($data);
wp_die();
}
}
new Dynb();
In Firefox, this works just fine, but in Chrome, my JS Ajax call returns 0. I can't for the life of me figure out what the problem is. Anyone?
just add exit() in randomize_parallax() function,i think it will fix your issue
When sending an ajax request from the front-end, you need to include an action that has wp_ajax_nopriv_ ... (shown below) if you want this to work. If you don't add that action, users that are not logged in will not be able to call for the ajax function.
add_action('wp_ajax_nopriv_randomize_parallax', array($this, 'randomize_parallax'));

Ajax call not working out in wordpress

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');

Calling php function with ajax and passing return value to div

I have a function that adds social buttons to my blog posts , but once i load more posts using ajax I cant figure out how can I call add_social_buttons() and pass the data to div.
I'm not really familiar with ajax , i tried this method :
$.ajax({
type:"POST",
url:"functions.php",
data: "social_sharing_buttons()",
success: function(data){
$('.pp').html(data);
}
but it seems that it tries to invoke some totally other function Fatal error: Call to undefined function add_action().
As far as I am aware, you can't. What you can do is have a handler file for your classes, so for example say we have this PHP class,
<?php
class Car {
function getCarType() {
return "Super Car";
}
}
?>
Then in your handler file,
<?php
require_once 'Car.php';
if(isset($_POST['getCarType'])) {
$car = new Car();
$result = $car->getCarType();
echo $result;
}
?>
You'd post your AJAX request to the handler, you could make specific handlers for each request or you could have a generic AJAX handler, however that file could get quite big and hard to maintain.
In your case you'd have in that data,
"getSocialButtons" : true
Then in your AJAX handler file,
if (isset($_POST['getSocialButtons'])) {
// Echo your function here.
}
Then you'd echo out the function within that if statement and using the success callback in your AJAX request do something like this.
document.getElementById("yourDivId").innerHTML = data
That is assuming you're using an ID. Adjust the JS function to suit you.
Try to call that function social_sharing_buttons() like this in function.php:
$.ajax({
type:"POST",
url:"functions.php",
data: {action: 'add'},
success: function(data){
$('.pp').html(data);
}
in functions.php
if(isset($_POST['action']) && !empty($_POST['action'])) {
if($_POST['action'] == 'add') {
echo social_sharing_buttons();
}
}

Codeigniter method inside javascript loop

I have the following javascript loop which correctly alerts the value I need to use in a Codeigniter method. Here is the js loop:
function myInsert(){
$('input[name=r_maybe].r_box').each(function(){
if( $(this).prop('checked') ){
// need to replace this alert with codeigniter method below
alert ($(this).prop('value'));
}
});
}
Instead of alerting the required value, I need to somehow execute this Codeigniter method:
//this would never work because it mixes JS with PHP, but I need a workaround
$this->appeal_model->myMethod($(this).prop('value'), 888, 999);
Is there someway that I can run this PHP code inside the javascript loop? I know about PHP being server-side and JS being client-side, but I'm sure there must be a solution to my problem that I'm just not aware of yet. Thanks.
The solution to this is to make an ajax call to the server, you can have a method on your controller which calls your codeigniter method. This divides your php call and your client side call.
If you are inserting something into the database, you should use the ajax post method.
http://api.jquery.com/jQuery.post/
function myInsert() {
$('input[name=r_maybe].r_box').each(function(){
if( $(this).prop('checked') ){
var value = $(this).prop('value');
$.post("controllername/functionname", { value: value }, function(data) {
alert(data); // Returned message from the server
});
}
});
}
Use ajax to store data to the server side:
The code should be something like this:
function myInsert(){
$dataArray=[];
$('input[name=r_maybe].r_box').each(function(){
if( $(this).prop('checked') ){
// need to replace this alert with codeigniter method below
dataArray.push($(this).prop('value'))
}
});
if(dataArray.length>0)
{
$.ajax({
url:"your file name",//this file should contain your server side scripting
type:"POST",
data:{dataName : dataArray}
success:function(){
}
});
}
}
you can use $.post from jquery
function myInsert(){
$('input[name=r_maybe].r_box').each(function(){
if( $(this).prop('checked') ){
$.post('<?php echo site_url("controllerName/functionName")?>',
{"post1": $(this).prop('value'), "post2":888, "post3": 999 },
function(data.res == "something"){
//here you can process your returned data.
}, "json"); //**
}
});
}
In your controller you can have:
function functionName()
{
//getting your posted sec token.
$post1 = $this->input->post('post1');
$post2 = $this->input->post('post2');
$post3 = $this->input->post('post3');
$data['res'] = "something";// return anything you like.
// you should use json_encode here because your post's return specified as json. see **
echo json_encode($data); //$data is checked in the callback function in jquery.
}
Since this will be dumping data directly into your db, make sure this is secured in some manner as well, in terms of who has access to that controller function and the amount of scrubbing/verification done on the data being passed.

Categories