wordpress ajax won't send response as array, why? - ajax

i have worked for wordpress project which need to call back some result from database via ajax .
the problem is the response will be in string form which is not as i aspect .
here is whats my try :
//The PHP
function edit_something() {
if ( isset($_REQUEST) ) {
global $wpdb;
$ID = intval( $_REQUEST['ID'] );
$query= "SELECT * FROM `TABLE` WHERE `ID` = '$ID';";
$result= $wpdb->get_results( $queryHavadesEnsani, 'ARRAY_A' );
print_r( $resultsHavadesEnsani );
}
}
die();
}
add_action( 'wp_ajax_edit_something', 'edit_something' );
and the endpoint
function myplugin_ajaxurl() {
echo '<script type="text/javascript">
var ajaxurl = "' . admin_url('admin-ajax.php') . '";
</script>';
}
add_action('wp_head', 'myplugin_ajaxurl');
at the end the jquery
function sendAjax( ID ) {
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
'action' : 'edit_something',
'ID' : ID
},
success:function(data) {
console.log(data)
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
i realy need your guidance
more info :
i also tried json_encode for php and JSON.parse for js but error the response will be Object object .

I guess instead of "echo" you should use wp_send_json_success
https://developer.wordpress.org/reference/functions/wp_send_json_success/
How to call ajax in Wordpress

Related

Wordpress, admin menu, Ajax 400 bad request

I am trying to delete database row using button, (this is inside my plugin in admin area)
but i am not able to figure out why my ajax call is not working.
Every time i try i recive: 400 bad request all the time.
So i did not manage it yet to call the function properly
this is my button:
<button class="deletebutton" <?php echo 'value="' . $data->id . '"' ?> class="delete"> delete</button>
And i use:
add_action('wp_ajax_delete_data', 'delete_data');
MY function: (i know it work i have use it many times before
'function delete_data($element_id){
global $wpdb;
$tablename = $wpdb->prefix . 'my_table';
$wpdb->delete($tablename, array('id' => $element_id));
}'
And Jquery/AJAX <- here is the problem i think
<script>
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery(document).ready(function() {
jQuery(".deletebutton").click(function(){
var element_id = this.value;
jQuery.ajax({
url: ajaxurl,
type: 'POST',
action: 'delete_data',
data: element_id
dataType: 'data',
});
});
});
</script>
You have given the wrong actions name. see more information here
Change this line
`add_action('wp_ajax_worktmp_delete_absence', 'delete_data');`
With this
`add_action('wp_ajax_delete_data', 'delete_data');`
So the proper of doing this is
Create a separate js file or you can use it upon the existing js file like following while you are enqueuing your script:
wp_register_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . '{your_js_file_location}', array( 'jquery' ), $this->version, false );
wp_localize_script( $this->plugin_name, 'test_ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script($this->plugin_name);
Then
add_action('wp_ajax_delete_data', 'delete_data');
if it is for normal user hten add the folowwing as well
add_action('wp_ajax_nopriv_delete_data', 'delete_data');
Then in your js file
jQuery(document).ready(function($) {
$(".deletebutton").click(function(){
var element_id = this.value;
$.ajax({
url: test_ajax_object.ajaxurl,
type : 'post',
data : {
"action" : 'delete_data', "data_id":element_id},
success: function( response ) {
console.log(response);
}
});
});
});
And in your php file
function delete_data(){
global $wpdb;
$element_id = $_POST['data_id'];
$tablename = $wpdb->prefix . 'my_table';
$wpdb->delete($tablename, array('id' => $element_id));
}
This might work, try once

Why Ajax response in Wordpress doesn't work?

I have odd (for me) problem with ajax in Wordpress. I do not receive proper response from server. I read Wordpress Codex to find out what I doing wrong, but still I have no clue.
I don't know if it is important or not, but when I tried add a type to ajax syntax, I received an error message.
class databaseClass
{
function __construct()
{
if ( isset($_SERVER['HTTPS']) )
$protocol = 'https://';
else
$protocol = 'http://';
wp_enqueue_script( 'ajaxScript', '/wp-content/themes/bulk/js/ajaxScript.js');
wp_localize_script( 'ajaxScript', 'my_ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php', $protocol ),
'nonce' => wp_create_nonce( '111')
) );
add_action('wp_ajax_save_sort', 'ajaxFunctionInPHP');
add_action( 'wp_ajax_nopriv_save_sort', 'ajaxFunctionInPHP');
}
function ajaxFunctionInPHP(){
/*check_admin_referrer();
$response['custom'] = "ssss";
$response = json_encode($response);
wp_send_json($response) ;*/
ob_clean();
$response['custom'] = "TEST";
echo $response;
die();
}
}
class ajaxClass extends databaseClass
{
function __construct()
{
parent::__construct();
}
public function ajaxPage()
{
echo '<form name="ajaxTest" type="POST">
<input id="ajaxButton" type="button" value="KLIK"/>
</form>
';
}
}
jQuery( document ).ready( function () {
jQuery('#ajaxButton').click(function() {
var dataFromFunction="";
jQuery.ajax({
url: my_ajax_object.ajaxurl,
type: 'POST',
data: {
action: 'save_sort',
order: dataFromFunction
},
success: function (response){
console.log("success message");
console.log(response.custom)
},
error: function (response){
console.log("error message");
}
});
});
} );
success message
ajaxScript.js?ver=5.0.4:15 undefined
Your code seems to be correct but I am sharing my personal approach to doing this in hopes that this might be helpful. Make changes to JS as mentioned below:
jQuery( document ).ready( function ($) {
$('#ajaxButton').click(function() {
var dataFromFunction="Test Data";
$.ajax({
url: my_ajax_object.ajaxurl,
type: 'POST',
data: {
action: 'save_sort',
order: dataFromFunction
},
}).done( function (response){
console.log("success message");
console.log(response.custom)
}).fail(function (response){
console.log("error message");
}).always(function(){
console.log('Ajax Completed');
});
});
});
Also for your script localization, it is good to define the scheme parameter in admin_url function but not necessary so 'ajax_url' => admin_url( 'admin-ajax.php') should be just fine.
You seem to have created nonce but haven't used it and a good practice would be to use create nonce function in your form section and not in localization.
I do have a suggestion for your ajax response function but this is just an advice. Change your function to return as follows:
function ajaxFunctionInPHP(){
$response['dataFromFunction'] = sanitize_text_field($_POST['dataFromFunction']);
wp_send_json( $response);
}
Good Luck!!

i got error (Error get data from ajax)

hi i am unable to call my ajax function in codeigniter , below is my script :
whenever i click edit button from my data table i got error (Error get data from ajax) , could u pls help me where i am doing wrong.
<script type="text/javascript">
var save_method;
function edit_question(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
// document.write("test");
//Ajax Load data from ajax
$.ajax({
// document.write("test");
url : "<?php echo base_url('index.php/test_cont/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="question_id"]').val(data.question_id);
// $('[name="cid"]').val("<?php //echo $a; ?>");
$('[name="cid"]').val(data.cid);
$('[name="ques"]').val(data.question);
// $('[name="opa"]').val(data.options);
// $('[name="opb"]').val(data.options);
// $('[name="opc"]').val(data.options);
// $('[name="opd"]').val(data.options);
$('[name="ra"]').val(data.answer);
$('[name="marks"]').val(data.marks);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Questions'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
i have a controller name test_cont , here's code :
public function ajax_edit($id)
{
$data = $this->m->get_by_id($id);
echo json_encode($data);
}
public function question_update()
{
$data = array(
'course_id'=>$this->input->post('cid'),
'question'=>$this->input->post('ques'),
'marks'=>$this->input->post('marks'),
'options' => $options,
'answer' => $this->input->post('ra'),
);
$this->m->question_update(array('question_id' => $this->input->post('question_id')), $data);
echo json_encode(array("status" => TRUE));
}

Wordpress: AJAX not working

I'm setting up a plugin. Now I'm trying to get an AJAX-PHP code working but I don't get the succeed data and all end with an error.
tracker.php is the main plugin file.
This is the function on my tracker.php that prints the title and some HTML code:
require_once dirname(__FILE__) . '/user-listing.php';
function trez_tracker_user_listing(){
?>
<h1>Tracker - User List</h1>
<div class="clicker">Click here</div>
<div id="printer"></div>
<?php
}//trez_tracker_user_listing
So in user-listing.php I added the following code:
function user_listing_enqueuer() {
wp_register_script( "ajax_user_request", WP_PLUGIN_URL.'/tracker/script/ajax_user_request.js', array('jquery') );
wp_localize_script( 'ajax_user_request', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'ajax_user_request' );
}
add_action( 'init', 'user_listing_enqueuer' );
function user_fetcher(){
$result = 'Message to display';
return $result;
}//user_listing
add_action("wp_ajax_user_fetcher", "user_fetcher");
And finally the javascript code in /script/ajax_user_request.js:
/* ajax_user_request.js */
jQuery(document).ready( function() {
jQuery(".clicker").click( function() {
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "user_fetcher"},
success: function(response) {
if(response.type == "success") {
jQuery("#printer").html(response)
}
else {
alert("AJAX error")
}
}//success
})//jQuery.ajax
})//Clicker function
})//document ready
When clicking on the <div>, I just get the alert message "AJAX error".
How can I fix it?
Thank you!
You are getting the error because you are not returning the JSON data, you are return string through your user_fetcher function.
function user_fetcher(){
$result = 'Message to display';
return $result;
}//user_listing
Change the user_fetcher function so that it will return the JSON data to the AJAX call.
function user_fetcher(){
$result = 'Message to display';
echo json_encode(array('type'=>'success', 'message'=>$result));
die(0);
}//user_listing
And in jquery check the response like this:
success: function(response) {
if(response.type == "success") {
// Add message
jQuery("#printer").html(response.message)
}
else {
alert("AJAX error")
}
}//success
For the hook wp_ajax_user_fetcher, make sure you are using this after logged in, if you are not logged in in the admin section then you have to use wp_ajax_nopriv_user_fetcher. Or you can use both:
// Work if user is login
add_action("wp_ajax_user_fetcher", "user_fetcher");
// Work if user is not login
add_action("wp_ajax_nopriv_user_fetcher", "user_fetcher");

Send ajax collected data to the current users database Wordpress

I am using WooCommerce and added an additional field "location_gps" to collect the location (lat,long) added the ajax call to collect the data. Now I'm stuck getting the data into the current users (user_meta).
Added this in funtions.php
// AJAX - implementation
function add_myscript(){
wp_enqueue_script( 'my-ajax.js', get_bloginfo('template_directory') . "/scripts/my-ajax.js", array( 'jquery' ) );
}
add_action( 'init', 'add_myscript' );
function myAjax(){
global $wpdb;
//get data from our ajax() call
$long = $_POST['long'];
$lat = $_POST['lat'];
$results = "<p>".$lat.", ".$long."</p>"; // this is how it supposed to land in the DB
if($wpdb->insert('location_gps',array(
'long'=>$long,
'lat'=>$lat,
))===FALSE){
echo "Error";
}
else {
echo "Successfully added, row ID is ".$wpdb->insert_id;
}
die();
}
// create custom Ajax call for WordPress
add_action( 'wp_ajax_nopriv_myAjax', 'myAjax' );
add_action( 'wp_ajax_myAjax', 'myAjax' );
Here the JS part..
jQuery(document).ready(function() {
jQuery("#save_loc_button").click(function(){
var long = jQuery("input#long").val();
var lat = jQuery("input#lat").val();
jQuery.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
data: { "action": "myAjax", "lat": lat, "long": long },
beforeSend: function(){
jQuery("#test-div").html('processing...');
},
success: function(event, request, settings){
jQuery("#test-div").html('');
jQuery("#test-div").append(event);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});

Resources