getherbert / herbert

The WordPress Plugin Framework:
http://getherbert.com/
632 stars 94 forks source link

Sending ajax request to admin . #92

Closed PrafullaKumarSahu closed 8 years ago

PrafullaKumarSahu commented 8 years ago

I need to send some request to admin-ajax.php page, actually those data will be processed in AdminController@postStatusUpdate method ,

I tried using route something like this:-

function changeStatus(post){
    console.log(post);
    var selectedPosts = [];
    selectedPosts.push(post);
    //console.log(selectedPosts);
    var data = {
        selected_posts: selectedPosts,
        action: 'postStatusUpdate',
        //whatever: ajax_object.we_value
    };
    //jQuery.post(ajax_object.ajax_url, data, function(response){
    jQuery.post( 'http://localhost/test/wp-admin/admin.php?page=analytica-admin-settings/changeStatus', data, function(response){
        console.log( response );
    });
}

and in route.php


$router->get([
    'as'   => 'userProfile',
    'uri'  => panel_url('Analytica::mainPanel') . '/changeStatus',
    //'uses' => __NAMESPACE__ . '\Controllers\UserController@postStatusUpdate'
    'uses' => function(){
        echo 'abc';exit;
    }
]);

this does not worked.

error:- POST http://localhost/test/wp-admin/admin.php?page=analytica-admin-settings/changeStatus 403 (Forbidden)

then I thought of doing it in wordpress way, in app/actions.php

add_action( 'admin_menu', function(){
    add_action('admin_print_scripts-' . $hook_suffix, 'analytica_admin_script');
});

function analytica_admin_script(){
    wp_enqueue_script( 'analytica');
}

add_action( 'admin_init', function(){
    wp_localize_script( 'analytica', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234) );  
}); 

this does not gives me ajax_object in my js file .

Can you please guide me here.

jasonagnew commented 8 years ago

You’ve got confused between the router (front-end) and the panels (admin area)

Add post panel https://github.com/bigbitecreative/wordpress-git-content/blob/master/app/panels.php#L12

Handle save https://github.com/bigbitecreative/wordpress-git-content/blob/master/app/Controllers/AdminController.php#L24,L37

Form action https://github.com/bigbitecreative/wordpress-git-content/blob/master/resources/views/admin/index.twig#L7

PrafullaKumarSahu commented 8 years ago

@jasonagnew thank you so much, I hope you are doing well, I am thinking I can answer some question posted here, I have tried to answer one, I will learn a lot from it, I think so .

PrafullaKumarSahu commented 8 years ago

@jasonagnew sorry but what you have provided me I got it good, that when I am sending some data to admin, I should use panel and when I am sending to front-end I should use route, now, I am already using

$panel->add([
    'type' => 'panel',
    'as'   => 'mainPanel',
    'title' => 'Analytica',
    'rename' => 'General',
    'slug' => 'analytica-admin-settings',
    'icon' => 'dashicons-chart-area',
    'uses' => __NAMESPACE__ . '\Controllers\AnalyticaController@index', //displaying page
    'post' => __NAMESPACE__ . '\Controllers\AnalyticaController@save',   //data send from form when submit there is two submit working fine as the forms are displayed in different condition.
        /**
       *  It does not seems I will be doing something like this !!!!
       *   'post' => __NAMESPACE__ . '\Controllers\AnalyticaController@postStatusChange',
       */
]);

but when I am sending data to the same controller method with post request, using ajax, how I can give to uri to ajax request and how I can specify another method for post request here ?

I am trying to use put or patch , I do not think a good idea, but I know when you will be replying , I can only put myself trying whatever ideas comes to my mind .

jasonagnew commented 8 years ago

There two ways to do this, you could use PUT/PATCH, or use actions.

1) PUT or PATCH

$panel->add([
    'type' => 'panel',
    'as'   => 'mainPanel',
    'title' => 'Analytica',
    'rename' => 'General',
    'slug' => 'analytica-admin-settings',
    'icon' => 'dashicons-chart-area',
    'uses' => __NAMESPACE__ . '\Controllers\AnalyticaController@index', 
    'post' => __NAMESPACE__ . '\Controllers\AnalyticaController@save',  
    'put'  => __NAMESPACE__ . '\Controllers\AnalyticaController@postStatusChange',
]);
// Build fields
var fields = [];

//Switch method to PUT
fields['_method'] = 'put'

//Build URL - could pass this from PHP
var url = '/wp-admin/admin.php?page=analytica-admin-settings';

//Send request
$.ajax(url, {
  contentType : 'application/json',
  dataType: 'json',
  data: JSON.stringify(fields),
  type: 'POST',
  success: function(data) {
  }
  failure: function(errMsg) {
  }
});

2) Actions

$panel->add([
    'type' => 'panel',
    'as'   => 'mainPanel',
    'title' => 'Analytica',
    'rename' => 'General',
    'slug' => 'analytica-admin-settings',
    'icon' => 'dashicons-chart-area',
    'uses' => __NAMESPACE__ . '\Controllers\AnalyticaController@index', 
    'post' => [
      'save' => __NAMESPACE__ . '\Controllers\AnalyticaController@save',  
      'status-change' => __NAMESPACE__ . '\Controllers\AnalyticaController@postStatusChange',
    ]
]);
// Build fields
var fields = [];

//Build URL - could pass this from PHP
var url = '/wp-admin/admin.php?page=analytica-admin-settings&action=status-change';

//Send request
$.ajax(url, {
  contentType : 'application/json',
  dataType: 'json',
  data: JSON.stringify(fields),
  type: 'POST',
  success: function(data) {
  }
  failure: function(errMsg) {
  }
});
PrafullaKumarSahu commented 8 years ago

@jasonagnew You are awesome :) I am using the second one, as I will need the first one also , there is a lot of wired things you will notice in my plugin, I am asked to use one controller and one template , that is you may find it making herbert dirty ( may be not a really good use of Herbert ), as the controller can be still divided and I could have use a model .any way, after this tomorrow, I will be adding ajx pagination and it should be over. thank you so much.

giwrgos88 commented 8 years ago

@jasonagnew if you use the second option (actions) that means in postStatusChange in order to return a json array or object you have to used the wordpress way

echo json_encode($result, JSON_FORCE_OBJECT);
    die();

or there is a better way? I saw in the framework there is a class JsonResponse, I tried to use it but is not working like this way return new JsonResponse("testing");

jasonagnew commented 8 years ago

@giwrgos88 return new JsonResponse(); would only work on a route (option 1) as a panel (option 2) has a lot of dashboard code inserted before we can output meaning even if you did your idea:

echo json_encode($result, JSON_FORCE_OBJECT);
die();

You could very well end up with none json data being passed before your json string. Therefore I would stick with routes and check if the user is logged and is a admin before return the json.

giwrgos88 commented 8 years ago

@jasonagnew I see ok thanks a lot I will use then the first method, thanks a lot