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>
	<div class="address_format"></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);
      url:'your controller url',

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:

      $fields = $_POST;
      $address = new Address((int)$fields['id']);
      $formated_address = $this->_getFormatedAddress($address, "<br>");
      echo $formated_address;

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
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x