How to update billing fields on Woocommerce checkout with AJAX - ajax

So, I want to unset a few billing fields depending on shipping method, however it doesn't work unless I reload the whole checkout page. How to reload the billing fields using AJAX?
/*
* Remove fields for chosen shipping method
*/
add_filter( 'woocommerce_checkout_fields', 'awoohc_override_checkout_fields' );
function awoohc_override_checkout_fields( $fields ) {
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
if ( 'local_pickup:4' === $chosen_methods[0] ) {
unset( $fields['billing']['billing_address_1'] );
unset( $fields['billing']['billing_address_2'] );
}
return $fields;
}

Related

Custom admin order button to add an item works, but item does not appear

Adding an item takes eight clicks, in the WC admin order page, so I thought I would add custom buttons for some of my most commonly-added products to do it all at once. I found several hints that get me most of the way there -- the item is indeed added to the order, but it doesn't appear until you reload the page, or hit Recalculate. Calling $('.calculate-action').trigger('click'); at that point does work but that requires yet another click ("OK"), an annoyance I am trying to avoid. The regular "Add Item(s)" and then "Add products" ... "Add" (with all the faffing about to select the product) just gets on with it at this point. How?
Is there a different approach, or maybe one more call I need to add?
scna_orderadmin_add_product.js:
(function( $ ) {
'use strict';
$('.inside').on('click','#scna_item_button', function(){
// get the order_id from the button tag
var order_id = $(this).data('order_id');
// get the product_id from the button tag
var product_id = $(this).data('product_id');
// send the data via ajax to the sever
$.ajax({
type: 'POST',
url: mb_script_var.ajaxurl,
dataType: 'json',
data: {
action: 'scna_orderadmin_add_product',
order_id: order_id,
product_id: product_id
},
success: function (data, textStatus, XMLHttpRequest) {
// if(data.error == 0)
// {
// trigger the "Recalculate" button to recalculate the order price
// and to show the new product in the item list
// $('.calculate-action').trigger('click');
// }
// show the control message
alert(data.msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
})( jQuery );
functions.php:
/** Add a custom button to the admin order page to add SCNA Membership.
*
* To save clicks when creating a new order from a paper form.
*/
function scna_orderadmin_add_product_buttons($order)
{
// Add a button that adds SCNA 1- and 2-year memberships, to save steps.
// the button tag gets as data attributes your product id and the order id
// later we will grab this data and send them to the server
echo '<button id="scna_item_button" type="button" class="button add-special-item" data-order_id="'. esc_attr($order->get_id()) .'" data-product_id="112" >Add SCNA 1-year</button>';
echo '<button id="scna_item_button" type="button" class="button add-special-item" data-order_id="'. esc_attr($order->get_id()) .'" data-product_id="113" >Add SCNA 2-year</button>';
}
/**
* hook to add the button
*/
add_action('woocommerce_order_item_add_action_buttons', 'scna_orderadmin_add_product_buttons');
/**
* Add javascript
*/
function scna_orderadmin_add_product_js_file()
{
wp_enqueue_script( 'scna_orderadmin_add_product_js', get_stylesheet_directory_uri() ."/js/scna_orderadmin_add_product.js", array('jquery'), NULL, true );
// send the admin ajax url to the script
wp_localize_script( 'scna_orderadmin_add_product_js', 'mb_script_var', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
/**
* hook to add the javascript file
*/
add_action( 'admin_enqueue_scripts', 'scna_orderadmin_add_product_js_file' );
/**
* Ajax callback
*/
function scna_orderadmin_add_product()
{
/////////////////////////////////////////////////////////////////////////////
/// Attention, to keep the example simple we will not check any ajax data. //
/////////////////////////////////////////////////////////////////////////////
//
// the data from the ajax call
$order_id = intval($_POST['order_id']);
$product_id = intval($_POST['product_id']);
//getting order Object
$order = wc_get_order($order_id);
// gettting the product
$product = wc_get_product($product_id);
$back_data = array('error' => 0, 'msg' => '');
if($order !== false AND $product !== false)
{
// Add the product to the order
$order->add_product($product, 1);
// Save the order data
$order->calculate_totals();
//$order->save();
$back_data['msg'] = 'The item was added';
}
else
{
$back_data['error'] = 1;
$back_data['msg'] = 'No item was added';
}
wp_send_json( $msg );
}
/**
* hook to add the ajax callback
*/
add_action( 'wp_ajax_scna_orderadmin_add_product', 'scna_orderadmin_add_product' );

Woocommerce apply discount to cart's total price with ajax

My Goal : Apply a 10% discount on total cart's price using AJAX.
The context : This discount must be applied only for specific users coming from a given website. The idea is to get their membership number in an input field I added in cart's page. With an API I will check this number and apply the discount or not (considering the issue explained further, I won't detail this checking part here and focus only with the problem).
The idea :
Create a plugin which will add an input field in cart's page with a validation button.
Make an AJAX call when the button is clicked
Apply discount if the user membership number is good (I won't deal with API checking here since it's not the problem)
The issue : So I'm using AJAX to validate this number and then apply a 10% discount on the total cart's price. The problem is I can't find how to update the total.
My JS:
(function($) {
$("body").on("click", ".updateCart", function(e) {
e.preventDefault();
var form = $('#cartAjaxTcs');
var value = form.serialize();
$.ajax({
type:'POST',
data: {
action: 'test',
number: value
},
url: ajaxurl,
success: function(value) {
jQuery("[name='update_cart']").removeAttr('disabled');
jQuery("[name='update_cart']").trigger("click");
console.log(value);
},
error:function(){
console.log('error');
}
});
});
})( jQuery );
My PHP:
<?php
/*
Plugin Name: discount Plugin
Description: Apply 10% discount on cart's price
Author: Aurélien
Version: 1.0.0
*/
/**
* Check if WooCommerce is active
**/
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
class Discount_Plugin{
public static function init() {
add_action('wp_enqueue_scripts', __CLASS__ .'::callback_for_setting_up_scripts');
//Add input field
add_action('woocommerce_cart_collaterals', __CLASS__.'::order_comments_custom_cart_field');
}
public static function callback_for_setting_up_scripts() {
$path = '/wp-content/plugins/discount-plugin/assets/css/style.css';
wp_register_style( 'discountStyle', $path );
wp_enqueue_style( 'discountStyle' );
wp_enqueue_script( 'ajax-script', plugins_url( 'assets/js/discount-plugin.js', __FILE__ ), array('jquery'), '1.0', true );
wp_localize_script( 'ajax-script', 'ajaxurl', admin_url( 'admin-ajax.php' ) );
}
public static function order_comments_custom_cart_field() {
?>
<form id="cartAjaxTcs" class="discount_input_wrapper" method="post" action="/wp-admin/admin-post.php">
<div class="discount_form_field">
<input type="text" name="number" id="number" placeholder="<?php echo 'My number, ie : 4GG524G42';?>">
<label for="number"><?php echo 'Membership number';?></label>
</div>
<button class="updateCart" type="submit"><?php echo 'Update cart';?></button>
</form>
<?php
}
Discount_Plugin::init();
add_action( 'wp_ajax_test', 'test' );
add_action( 'wp_ajax_nopriv_test', 'test' );
function test()
{
//Solution 1 or solution 2
}
}
My 1st solution : I tried to directly reduce total price like this. It changes the total price but not display it, even in backend cart's report where the total price is still the same than before discount.
function test()
{
//This is displayed in console
echo 'test-init';
if (!DOING_AJAX){
return;
}
$total = (int) WC()->cart->get_totals()['total'];
$total *= 0.9;
WC()->cart->set_total($total);
wp_die();
}
My 2nd solution:
I tried to trigger the "update cart" button (already present on the page) and use woocommerce_before_calculate_totals hook to update the price but it is not even called.
Obviously, no hook or filter are exectuted inside my AJAX's action function. I have tested with a simple filter to add a class to the body and it doesn't work inside my action function but works perfectly outside. I put some flags to see if my function was called by AJAX and it is!
//This works well! If I put the same filter in my 'test' function it doesn't work
add_filter( 'body_class', function( $classes ) {
return array_merge( $classes, array( 'test-class' ) );
} );
function test()
{
//This is displayed in console
echo'test-init';
if (!DOING_AJAX){
return;
}
//This does't work
add_filter( 'body_class', function( $classes ) {
return array_merge( $classes, array( 'test-class2' ) );
} );
//The callback function isn't called
add_action( 'woocommerce_before_calculate_totals', 'update_price' );
//This is displayed in console
echo 'test';
wp_die();
}
//Not called
function update_price(){
echo 'update';
}
EDIT :
I re-wrote my explanations to make them a bit more understandable with additional code:
Here are some tries with a negative fee try using woocommerce_cart_calculate_fees hook:
The callback function of woocommerce_cart_calculate_fees hook works perfectly if I use add_action outside of my AJAX action function like this :
add_action( 'wp_ajax_test', 'test' );
add_action( 'wp_ajax_nopriv_test', 'test' );
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
global $woocommerce;
if ( ( is_admin() && ! defined( 'DOING_AJAX' )))
return;
$percentage = 0.1;
$surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
$woocommerce->cart->add_fee( 'discount', -$surcharge, true, '' );
}
function test(){
//My AJAX action function
}
So this work, the negatif fee is applied but when the page is loaded and that's not what I would like since I want to apply the negative fee when I trigger update cart button, so the idea is to integrate the add_action inside my AJAX action function like this :
add_action( 'wp_ajax_test', 'test' );
add_action( 'wp_ajax_nopriv_test', 'test' );
function woocommerce_custom_surcharge() {
global $woocommerce;
if ( ( is_admin() && ! defined( 'DOING_AJAX' )))
return;
$percentage = 0.1;
$surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
$woocommerce->cart->add_fee( 'discount', -$surcharge, true, '' );
}
//My AJAX action function
function test(){
echo 'test1'; //flag 1
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
echo 'test2'; //flag 2
}
The callback function woocommerce_custom_surcharge isn't called at all. Both my flags are displayed in chrome console so it means my action function is correctly called. So my question is : how to make this add_action work inside my action function?
You missed the usage a WC Session variable to set some data and use it in your discount function… The First function below handle your settings and it's loaded everywhere on other functions.
// Settings
function get_membership_settings(){
$discount_percentage = 1; // the discount percentage: 1% here
return array(
'percentage' => $discount_percentage,
'field_key' => 'membership_number', // Field "name" key (or id)
'field_type' => 'text',
'field_label' => __('Membership number', 'woocommerce'),
'button_text' => __('Apply membership number', 'woocommerce'),
'discount_text' => sprintf( __('Membership discount%s', 'woocommerce'), ' ('.$discount_percentage.' %)' ), // for negative fee
'valid_message' => __('Number is valid (text message).', 'woocommerce'),
'unvalid_message' => __('Number not valid (text message).', 'woocommerce'),
'empty_field_text' => __('Please enter your membership number.', 'woocommerce'),
);
}
// Settings + Membership number
function get_membership_data(){
$settings = get_membership_settings();// Load settings
$field_key = $settings['field_key']; // The field Id
$user_value = get_user_meta( get_current_user_id(), $field_key, true ); // Get "membership number" from user data
$session_value = WC()->session->get($field_key); // Get "membership number" from session variable
// Set "membership number" in the array
$settings['field_value'] = empty($session_value) ? $user_value : $session_value;
return $settings;
}
The displayed field on cart (see the screenshot at the end):
// Display a text input field on cart (+ javascript)
add_action('woocommerce_cart_contents', 'display_field_membership_number', 100 );
function display_field_membership_number(){
extract(get_membership_data()); // Load data and settings
echo '<tr><td colspan="6" class="membership" style="padding:0;border-top:16px solid #FFF;">
<style>.message.off,label.hidden{display:none}.membership .message{margin-left:20px}</style>
<div id="'.$field_key.'-wrapper">
<label for="'.$field_key.'" class="hidden"> '.$field_label.' <abbr class="required" title="required">*</abbr></label>
<input type="'.$field_type.'" class="input-'.$field_type.'" name="'.$field_key.'" id="'.$field_key.'" placeholder="'.$field_label.'" value="'.$field_value.'">
<button type="button" class="button">'.$button_text.'</button>
<span class="message off"></span>
</div>
</td></tr>
<tr><td colspan="6" style="padding:0"></td></tr>';
}
The jQuery / Ajax code:
// Function that send the Ajax request | jQuery + Ajax
add_action('wp_footer', 'membership_number_js_script');
function membership_number_js_script() {
if( ! is_cart() ) return; // Only on cart
$field_key = get_membership_settings()['field_key']; // Load field key id
// jQuery Ajax code
?>
<script type="text/javascript">
jQuery( function($){
if (typeof woocommerce_params === 'undefined')
return false;
var s = '#<?php echo $field_key; ?>-wrapper';
$(s+' button').click( function(){
var value = $(s+' input').val();
// Function that handle the display of the message
function handleDisplayMessage( selector, response, error = false ) {
if ( ! error ) {
$.each( $.parseJSON(response), function(index, value){
displayMessage( selector, value, index );
});
} else {
displayMessage( selector, response, 0 );
}
}
// Function that display a message
function displayMessage( selector, response, type ) {
$(selector).hide('0').removeClass('off').html(response).css('color', (type == 1 ? '#03C03C' : '#DC143C')).show();
setTimeout(function() {
$(selector).hide();
}, 3000 );
}
$.ajax({
type: 'POST',
url: wc_cart_params.ajax_url,
data: {
'action': '<?php echo $field_key; ?>',
'<?php echo $field_key; ?>': value,
},
success: function (response) {
handleDisplayMessage( (s+' .message'), response );
$(document.body).trigger("added_to_cart"); // refresh cart
},
error:function(error){
handleDisplayMessage( (s+' .message'), ('A problem occured (error: '+error+')'), true );
}
});
});
});
</script>
<?php
}
The PHP WordPress Ajax receiver function:
// Get the ajax request and set value to WC session (and the field validation)
add_action( 'wp_ajax_membership_number', 'set_membership_number_and_validation' );
add_action( 'wp_ajax_nopriv_membership_number', 'set_membership_number_and_validation' );
function set_membership_number_and_validation() {
extract(get_membership_settings()); // Load and extract settings
if( isset($_POST[$field_key]) && ! empty($_POST[$field_key]) ) {
## HERE BELOW, SET YOUR CODE (that checks membership number for validation)
$validation = true; // "true" when validated (or false if not)
// Set membership number to a WC session variable
WC()->session->set($field_key, $_POST[$field_key]);
// Send response back
echo json_encode( ($validation ? [1 => $valid_message] : [0 => $unvalid_message]) );
} else {
// Send response back
echo json_encode( [0 => $empty_field_text] );
}
die();
}
The discount part:
there are multiple ways to make a discount (here are two of them, using different hooks):
1. Discount based cart subtotal + shipping tolal (negative fee):
// 1. Percentage discount for Membership (with a negative fee)
add_action( 'woocommerce_cart_calculate_fees', 'add_membership_discount' );
function add_membership_discount( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
extract(get_membership_data()); // Load and extract settings + membership numver
if( ! empty($field_value) ) {
// Calculation
$discount = ( $cart->get_cart_contents_total() + $cart->get_shipping_total() ) * $percentage / 100;
$cart->add_fee( $discount_text, -$discount ); // Add a discount
}
}
2. Discount on cart item price:
// 2. Percentage discount for Membership (on cart items price)
add_action( 'woocommerce_before_calculate_totals', 'add_membership_cart_item_discount' );
function add_membership_cart_item_discount( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
extract(get_membership_data()); // Load and extract settings + membership numver
if( ! empty($field_value) ) {
// Loop through cart items
foreach( $cart->get_cart() as $cart_item ){
// Get the real WC_Product Object
$product = wc_get_product($cart_item['data']->get_id());
$price = $product->get_price(); // The real product price
$discounted_price = $price * ( 1 - ( $percentage / 100 ) ); // Calculation
$cart_item['data']->set_price($discounted_price); // Set the discounted price
}
}
}
All code goes in functions.php file of your active child theme (or active theme). Tested and works.
Similar threads:
First order discount for guest customers checking Woocommerce orders billing email
Dynamic discount using AJAX and Fee API in Woocommerce checkout page

codeigniter pagination - how to keep on same page after deleting row

I am using codeigniter pagination library and doing update and delete through form. The problem is when I delete or update any record after delete or update I redirected back to 1st page even if I am at 4th page. How I can redirected to the same page at which I have done update or delete.
Here is my controller code for update and delete functions:
public function update_att(){
if(isset($_POST['update'])){
$u_id = $_POST['at_id'];
if($_POST['status']=="Present"){
$data = array(
'status'=>"Absent"
);
$this->db->where('at_id', $u_id);
$this->db->update('attendence', $data);
}elseif ($_POST['status']=="Absent") {
$data = array(
'status'=>"Present"
);
$this->db->where('at_id', $u_id);
$this->db->update('attendence', $data);
}
redirect("usr/att_list", "refresh");
}
}
public function delete_att(){
if (isset($_POST['delete'])) {
$at_id = $_POST['at_id'];
$this->db->where('at_id', $at_id);
$this->db->delete('attendence');
}
redirect("usr/att_list" );
}
Currently I am redirecting to the first page , any suggestion how I redirect to that page where I have done delete or update.
Add <input type='hidden' name='current_page' value='<?php echo $current_page?>' /> to your form.
Keep in mind you need to populate $current_page with something like
$current_page = ''; // empty means first page
if( isset($_REQUEST['current_page'] ){
$current_page = $_REQUEST['current_page'];
}
Then based on your sample you just modifiy the redirect path as follows (for both your functions):
public function delete_att(){
if (isset($_POST['delete'])) {
$at_id = $_POST['at_id'];
$this->db->where('at_id', $at_id);
$this->db->delete('attendence');
}
redirect("usr/att_list".(strlen($current) ? "?".$current : "" );
}
Note:
Your path to your page should look something like this domain.com/controller/your_page_with_pagination/?current_page=A_NUMBER then in your controller/your_page_with_pagination you adjust the data you wish to output based on $_GET['current_page']
Edit based on your link:
public function att_list($id = ""){
/**
* Keep your data in array
*/
$this->data = array();
/**
* Add the page number ($id) to the array
* Check for url /:id first , or else check for a $_GET/$_POST current_page (this will be triggered when you submit your form)
*/
$this->data['current_page'] = is_numeric($id) ? $id : (isset($_REQUEST['current_page'] ? $_REQUEST['current_page']: 0);
/**
* This is your 'keep on the same page' line
* $this->data['current_page'] will act as an offset in your query
* You can read about 'offset' here https://www.w3schools.com/php/php_mysql_select_limit.asp
* $this->data['my_desired_records'] must be generated into your <form> ... </form> , and the same form must contain the input with name='current_page'
*/
$this->data['my_desired_records'] = $this->your_model->get_data($this->data['current_page']);
/**
* Pass the whole array into your view
*/
$this->load->view('path/to/view', $this->data);
}
Then in your view add in your form <input type='hidden' name='current_page' value='<?php echo $this->data['current_page']?>' />

why is my ajax function not working as expected?

so my class looks like this:
class Myclass{
private $nonce;
public function __construct(){
if( get_current_screen()->id == 'nav-menus' ){
$this->nonce = 'my-plugin-nonce';
}
add_action( 'wp_ajax_run_action', array( $this, 'run' ) );
wp_localize_script(
'my-script',
'my_script',
array( 'nonce' => wp_create_nonce( $this->nonce ),
'ajaxurl' => admin_url('admin-ajax.php'),
)
);
}
public function run(){
if( ! wp_verify_nonce( $_POST['nonce'], $this->nonce ) )
return false;
wp_send_json_success();
}
}
new Myclass;
And here is the javascript code:
$.ajax({
type: 'POST',
dataType: 'json',
url: my_script.ajaxurl,
data: {
'action': 'run_action',
'nonce' : my_script.nonce,
},
complete: function( object ) {
console.log( object.responseJSON )
}
});
The problem is that when i try to call the run_action action from within my javascript ajax function it does not return true as it should.
Note that i have properly localized my script and any data contained in the object is being rendered correctly.
Why is that happening ?
Localization of the script must be done on the pages you are including the script on (ie. on the nav-menus.php admin page in this case) - you do not include the code that actually enqueues your javascript, but the code you did post suggests to me that you are actually attempting to localize the script in the ajax-call itself - which won't work.
I've rearranged your code below and added comments to explain each change:
class Myclass {
/**
* No reason not to assign this already (and I've renamed it to explicitly,
* let people reading the code know that it is not the nonce itself, but the
* name of the nonce action - fooled me for a minute or two :p
*/
private $nonce_action_name = 'my-plugin-nonce';
/**
* The __construct function is great for hooking everything you need to
* hook, and for setting initial variables. Pretty much anything else
* should NOT be in this function though!
*/
public function __construct(){
// Register your ajax action.
add_action( 'wp_ajax_run_action', array( $this, 'run' ) );
// Hook into the appropriate action for admin scripts
add_action( 'admin_enqueue_scripts', array( $this, 'scripts' ) );
}
public function scripts() {
/**
* I've negated your if-statement here - basically we don't want to do
* anything at all if we are not on the correct page - which is clearer
* this way - also you had it in the __construct function, which will
* actually produce a fatal error, since get_current_screen is not
* usually defined yet at that point(!)
*/
if( get_current_screen()->id !== 'nav-menus' ){
return;
}
//Now enqueue (or register) the script
wp_enqueue_script('my-script', plugins_url('/my-script.js', __FILE__));
//Then localize it
wp_localize_script(
'my-script',
'my_script',
array(
'nonce' => wp_create_nonce( $this->nonce_action_name ),
'ajaxurl' => admin_url('admin-ajax.php'),
)
);
}
/**
* Actual ajax handler
*/
public function run(){
if( ! wp_verify_nonce( $_POST['nonce'], $this->nonce_action_name ) ) {
//This is a guess, but I think you'll want to wp_send_json_error
//here to match up with your success below
wp_send_json_error();
} else {
wp_send_json_success();
}
/**
* Always recommended to explicitly die() after handling ajax - though
* the wp_send_json_* family probably does it for you.
*/
die();
}
}
new Myclass;
A final note is that ajaxurl is actually always defined in the admin, so you don't really need to add that to your localization (though it only hurts by adding a few extra bytes).
Note from the codex:
wp_localize_script() MUST be called after the script has been registered using wp_register_script() or wp_enqueue_script().
So your workflow should be as follows:
Register script
Localize it
Enqueue your localized script.
Tie it to appropriate action: wp_enqueue_scripts or admin_enqueue_scripts
For example:
Add action to your __construct method:
add_action('wp_enqueue_scripts', array($this, 'registerAjaxScript'));
Then create a method that registers and localizes your script:
function registerAjaxScript() {
wp_register_script('my-script',
string $src,
array $deps,
string or bool $ver,
bool $in_footer
);
wp_localize_script('my-script',
'my_script',
array( 'nonce' => wp_create_nonce( $this->nonce ),
'ajaxurl' => admin_url('admin-ajax.php'),
)
);
}

magento rest api create method return

I make an rest api module for shiping and order with carrier and tracking code.
The problem is when i cal the method _created() -(Post) it doesn't return any value. I dont know if the function allow returns or not.
This is my create function
protected function _create($orderData)
{
$orderId = $this->getRequest()->getParam('order_id');
if($orderData['incrementId']){
$incrementId = $orderData['incrementId'];
}else{
$cModel = Mage::getModel('sales/resource_order');
$incrementId = $cModel->getIncrementId($orderId);
}
$order = Mage::getModel('sales/order')
->getCollection()
->addAttributeToFilter('state', array('neq' => Mage_Sales_Model_Order::STATE_CANCELED))
->addAttributeToFilter('increment_id', $incrementId)
->getFirstItem();
if ($order->hasData()) {
if($order->canShip()){
$shipment = new Mage_Sales_Model_Order_Shipment_Api();
$shipmentId = $shipment->create($incrementId);
$trackid = $shipment->addTrack($shipmentId, 'custom', 'ups', '#111111' );
return $shipmentId;
}else{
$this->_critical(self::RESOURCE_NOT_FOUND);
}
}else{
$this->_critical(self::RESOURCE_NOT_FOUND);
}
//return null;
}
The api call:
$resourceUrl = "$apiUrl/shipping/order/1?type=rest";
$oauthClient->fetch($resourceUrl, json_encode($orderData), 'POST', $headers);
print_r($oauthClient->getLastResponse());
I dont know why the response comes empty, even if i errase all the content of the function and just return a value, its comes empty.
Any idea for it?
The answer R.S said is for SOAP instead of REST. You definition is correct.
The return of create is a URL which will appear in http header "location". It is not a valid way to show response for _create event. If you want to response something, you should use _multicreate
if you want to add response data in _multicreate you should use
$this->getResponse ()->addMessage ( "", 0, array (
'id' => $quote->getId ()
), Mage_Api2_Model_Response::MESSAGE_TYPE_SUCCESS );
And you should retrieve the URL in location to receive the correct things.
Use this code to get URL correctly.
$this->_getLocation ( $quote )
Another tricky is you can set the header to make it force redirect
$this->getResponse ()->setRawHeader ( '"Content-Type" = "application/json"' );
However, at this time, only if the magento install in the root of your domain, or the url will be wrong.
Hence you can use some code not good but make things work.
The final code is
$this->getResponse ()->setRawHeader ( '"Content-Type" = "application/json"' );
$base_url = Mage::getBaseUrl ( Mage_Core_Model_Store::URL_TYPE_WEB );
$base_url = substr ( $base_url, 0, strlen ( $base_url ) - 1 );
return $base_url . $this->_getLocation ( $order );
Take a look # Creating a custom API or extending the Core API
Shouldn't your create method be
public function create($customerData){
....

Resources