Wordpress plugin insert query is not working - php

I'm calling a wordpress plugin function via a front end page which is working good, the function that i m calling is inserting data into the database but its not working
here is the query i m running(which is not working):
The function is being called on submit as echo value is printed but no data is being inserted
function savedata(){
echo "<pre>";print_r($_POST);exit;
global $wpdb;
$wpdb->insert('questoptions',
array(
'question_id' => $_POST['question_id'],
'text' => $_POST['text']
),
array(
'%s',
'%s'
)
);
die();
return true;
}
here is the function calling this function from front end:
function abc(){
jQuery.ajax({
type: 'POST',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: { action: 'savedata', 'question_id': document.getElementById('question_id').value, 'text': document.getElementById('text').value },
success: function(data){
alert('success');
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
anyone has any idea?
Thanks.

Wordpress ajax function infromation
Add this functions and check your post data is called or not ?
wp_ajax_nopriv_(action) executes for users that are not logged in.
add_action( 'wp_ajax_savedata', 'custom_savedata' );
add_action( 'wp_ajax_nopriv_savedata', 'custom_savedata' );
function custom_savedata() {
global $wpdb;
if(isset($_POST) && !empty($_POST['question_id'])):
$data = ($wpdb->insert('table_name_add_here', array(
'question_id' => $_POST['question_id'],
'text' => $_POST['text'],
)
));
if($data){
echo 'success';
}else{
echo 'not success';
}
else:
echo 'please check post data';
endif;
exit;
}

plz remove second line
echo "<pre>";print_r($_POST);exit;'
so it execute rest of code and return.
if u should try this and also not get solution than u must be check your database table name if table name pretend by 'wp' than u should try wp_ questoptions as table name in query instead of questoptions.
thinks. might be it will help you.

Related

Get PHP values in AJAX to replace input field values

I've created a Custom Post Type in Wordpress called Location/Tour and another one called Itinerary. In my CPT Itinerary, I have some ACF custom fields one of them is a repeater field that has subfields (Relationship field for the CPT Location/Tour, Title field, Description field).
I've created a button that should trigger an AJAX script which job is to get the values from the CPT Location/Tour(Title and Description) and
put them in my input subfields(Title and Description) in my CPT Itinerary.
I've created a PHP function that gets the values from the CPT Location/Tour and now I'm trying to run the PHP function using AJAX.
I was able to get the AJAX working and I get the values in my console log under ResponseText.
Now the part I'm struggling with. I need to set each value as a separate variable in JS so that I can replace the input field values with the new ones but unfortunately I don't know how.
I've tried almost everything and I think that I'm close to the answer but I'm missing something. :(
Here is my post-value-loader.php
<?php
// LOAD DEFAULT VALUES FROM DEFAULT TOUR
add_action('wp_ajax_post_loader', 'post_loader');
function post_loader($field) {
$post_id = $_POST["post_id"];
$args = array(
'p' => $post_id,
'numberposts'=> -1, // Fetch all posts...
'post_type'=> 'location_tour', // from the 'location_tour' CPT...
);
$location = new WP_Query( $args );
if ( $location->have_posts() ) : while ( $location->have_posts() ) : $location->the_post();
$title = the_field('title'); //The Title field value that we need
$description = the_field('description'); //The Description field value that we need
wp_reset_postdata();
?>
<?php endwhile; endif; ?>
<?php add_action('acf/prepare_field/name=default_tour', 'post_loader'); ?>
<?php }
// BUTTON TO RUN AJAX
function my_acf_prepare_field($field) {
echo '<div class="acf-field"><button type="submit" id="data_fetch" class="button acf-load-default-tour-values">Load default value</button></div>';
return $field;
}
add_action('acf/prepare_field/name=default_tour', 'my_acf_prepare_field');
// ADD SCRIPT TO WORDPRESS ADMIN AJAX
function js_data_fetch() {
wp_enqueue_script ("ajax-data-fetch", get_stylesheet_directory_uri() . "/inc/assets/js/data-fetch.js", array('jquery'));
//the_ajax_script will use to print admin-ajaxurl in data-fetch.js
wp_localize_script('ajax-data-fetch', 'the_ajax_script', array('ajaxurl' =>admin_url('admin-ajax.php')));
}
add_action("admin_enqueue_scripts", "js_data_fetch");
?>
And here is my data-fetch.js (Note: I'm not a JS guy :( )
jQuery(document).on( 'click', '#data_fetch', function( dohvati ){
dohvati.preventDefault();
var post_id = jQuery('.acf-row .selection .values ul li span').data('id'); // This takes the post ID from the selected Post(Location/Tour) in the Relationship field
jQuery.ajax({
url: the_ajax_script.ajaxurl, //The URL that we set for the wordpress admin-ajax.php
type: "POST",
dataType: 'json',
data: {
action: 'post_loader', // This is the name of the php function
post_id: post_id,
},
success: function(data){
console.log(data)
},
error: function(error){
console.log(error)
},
});
jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeabc041c8a").val(title); //This is replacing the title field - but the variables are missing
jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeab8f41c89").val(description); //This is replacing the description field - but the variables are missing
});
Also here are two images from the CPT Itinerary editor (https://imgur.com/kFImdpe) with the fields and my console log (https://imgur.com/wwxKXQP). Hope that this helps.
You have to return the data as JSON from post_loader function. I've cleaned up a little, but still, it's a mess.
// LOAD DEFAULT VALUES FROM DEFAULT TOUR
add_action('wp_ajax_post_loader', 'post_loader');
function post_loader() {
$post_id = $_POST["post_id"];
$args = array(
'p' => $post_id,
'numberposts'=> -1, // Fetch all posts...
'post_type'=> 'location_tour', // from the 'location_tour' CPT...
);
$location = new WP_Query( $args );
if ( $location->have_posts() ) :
while ( $location->have_posts() ) :
$location->the_post();
$title = the_field('title');
$description = the_field('description');
// You have to return data as json
wp_send_json([
'title' => $title,
'description' => $description
]);
//wp_reset_postdata();
endwhile;
endif;
// Why do you need this inside this function?
// add_action('acf/prepare_field/name=default_tour', 'post_loader');
}
JS
jQuery(document).on( 'click', '#data_fetch', function( dohvati ){
dohvati.preventDefault();
var post_id = jQuery('.acf-row .selection .values ul li span').data('id'); // This takes the post ID from the selected Post(Location/Tour) in the Relationship field
jQuery.ajax({
url: the_ajax_script.ajaxurl, //The URL that we set for the wordpress admin-ajax.php
type: "POST",
dataType: 'json',
data: {
action: 'post_loader', // This is the name of the php function
post_id: post_id,
},
success: function(data){
console.log(data)
jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeabc041c8a").val(data.title); //This is replacing the title field - but the variables are missing
jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeab8f41c89").val(data.description); //This is replacing the description field - but the variables are missing
},
error: function(error){
console.log(error)
},
});
});

Ajax request return success message but data does not insert into database

I am sending a ajax request it also returning success message but data is not inserting. Basically it is a link, when I will will click on the link then ajax will send a request to controllers and in database it increase the value with the previous value by 1. I have tried pass huge times but failed. This is a codignator project. It will grateful if you kindly help.
Ajax File :
$(document).ready(function(){
$("#like").click(function(e){
e.preventDefault(); // <------this will restrict the page refresh
var post_id = $(this).prop('rel');
$.ajax({
url: "http://localhost/ci_website/index.php/site/add_like",
type: 'POST',
data : post_id,
dataType: 'json',
success: function(res) {
if (res.success) {
alert(res.msg);
} else {
alert(res.msg);
}
}
});
return false;
});
});
View File :
<a id="like" class="like_btn" rel="<?php echo $blog['blog_id'];?>" href="<?php echo site_url('site/add_like') . '/' . $blog['blog_id'];?>">Like</a>
Controller File :
public function add_like()
{
header('Content-Type: application/json');
if ($this->input->is_ajax_request()) {
$post_id = $this->uri->segment(3);
$this->db->set('post_like', '`post_like` + 1', FALSE);
$this->db->where('blog_id', $post_id);
$add_post_view = $this->db->update('wb_blog');
if ($add_post_view) {
die(json_encode(array('success' => true, 'msg' => 'Your Like has been sent successfully.')));
} else die(json_encode(array('success' => false, 'msg' => 'Something bad happened!!! Please, try again.')));
}
}
update
check with
if ($this->db->_error_message()) {
return FALSE; // Or do whatever you gotta do here to raise an error
} else {
return $this->db->affected_rows();
}`
You aren't calling the function, you're only loading the function, and since the loading of the file succeeded, it returns true.
After defining the function try calling it and see if that does work.
url: "http://localhost/ci_website/index.php/site/add_like/"+post_id,
I have add 'post_id' after the link. This is work fine. I did not define the exact id against which the row of the table will be affected.

Codeigniter cascading dropdown with data from database

I'm need help in making a cascading dropdown that contains data from the database
I found a tutorial about this
and
I've tried this
Controller:
function ajax_call() {
if(!empty($_POST['table'])){
if ($_POST) {
$table = $_POST['table'];
$arrYear = $this->my_model->get_categories($table);
foreach ($arrYear as $years) {
$arrFinal[$years->category2 = $years->category2;
}
echo "<p>2nd Category:<br>";
echo form_dropdown('year',$arrFinal);
echo "</p><br>";
}
else
{
echo "<p>2nd Category:<br>";
echo form_dropdown('year','');
echo "</p><br>";
}
}
}
My view:
$options = array(
'' => 'Select',
'category_one' => 'Category 1',
'category_two' => 'Category 2',
);
echo form_error('table');
echo "<p>Category:<br> ";
echo form_dropdown('table', $options, $this->input->post('table'), 'id="table"');
echo "</p><br>";
Script inside my view:
<script type="text/javascript">
$(document).ready(function(){
$('#table').change(function(){
var selTable = $(this).val(); // selected name from dropdown #table
$.ajax({
url: "ajax_call", // or "resources/ajax_call" - url to fetch the next dropdown
async: false,
type: "POST", // post
data: "table="+selTable, // variable send
dataType: "html", // return type
success: function(data) { // callback function
$('#year').html(data);
}
})
});
});
</script>
My Model:
function get_categories($table) {
$this->db->select('category2')->from($table);
$query = $this->db->get();
return $query->result();
}
My only problem with this is that the 2nd dropdown isn't visible on the page when loaded, and it would only appear when I select on the 1st dropdown.
How can i make set it to appear on the page without selecting on the 1st dropdown?
Can anyone help?
Ok I couldn't figure out how to do what i wanted. So instead i searched around the deep parts of the internet and found this little tutorial that was actually what i needed.
http://supundharmarathne.wordpress.com/2013/03/13/simple-ajax-drop-down-filtering-with-codeigniter/
This is happening because the ajax call to populate your table is only being triggered after the table changes $('#table').change(function(){...}). Try populating the table without waiting for such change; maybe inside $(document).ready(function(){...})
you added a completely obsolete if ($_POST) to your code. You are already checking if a variable in $_POST exists, hence it can never be empty after that. That caused your ELSE statement to relate to the second IF, not the first.
function ajax_call() {
if(!empty($_POST['table'])){
$table = $_POST['table'];
$arrYear = $this->my_model->get_categories($table);
foreach ($arrYear as $years) {
$arrFinal[$years->category2 = $years->category2;
}
echo "<p>2nd Category:<br>";
echo form_dropdown('year',$arrFinal);
echo "</p><br>";
}
else
{
echo "<p>2nd Category:<br>";
echo form_dropdown('year','');
echo "</p><br>";
}
}
and that is why you should always indent your code correctly.

jQuery .ajax function, exactly how to use it

I am using wordpress and need to update a tables data with jQuery ajax, I have the below code which posts the data successfully.
jQuery('#update-<?php echo $row->id; ?>').live('click', function (){
var myname = jQuery('input[name="name_two"]').val();
var mystep = jQuery('#step<?php echo $row->id; ?> option:selected').val();
jQuery.ajax({
type: "POST",
url: "/wp-content/plugins/gates/updateGateData.php",
data: {name_two:myname, step_two:mystep},
success: function(data) {
alert('Data updated');
},
});
});
Now my problem resides on what to put in the updateGateOption.php file to post to update the database.
Thanks Guys for the responses! So I have this now:
$name = $_POST['name_two'];
$step = $_POST['step_two'];
global $wpdb;
$wpdb->update(
'gate_options',
array(
'step' => $step,
'name' => $name,
'image_path' => 'new-img-path',
'option' => strtolower($name),
'value' => strtolower($name),
)
);
But the values are not being updated, plus I cannot see any errors..
Try below Code in updateGateOption.php:
$name = $_POST['name_two'];
$step = $_POST['step_two'];
Now run your query,
if(mysql_query("UPDATE tablename SET field1= $name, field2=step WHERE 1=1 AND YOUR_CONDITION")){
echo "Data updated successfully";
}else{
echo "Something went wrong";
}

Wordpress: how to call a plugin function with an ajax call?

I'm writing a Wordpress MU plugin, it includes a link with each post and I want to use ajax to call one of the plugin functions when the user clicks on this link, and then dynamically update the link-text with output from that function.
I'm stuck with the ajax query. I've got this complicated, clearly hack-ish, way to do it, but it is not quite working. What is the 'correct' or 'wordpress' way to include ajax functionality in a plugin?
(My current hack code is below. When I click the generate link I don't get the same output I get in the wp page as when I go directly to sample-ajax.php in my browser.)
I've got my code[1] set up as follows:
mu-plugins/sample.php:
<?php
/*
Plugin Name: Sample Plugin
*/
if (!class_exists("SamplePlugin")) {
class SamplePlugin {
function SamplePlugin() {}
function addHeaderCode() {
echo '<link type="text/css" rel="stylesheet" href="'.get_bloginfo('wpurl').
'/wp-content/mu-plugins/sample/sample.css" />\n';
wp_enqueue_script('sample-ajax', get_bloginfo('wpurl') .
'/wp-content/mu-plugins/sample/sample-ajax.js.php',
array('jquery'), '1.0');
}
// adds the link to post content.
function addLink($content = '') {
$content .= "<span class='foobar clicked'><a href='#'>click</a></span>";
return $content;
}
function doAjax() { //
echo "<a href='#'>AJAX!</a>";
}
}
}
if (class_exists("SamplePlugin")) {
$sample_plugin = new SamplePlugin();
}
if (isset($sample_plugin)) {
add_action('wp_head',array(&$sample_plugin,'addHeaderCode'),1);
add_filter('the_content', array(&$sample_plugin, 'addLink'));
}
mu-plugins/sample/sample-ajax.js.php:
<?php
if (!function_exists('add_action')) {
require_once("../../../wp-config.php");
}
?>
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
var aref = this;
jQuery(this).toggleClass('clicked');
jQuery.ajax({
url: "http://mysite/wp-content/mu-plugins/sample/sample-ajax.php",
success: function(value) {
jQuery(aref).html(value);
}
});
});
});
mu-plugins/sample/sample-ajax.php:
<?php
if (!function_exists('add_action')) {
require_once("../../../wp-config.php");
}
if (isset($sample_plugin)) {
$sample_plugin->doAjax();
} else {
echo "unset";
}
?>
[1] Note: The following tutorial got me this far, but I'm stumped at this point.
http://www.devlounge.net/articles/using-ajax-with-your-wordpress-plugin
TheDeadMedic is not quite right. WordPress has built in AJAX capabilities. Send your ajax request to /wp-admin/admin-ajax.php using POST with the argument 'action':
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
jQuery(this).toggleClass('clicked');
jQuery.ajax({
type:'POST',
data:{action:'my_unique_action'},
url: "http://mysite/wp-admin/admin-ajax.php",
success: function(value) {
jQuery(this).html(value);
}
});
});
});
Then hook it in the plugin like this if you only want it to work for logged in users:
add_action('wp_ajax_my_unique_action',array($sample_plugin,'doAjax'));
or hook it like this to work only for non-logged in users:
add_action('wp_ajax_nopriv_my_unique_action',array($sample_plugin,'doAjax'));
Use both if you want it to work for everybody.
admin-ajax.php uses some action names already, so make sure you look through the file and don't use the same action names, or else you'll accidentally try to do things like delete comments, etc.
EDIT
Sorry, I didn't quite understand the question. I thought you were asking how to do an ajax request. Anyway, two things I'd try:
First, have your function echo just the word AJAX without the a tag. Next, try changing your ajax call so it has both a success and a complete callback:
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
var val = '';
jQuery(this).toggleClass('clicked');
jQuery.ajax({
type:'POST',
data:{action:'my_unique_action'},
url: "http://mysite/wp-admin/admin-ajax.php",
success: function(value) {
val = value;
},
complete: function(){
jQuery(this).html(val);
}
});
});
});
WordPress environment
First of all, in order to achieve this task, it's recommended to register then enqueue a jQuery script that will push the request to the server. These operations will be hooked in wp_enqueue_scripts action hook. In the same hook you should put wp_localize_script that it's used to include arbitrary Javascript. By this way there will be a JS object available in front end. This object carries on the correct url to be used by the jQuery handle.
Please take a look to:
wp_register_script(); function
wp_enqueue_scripts hook
wp_enqueue_script(); function
wp_localize_script(); function
File: functions.php 1/2
add_action( 'wp_enqueue_scripts', 'so_enqueue_scripts' );
function so_enqueue_scripts(){
wp_register_script( 'ajaxHandle', get_template_directory() . 'PATH TO YOUR JS FILE', array(), false, true );
wp_enqueue_script( 'ajaxHandle' );
wp_localize_script( 'ajaxHandle', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
File: jquery.ajax.js
This file makes the ajax call.
jQuery(document).ready( function($){
//Some event will trigger the ajax call, you can push whatever data to the server, simply passing it to the "data" object in ajax call
$.ajax({
url: ajax_object.ajaxurl, // this is the object instantiated in wp_localize_script function
type: 'POST',
data:{
action: 'myaction', // this is the function in your functions.php that will be triggered
name: 'John',
age: '38'
},
success: function( data ){
//Do something with the result from server
console.log( data );
}
});
});
File: functions.php 2/2
Finally on your functions.php file there should be the function triggered by your ajax call.
Remember the suffixes:
wp_ajax ( allow the function only for registered users or admin panel operations )
wp_ajax_nopriv ( allow the function for no privilege users )
These suffixes plus the action compose the name of your action:
wp_ajax_myaction or wp_ajax_nopriv_myaction
add_action( 'wp_ajax_myaction', 'so_wp_ajax_function' );
add_action( 'wp_ajax_nopriv_myaction', 'so_wp_ajax_function' );
function so_wp_ajax_function(){
//DO whatever you want with data posted
//To send back a response you have to echo the result!
echo $_POST['name'];
echo $_POST['age'];
wp_die(); // ajax call must die to avoid trailing 0 in your response
}
Hope it helps!
Let me know if something is not clear.
Just to add an information.
If you want to receive an object from a php class method function :
js file
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
var data = {
'action': 'getAllOptionsByAjax',
'arg1': 'val1',
'arg2': $(this).val()
};
jQuery.post( ajaxurl, data, function(response) {
var jsonObj = JSON.parse( response );
});
});
php file
public static function getAllOptionsByAjax(){
global $wpdb;
// Start query string
$query_string = "SELECT * FROM wp_your_table WHERE col1='" . $_POST['arg1'] . "' AND col2 = '" . $_POST['arg2'] . "' ";
// Return results
$a_options = $wpdb->get_results( $query_string, ARRAY_A );
$f_options = array();
$f_options[null] = __( 'Please select an item', 'my_domain' );
foreach ($a_options as $option){
$f_options [$option['id']] = $option['name'];
}
$json = json_encode( $f_options );
echo $json;
wp_die();
}

Categories