How To Get Customer Address Through AJAX Prestashop

As you maybe already know you can do a lot of things un prestashop being built on a MVC framework you have all the control you need in this CMS.  This tutorial will try to show how can you get customer address through ajax in prestashop. You will see is nothing complicated you will have only to write few lines of code to make it working. First of all we will need the javascript ajax action, and in our example we will use a select when a select is changed by the client to select a new address we will trigger our function and we will send a $_POST request to our controller and then send back the customer address.

Create ajax function in jquery

First of all we need the select so we will use the following html:

<div class="selectRequired">
	<select id="address_">
		<option value="1">First Addres</option>
		<option value="2">Second Address</option>
		<option value="3">Third Address</option>
	</select>
	<div class="address_format"></div>
</div>

 

Then the javascript change event is the following:

jQuery('.addresses_select').on('change2', function(e){
    var address_id = jQuery(this).val(),
      _this = jQuery(this);
    jQuery.ajax({
      type:"POST",
      url:'your controller url',
      data:{
        'id':address_id,
        'get_address':'1'
      },
      success:function(result){
        _this.closest('.selectRequired').find('.address_format').html(result);
      },
      error:function(error){
        
      }
    })
  });

On change event is triggered we get the id from selected option, and then send it the the controller, when success function is called we just append the html we just received from controller in address_format div and that's it. 

The php function for this should look like the following:

if(Tools::isSubmit('get_address')){
      $fields = $_POST;
      $address = new Address((int)$fields['id']);
      $formated_address = $this->_getFormatedAddress($address, "<br>");
      echo $formated_address;
      exit();
    }

In the above function we just create a new address object based on the id which was received thourgh ajax and use the prestashop's function _getFormatedAddress() to format the address and then send it back to our ajax function in order to be added in html.

This is function _getFormatedAddress

protected function _getFormatedAddress(Address $the_address, $line_sep, $fields_style = array())
    {
        return AddressFormat::generateAddress($the_address, array('avoid' => array()), $line_sep, ' ', $fields_style);
    }

These are all steps you need to complete to to get customer address through ajax.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x